0

Below is a simple class which i want to wrap dio class is singleton, as i enabled analyzer i get this error:

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

my code:

const baseApiUrl = 'http://localhost';

class BaseDio {
  BaseDio._();

  static BaseDio _instance;

  static BaseDio getInstance() {
    return _instance;
  }

  final cacheManager = DioCacheManager(CacheConfig(baseUrl: baseApiUrl));
  final BaseOptions options = BaseOptions(
    connectTimeout: 20000,
    receiveTimeout: 30000,
  );

  Dio getDio() {
    final dio = Dio(options)
      ..interceptors.addAll(
        [

          PrettyDioLogger(
            requestHeader: true,
            requestBody: true,
            responseBody: true,
            responseHeader: false,
            compact: false,
          ),

          cacheManager.interceptor as Interceptor,
          LogInterceptor(responseBody: false),
        ],
      );

    return dio;
  }
}

how can i resolve this problem for analyzer ?

2 Answers 2

1

You can use a factory method to create a singleton in Dart:

class BaseDio {
  static final BaseDio _singleton = BaseDio._internal();
  final int value = 42;

  factory BaseDio() => _singleton;

  BaseDio._internal() {
    // private constructor that creates the singleton instance
  }
}

final baseDioSingleton = BaseDio();
print(baseDioSingleton.value);
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, how can i access to _singleton from outside of this class now? for example BaseDio.getInstance().getDio()
The factory method call BaseDio() returns the _singleton value. The last string in the example code illustrates that
0

Non-nullable instance field '_instance' must be initialized.

Add a value to _instance or make it nullable:

BaseDio _instance = someValue;

or

static BaseDio? _instance;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.