我做了一個小應用程式,設計如下:
return MultiProvider(
providers: [
ChangeNotifierProvider(create: (context) => AModel()),
ChangeNotifierProvider(create: (context) => BModel(),),
ChangeNotifierProvider(create: (context) => CModel(),),
]
首先,需要在 CModel 中初始化配置資料,然后移動到 AModel 并添加詳細資料,在 A 頁面中如下所示:
Widget build(BuildContext context) {
AModel aModel = Provider.of<AModel>(context);
CModel cModel = Provider.of<CModel>(context);
添加詳細資料后,一切順利,日志:
build aModel.chosenData.length 1 build cModel.chosenData.length 0
build aModel.allConfigs.length 0 build cModel.allConfigs.length 1
強制停止應用重新打開后,A頁面崩潰,日志變為:
build aModel.chosenData.length 1 build cModel.chosenData.length 0
build aModel.allConfigs.length 1 build cModel.allConfigs.length 0
我糟糕的設計提出了這個問題,有什么辦法可以避免這種尷尬的情況嗎?
uj5u.com熱心網友回復:
很難用這些資訊給出準確的答案,但如果提供者依賴于另一個提供者,您可以嵌套它們,或從第三個小部件控制它們,這可能會對您有所幫助。
如果 A 依賴于 C 然后構建小部件,如
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/468637.html
