-1

I've applied the singleton pattern as in this issue and tried to accept a parameter using the method in this issue. But it gives me this error:

Non-nullable instance field 'id' must be initialized. Try adding an initializer expression, or add a field initializer in this constructor, or mark it 'late'

So where is the issue?

Here is my code:

  static final Singleton _inst = Singleton._internal();
  int id;
  Singleton._internal() {
    // some logic 
  }

  factory Singleton({required int id}) {
    _inst.id = id;
    return _inst;
  }
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Ahmed Osama
  • 672
  • 1
  • 8
  • 15

2 Answers2

0

Without your full code I am going to assume that your full Singleton class looks something like this:

class Singleton {
  int id;

  static final Singleton _inst = Singleton._internal();

  Singleton._internal() {
    // some logic
  }

  factory Singleton({required int id}) {
    _inst.id = id;
    return _inst;
  }
}

The thing is that since nullsafety you can't declare a non-nullable variable without assigning its value or mark it as late (just as said in your error message).

So what you should do is simply declare id like this:

class Singleton {
  late int id;

  // ...
}

Try the full sample on DartPad

Guillaume Roux
  • 6,352
  • 1
  • 13
  • 38
-2

In your People or Singlton class you have defined a field named id which is neither nullable nor initialized that is why you are getting this error. Just make your field nullable or assign some value to it to initialize. Like below

To make it nullable

   int? id; 

To initialize

  int id = "";
Diwyansh
  • 2,961
  • 1
  • 7
  • 11
  • 1
    Using the `late` keyword is much better as it will allow `id` to be non-nullable and he won't need to have an initialized value. – Guillaume Roux Dec 23 '21 at 10:05
  • I think we should let the user decide their need rather then being judge and one more thing you voted down my answer but it's not wrong just you have a different point of view I'll suggest you to now to misuse your rights – Diwyansh Dec 23 '21 at 10:12