[英]How to navigate in flutter during widget build?
我試圖檢測該用戶不再經過身份驗證並將用戶重定向到登錄。 這就是我的做法
Widget build(BuildContext context) {
return FutureBuilder(
future: _getData(context),
builder: (context, snapshot) {
try {
if (snapshot.hasError && _isAuthenticationError(snapshot.error)) {
Navigator.push(context, MaterialPageRoute(builder: (context) => LoginView()));
}
不幸的是,在構建時進行導航不起作用。 它拋出這個錯誤
flutter: setState() or markNeedsBuild() called during build.
flutter: This Overlay widget cannot be marked as needing to build because the framework is already in the
flutter: process of building widgets. A widget can be marked as needing to be built during the build
我不能只返回LoginView
小部件,因為父小部件包含應用欄和浮動按鈕,並且需要在沒有這些控件的情況下顯示登錄視圖。我需要導航。
有可能做到嗎?
將其包裹在Future.microtask
。 這將安排它在下一個異步任務周期(即build
完成后)發生。
Future.microtask(() => Navigator.push(
context,
MaterialPageRoute(builder: (context) => LoginView())
));
顫動中的流
通常的事情是使用發生用戶更改的流程。 當用戶注銷時,他會檢測到該更改並可以將其定向到另一個窗口。
問題在這里:
snapshot.hasError && _isAuthenticationError(snapshot.error)
而不是這個使用 OR
snapshot.hasError || _isAuthenticationError(snapshot.error)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.