从抽屉注销后返回登录,无论发生什么



当他从抽屉(无论他在哪里)单击注销按钮时,我需要重定向用户到登录页面。问题是,当我点击登出按钮时,屏幕保持不变。

根据这篇文章:Flutter provider状态管理,注销概念

我:

void main() async {
runApp(
MultiProvider(
providers: [
ChangeNotifierProvider<Profile>(
create: (final BuildContext context) {
return Profile();
},
)
],
child: MyApp(),
),
);
}

MyApp:

class _MyAppState extends State<MyApp> {
@override
void initState() {
super.initState();
initPlatformState();
}
/// Platform messages are asynchronous, so we initialize in an async method.
Future<void> initPlatformState() async {
if (!mounted) return;
}
@override
Widget build(BuildContext context) {
return new MaterialApp(
initialRoute: '/',
navigatorKey: navigatorKey,
// ...
home: Consumer<Profile>(
builder: (context, profile, child){
return profile.isAuthenticated ? SplashScreen() : AuthScreen();
}
)
);
}
}

抽屉中有退出按钮的部分:

ListTile(
leading: Icon(Icons.logout),
title: Text(AppLocalizations.of(context)!.logout),
onTap: () async {
SharedPreferences preferences =
await SharedPreferences.getInstance();
await preferences.clear();
final Profile profile =
Provider.of<Profile>(context, listen: false);
profile.isAuthenticated = false;
}),

正如我所说的,当我从抽屉中单击注销按钮时,用户正确地注销了,但屏幕保持不变。

这是配置文件类:

class Profile with ChangeNotifier {
bool _isAuthenticated = false;
bool get isAuthenticated {
return this._isAuthenticated;
}
set isAuthenticated(bool newVal) {
this._isAuthenticated = newVal;
this.notifyListeners();
}
}

我认为您使用提供商类不正确。像这样使用您的配置文件类。

class Profile with ChangeNotifier {
bool _isAuthenticated = true;
bool get getIsAuthenticated => _isAuthenticated;
set setIsAuthenticated(bool isAuthenticated) {
_isAuthenticated = isAuthenticated;
notifyListeners();//you must call this method to inform lisners
}
}

in set method callnotifyListners();

listTile中的将profile.isAuthenticated = false替换为profile.isAuthenticated = false;始终使用getter和setter作为最佳实践。我希望这就是你要找的。

在LogOut onTap()部分中添加Navigator.of(context). pushreplacementnamed ("/routeName")。

更多信息:https://api.flutter.dev/flutter/widgets/Navigator/pushReplacementNamed.html

确保在MyApp文件中设置了注销路由,我将编辑注销按钮文件如下:

ListTile(
leading: Icon(Icons.logout),
title: Text(AppLocalizations.of(context)!.logout),
onTap: () async {
SharedPreferences preferences =
await SharedPreferences.getInstance();
await preferences.clear();
final Profile profile =
Provider.of<Profile>(context, listen: false);
profile.isAuthenticated = false;
// add login file route here using Navigator.pushReplacementNamed() ; 
}),

导航器推送名称为->注销路线?

相关内容

  • 没有找到相关文章

最新更新