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

  }