当我们在FutureBuilder内部使用Get.toNamed()时,在构建过程中调用了setState()或mark



使用flutter 2.xGet package版本^4.1.2

我有一个类似的小部件:

class InitializationScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: FutureBuilder(
future:
// this is just for testing purposes
Future.delayed(const Duration(seconds: 4)).then((value) => "done"),
builder: (context, snapshot) {
if (shouldProceed(snapshot)) {
Get.toNamed("/login");
}
if (snapshot.hasError) {
// handle error case ...
}
return const Center(child: CircularProgressIndicator());
},
),
);
}
bool shouldProceed(AsyncSnapshot snapshot) =>
snapshot.hasData && snapshot.connectionState == ConnectionState.done;
}

FutureBuilder内部使用的Get.toNamed("/login");导致此错误:

在构建FutureBuilder时抛出了以下断言(dirty,state:_FutureBuilderState#b510d(:在生成过程中调用了setState((或markNeedsBuild((。

  • 我试图检查connectionStatus(基于SO答案(,但没有成功

有什么帮助吗?

build方法用于渲染UI。您的逻辑根本没有连接到渲染,所以即使没有错误,也没有意义将其放入build方法中。

最好将此方法转换为StatefulWidget,并将逻辑放在initState中,例如:

Future.delayed(const Duration(seconds: 4))
.then((value) => "done")
.then((_) => Get.toNamed("/login"));

尝试这个

Future.delayed(Duration.zero, () async {
your set state 

});

当在屏幕的初始build()期间立即调用setState()时,会发生此错误。为了避免这种情况,您可以通过将setState()放在Future.delayed中来解决问题,类似于:

Future.delayed(Duration(milliseconds: 100), () => Get.toNamed("/login"));

相关内容

最新更新