我正在尝试实现一个注销页面。因此,当用户点击导航中的注销按钮时,会调用以下代码:
Class Logout extends StatelessWidget {
@override
Widget build(BuildContext context) {
final provider = Provider.of<SignInProvider>(context, listen: true);
Future.delayed(Duration(seconds: 5), () async {
provider.isLoggedIn = false;
provider.notifyListeners();
Navigator.pushReplacement(
context, new MaterialPageRoute(builder: (context) => LoginGate()));
});
return Center(child: CircularProgressIndicator());
}
}
我得到以下错误:
The following assertion was thrown building MainScreen(dirty, dependencies: [_InheritedProviderScope<SelectedIndex?>, _InheritedProviderScope<SignInProvider?>], state: _MainScreenState#6a8ce):
setState() or markNeedsBuild() called during build.
我试着增加延迟,希望这能解决问题,但无济于事。如果您能帮我处理这个问题,我将不胜感激。
使用NavigationRail 显示注销按钮
const NavigationRailDestination(
icon: Icon(Icons.logout),
label: Text('Logout'),
),
Logout小部件使用以下方法调用:
child: Row(
children: [
NavigationRailExample(),
const VerticalDivider(thickness: 1, width: 1),
Expanded(
child: screenSwitch[providerSelectedIndex.selectedIndex],
)
],
),
List<Widget> screenSwitch = [
HomeScreen(),
Screen1(),
Screen2(),
Screen3(),
Screen4(),
Screen5(),
Screen6(),
Logout(),
];
您在构建方法中调用异步函数是错误的。试试这个:
class Logout extends StatelessWidget {
@override
Widget build(BuildContext context) {
return FutureBuilder(
future: doLogOut(context),
builder: (context, snapshot) {
return Center(child: CircularProgressIndicator());
},
);
}
Future<void> doLogOut(BuildContext context) async {
final provider = Provider.of<SignInProvider>(context, listen: true);
await Future.delayed(Duration(seconds: 5), () async {
provider.isLoggedIn = false;
provider.notifyListeners();
Navigator.pushReplacement(
context, new MaterialPageRoute(builder: (context) => LoginGate()));
});
}
}