Flutter:从main()方法更改小部件的状态

时间:2020-03-19 08:25:52

标签: flutter

我正在尝试从Hive存储中读取数据,读取完成后,我需要更新类_MyAppState的状态。 访问Hive是在main方法中完成的,因为初始化的Hive框也将在其他类中访问。

我写的代码如下。我需要的是在读取完成后从main()方法更新_loading类的变量_MyAppState

void main() async {
  var _dataReadFromHive = {};

  runApp(MyApp());


  final appDocDir = await path_provider.getApplicationDocumentsDirectory();
  await Hive.init(appDocDir.path);

  //read data from hive
  Hive.openBox('data').then((status){
   var box = Hive.box('data');
   //read data
   //after reading, update the state of MyAppState class

  });
}

...

class _MyAppState extends State<MyApp>{
    var _loading = true;

    Widget build(BuildContext context){
        return Material(
            child:Center(
                child : _loading ? CircularProgressIndicator() : Text("Loaded"),
            ),
        );
    }
}

请帮助我。我尝试过GlobalKey,但是我缺少了一些东西(我是一个步步高升的菜鸟)。

谢谢。

1 个答案:

答案 0 :(得分:0)

您不从主功能更新状态。 如代码中所示,从initState调用您的函数,然后从那里更新应用程序的状态。

我希望这会有所帮助。


void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  MyApp({Key key}) : super(key: key);

  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  var _loading = false;

  @override
  void initState() {
    readDataFromHive();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Material(
      child: Center(
        child: _loading ? CircularProgressIndicator() : Text("Loaded"),
      ),
    );
  }

  void readDataFromHive() async{
    setState(() {
      _loading = true;
    });
    final appDocDir = await path_provider.getApplicationDocumentsDirectory();
    await Hive.init(appDocDir.path);

    //read data from hive
    Hive.openBox('data').then((status) {
      var box = Hive.box('data');
      //read data
      //after reading, update the state of MyAppState class
      setState(() {
        _loading = false;
      });
    });
  }
}
相关问题