gpt4 book ai didi

flutter - FutureBuilder运行两次

转载 作者:行者123 更新时间:2023-12-03 02:42:17 25 4
gpt4 key购买 nike

我在两次启动FutureBuilder时遇到问题。
首先它正确地获取数据,返回我的StartScreen,然后几秒钟后,StartScreen重新生成,我注意到FutureBuilder再次启动。

这是我的代码,非常简单,所以我想知道问题出在哪里吗?

class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
FirebaseUser user;

@override
void initState() {
// TODO: implement initState
super.initState();
getNewestlocation();
}

@override
void dispose() {
super.dispose();
}

@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'APP',
theme: buildTheme(),
home: FutureBuilder<FirebaseUser>(
future: Provider.of<AuthService>(context).getUser(),
builder: (context, AsyncSnapshot<FirebaseUser> snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
if (snapshot.error != null) {
print('error');
return Text(snapshot.error.toString());
}
user = snapshot.data;
print('user here $user');
return snapshot.hasData ? StartScreen(user) : LoginScreen();
} else {
return LoadingCircle();
}
},
),
);
}
}

有人可以帮我吗?

最佳答案

future 再次激发,因为您正在与FutureBuilder同时在build方法中创建它。

FutureBuilder docs:

The future must have been obtained earlier, e.g. during State.initState, State.didUpdateConfig, or State.didChangeDependencies. It must not be created during the State.build or StatelessWidget.build method call when constructing the FutureBuilder. If the future is created at the same time as the FutureBuilder, then every time the FutureBuilder's parent is rebuilt, the asynchronous task will be restarted.



因此,为防止其触发,您必须执行以下操作:
    class _MyAppState extends State<MyApp> {
Future<String> _myString;

@override
void initState() {
super.initState();
_myString = _fetchString();
}

@override
Widget build(BuildContext context) {
return Scaffold(
body: FutureBuilder(
future: _myString,
builder: (context, snapshot) {
// build page stuff...
},
),
);
}
}

Future<String> _fetchString() async {
print('running future function');
await Future.delayed(Duration(seconds: 3));
return 'potatoes';
}

注意,要访问initState()中的提供程序,您必须将listen设置为false,如 this答案中所述。

关于flutter - FutureBuilder运行两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58664293/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com