Home > Back-end >  Non-nullable instance field '_dio' must be initialized Flutter
Non-nullable instance field '_dio' must be initialized Flutter

Time:12-31

I am using Dio for Json parsing and i have created a class for simple Json parsing and serializing but i am getting the following error


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

Below is the code for my class


Dio _dio;

  final baseUrl = "";

  HttpService(){
    _dio = Dio(BaseOptions(
      baseUrl:
    ));
  }

What might i be doing wrong

CodePudding user response:

Your variable _dio is non-nullable which means it can never be null. However when you put Dio _dio; it doesn't get a value.

You have 2 options:

Either make it nullable by putting a ? after the type: Dio? _dio;

or make it a late variable late Dio _dio; which means that it will shortly after get a value (hopefully _dio = Dio(BaseOptions(baseUrl:)); will do so) so that it can be treated as "never null" afterwards.

EDIT: More on that topic: https://dart.dev/null-safety

  • Related