Home > Blockchain >  How to init provider?
How to init provider?

Time:02-11

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 :)

CodePudding user response:

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();

}
  • Related