如何解决当 Flutter 应用程序加载时执行 Mobx 商店操作
我在 Mobx
应用中使用 Flutter
来管理我的状态。书面存储操作用于从本地存储中获取数据并添加到我的 Mobx
存储中。为此,我需要在每次应用加载时执行该操作,以便在应用加载完成后用户可以使用数据。
我已经试过了。但我无法访问 initState()
中的上下文。
class Navigation extends StatefulWidget {
@override
_NavigationState createState() => _NavigationState();
}
class _NavigationState extends State<Navigation> {
int currentIndex = 0;
final studentStore = Provider.of<StudentStore>(context); // Here I can't access context
@override
void initState() {
super.initState();
studentStore.addExistingData(); // This is where I'm trying to execute action
}
changeRoute(index) {
setState(() {
currentIndex = index;
});
}
@override
Widget build(BuildContext context) {
List<Widget> _widgetoptios = <Widget>[
WelcomeScreen(),Reports(),Text("History"),Text("Settings"),];
return Scaffold(
body: SafeArea(child: _widgetoptios.elementAt(currentIndex)),bottomNavigationBar: BottomTabNavigationBar(
currentIndex: currentIndex,onTap: changeRoute),);
}
}
解决方法
didChangeDependencies 是上下文第一次可用的方法。在 initState 之后,在加载所有依赖项之后。
late StudentStore _studentStore;
@override
void initState() {
super.initState();
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
_studentStore = Provider.of<StudentStore>(context); // you can get context here
// access your methods
_studentStore.addExistingData();
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。