'How to use the data from different model and context?

I made the small app, and designed like this:

return MultiProvider(
     providers: [
         ChangeNotifierProvider(create: (context) => AModel()),
        ChangeNotifierProvider(create: (context) => BModel(),),
         ChangeNotifierProvider(create: (context) => CModel(),),
       ]

at first, need initialize config data in CModel, then move to AModel and add detailed data, in the A page like this:

Widget build(BuildContext context) {
     AModel aModel = Provider.of<AModel>(context);
     CModel cModel = Provider.of<CModel>(context);

after add the detailed data, anything goes well and the log:

 build aModel.chosenData.length 1   build cModel.chosenData.length 0  
 build aModel.allConfigs.length 0   build cModel.allConfigs.length 1

after force stop the app and re-open, the A page is crashed, and the log becomes:

build aModel.chosenData.length 1   build cModel.chosenData.length 0  
 build aModel.allConfigs.length 1   build cModel.allConfigs.length 0

My terrible design raised this issue, is there any solution to avoid this embarrassed situation ?



Solution 1:[1]

Very difficult to give an accurate answer with this info but if a provider depends on another, you can nest them, or control them from a third widget, and that may help you.

If A depends on C then build the widgets like

WidgetA build(BuildContext context) {
 AModel aModel = Provider.of<AModel>(context);
 

WidgetC build(BuildContext context) {
 AModel aModel = Provider.of<AModel>(context);
 

WidgetMain build(BuildContext context) {
 -- Do things with C
 -- When get a result from C do things with A.
 -- Be careful to validate the state here, you can use didChangeAppLifecycleState(AppLifecycleState state) to check closing of the app

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 0ver0n