How to init provider?

Issue

The case is: i am going to use MyProvider in the following way SomeProvidersClass.get().myProvider; from this structure:

class SomeProvidersClass {
late final myProvider =
    Provider((ref) => MyProvider());

MyProvider get myProvider =>
    read(providers.myProvider);
}

But
i heed to MyProvider be initialized via some async function;
so i tried to do it in the following way:

class MyProvider {
  late final SomeType _someVariable; // need to init in async way

  Future<void> init() async => _someVariable = await SomeType.getInstance();

  MyProvider();

  // example of content of this provider that i am going to use
  dynamic? getSmth() => _someVariable.getSmth();

}

and i got the following error

LateInitializationError: field has not been initialized;

Could you suggest me any approach to do it? i am new in riverpod and providers 🙂

Solution

Try this:

class MyProvider {
  SomeType? _someVariable; // need to init in async way

  Future<void> init() async => _someVariable = await SomeType.getInstance();

  MyProvider(){
    init();
  }

  // example of content of this provider that i am going to use
  dynamic? getSmth() => _someVariable?.getSmth();

}

Answered By – Josteve

Answer Checked By – Terry (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *