在我的应用中,我有一个登录屏幕和一个主屏幕。从登录名导航到主屏幕时,我从.txt文件读取数据并显示4个随机数据点。我正在从initState的文件中获取数据,以便在状态更改时不会多次调用该数据,然后使用诸如...等未来的构建器等待它。
class _HomeScreenState extends State<HomeScreen> {
Future<bool> _future;
@override
initState() {
super.initState();
print('in initState about to call _getData');
_future = _getData();
}
@override
Widget build(BuildContext context) {
var futureBuilder = new FutureBuilder(
future: _future,
builder: (BuildContext context, AsyncSnapshot snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
case ConnectionState.active:
case ConnectionState.waiting:
return new Center(
child: new CircularProgressIndicator(),
);
case ConnectionState.done:
if (snapshot.hasError) {
return new Center(
child: Text('Error'),
);
} else {
return new ListView(
children: <Widget>[
//my view
],
);
}
}
}
);
return MaterialApp(
home: WillPopScope(
onWillPop: () async {
return Navigator.pop(context);
},
child: Scaffold(
body: futureBuilder,
),
)
);
现在,当我使用“后退”按钮导航回到登录屏幕,然后返回主屏幕时,initState将关闭多次(这可以通过我留下的打印语句看到)。当您在这两个屏幕(弹出式主屏幕,推式主屏幕)之间来回移动时,initState将被指数级调用多次。我很困惑,我们将不胜感激!
编辑:登录和主屏幕的完整代码都可以找到https://github.com/ViscousOx/Flutter-Stuff
答案 0 :(得分:0)
尝试:有效 在ConnectionState.waiting中使用默认语句。
class _HomeScreenState extends State<HomeScreen> {
Future<bool> _future;
@override
initState() {
super.initState();
print('in initState about to call _getData');
_future = _getData();
}
@override
Widget build(BuildContext context) {
var futureBuilder = new FutureBuilder(
future: _future,
builder: (BuildContext context, AsyncSnapshot snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.waiting:
return new Center(
child: new CircularProgressIndicator(),
);
default:
if (snapshot.hasError) {
return new Center(
child: Text('Error'),
);
} else {
return new ListView(
children: <Widget>[
//my view
],
);
}
}
}
);
return MaterialApp(
home: WillPopScope(
onWillPop: () async {
return Navigator.pop(context);
},
child: Scaffold(
body: futureBuilder,
),
)
);
答案 1 :(得分:0)
可以避免连接等待状态。我曾经是:
FutureBuilder(future: _isUserLoggedIn(),
builder: (ctx, loginSnapshot) =>
loginSnapshot.data == true ? AppLandingScreen() : SignUpScreen()
),