简体   繁体   English

如何初始化一个 Future,然后在 Flutter/Dart 中替换它?

[英]How to initialize a Future and then replace it in Flutter/Dart?

How do I do the initialize the Future correctly for a FutureBuilder in Flutter?如何在 Flutter 中为 FutureBuilder 正确初始化 Future? As you can see, there is an exception being thrown because the late Future is not yet initialized.如您所见,由于后期 Future 尚未初始化,因此引发了异常。 (please ignore that parameter v is not used in the method, removed method details for simplicity, but v is important). (请忽略该方法中未使用参数 v,为简单起见删除了方法细节,但 v 很重要)。

late Future<int> myIntvalue;

Future<int> getStackInit(int v) async {
  await Future.delay(Duration(seconds: 5));
  return 5;
}

@override
void initState()
{
  SharedPreferences.getInstance().then((sp) {
       int value = sp.getInt("StartValue") ?? 0;
       myIntvalue = getStackInit(value);
  });
  super.initState();
}

@override
Widget build(BuildContext context) {
  return Scaffold(
      body: FutureBuilder(
            future: myIntvalue,     <-- Exception, not initialized
            builder: (context, AsyncSnapshot snapshot) {
              ....

The problem ist, that myIntvalue is not yet initialized when the FutureBuilder is reached.问题在于,当到达 FutureBuilder 时 myIntvalue 尚未初始化。 What is the best way to initialized the future before it is "really" initialized?在“真正”初始化之前初始化未来的最佳方法是什么? Or is it possible to define a future during initialization and "replace" the result later on?或者是否可以在初始化期间定义未来并稍后“替换”结果? Is there any more elegant way?有没有更优雅的方式?

Thanks!谢谢!

In general, if you need to be able to check if something's been initialized, you need to make it nullable.通常,如果您需要能够检查某些内容是否已初始化,则需要将其设为可空。

Or you could set your Future to an initial sentinel value (eg Future.value(0) ), replace it later, and call setState to rebuild your widget tree, just as you would if you had to update any other member variable.或者您可以将您的Future设置为初始标记值(例如Future.value(0) ),稍后替换它,然后调用setState来重建您的小部件树,就像您必须更新任何其他成员变量一样。

However, in your case you should just initialize myIntvalue to the desired Future as soon as possible.但是,在您的情况下,您应该尽快将myIntvalue初始化为所需的Future For example:例如:

@override
void initState()
{
  Future<int> initializeIntValue() async {
    var sp = SharedPreferences.getInstance();
    int value = sp.getInt("StartValue") ?? 0;
    return await getStackInit(value);
  }

  myIntvalue = initializeIntValue();
  super.initState();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM