Provider: How to do some init actions ?

Created on 16 May 2019  路  4Comments  路  Source: rrousselGit/provider

such as: in my app, i need to request some configs from server(maybe several apis), but this function(which combined these apis, but these child functions are in different providers/states) should be called exactly only once. so what's the correct way to do with it? because of build and didChangeDependencies function may called multi times, so i can't call init in these function, but in initState, the 'listen' parameter can only be 'false' and this will throw exception if i call multi different child function.

Examle:

i have A,B states

in A:
class AStates with ChangeNotifier {
...
appInit() async{
...
childInitFunc1();
childInitFunc2();
childInitFunc3();
// if i call initB it will throw exception whatever listen is true or false
Provider.of(context,listen:false).initB();
}
...
}

in B:
class BStates with ChangeNotifier {
...
initB() async{
...
}
...
}

in index.dart:
class Test extends StatefulWidget {
@override
_TestState createState() => _TestState();
}

class _TestState extends State with WidgetsBindingObserver {
@override
void initState() {
//
// init here and if listen is true, it will throw exception
//
Provider.of(context, listen:false).appInit(state);
WidgetsBinding.instance.addObserver(this);
super.initState();
}

@override
void didChangeDependencies() {
// can't init here
super.didChangeDependencies();
}

@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
super.dispose();
}

@override
void didChangeAppLifecycleState(AppLifecycleState state) {
Provider.of(context).changeAppLifecycleState(state);
super.didChangeAppLifecycleState(state);
}

@override
Widget build(BuildContext context) {
// can't init here
return Container();
}
}

so what's wrong with my code? and what should i do correctly ?

All 4 comments

use Future.delay in initState like this https://github.com/rrousselGit/provider/issues/61
I tried an succeeded

@datvtwkm no.
There's a reason for these exceptions, and while sometimes using a Future this way may be the solution, that is not always the case.

@guopeng1994 widgets lifecycles can't be used to modify a provided value.
The value returned by Provider.of is supposed to be immutable.

If there's something to initialize, it should be done directly on the constructor of your model.

@rrousselGit thanks! i'll try that, hope this going to be work.

Closing it since it is answered.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

Alfie-AD picture Alfie-AD  路  4Comments

wemped picture wemped  路  5Comments

stocksp picture stocksp  路  5Comments

dikir picture dikir  路  5Comments

MaxTenco picture MaxTenco  路  5Comments