经过多次反复试验,我确定了问题所在。我忘记了我在MaterialApp 小部件中为/ 路由设置了FutureBuilder。我正在传递一个函数调用,该函数调用将未来返回给FutureBuilder 构造函数的future 参数,而不是指向未来的变量。
因此,每次更新路线时,都会创建一个全新的未来。在MaterialApp 构造函数之外进行函数调用并将生成的future 存储在一个变量中,然后将其传递给FutureBuilder 就可以了。
这似乎与我在打开键盘时遇到的奇怪行为有关,但这绝对是原因。我的意思见下文。
有错误的代码:
return MaterialApp(
title: appTitle,
theme: ThemeData(
primarySwatch: Colors.teal,
accentColor: Colors.tealAccent,
buttonColor: Colors.lightBlue,
),
routes: {
'/': (context) => FutureBuilder<void>(
future: futureFun(), //Bug! I'm passing a function that returns a future when called. So a new future is returned each time
builder: (context, snapshot) {
...
}
...
}
...
}
固定代码:
final futureVar = futureFun(); //calling the function here instead and storing its future in a variable
return MaterialApp(
title: appTitle,
theme: ThemeData(
primarySwatch: Colors.teal,
accentColor: Colors.tealAccent,
buttonColor: Colors.lightBlue,
),
routes: {
'/': (context) => FutureBuilder<void>(
future: futureVar, //Fixed! Passing the reference to the future rather than the function call
builder: (context, snapshot) {
...
}
...
}
...
}