How to solve: Singleton pattern with uninitialized argument error

Question

Asked by Ahmed O on December 23, 2021 (source).

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;
  }

Answer

Question answered by Guillaume R (source).

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

DART FLUTTER
SHARE: