如何使用SharedPreferences更改初始路由?

问题描述 投票:0回答:1

当用户登录时,执行以下代码。

login() async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setBool('loggedIn', true);
  }

而且我想在initialRoute中控制如果loggedIn等于true,则不会显示登录页面。 我该怎么做?

flutter dart sharedpreferences
1个回答
0
投票

您可以在 SharedPreferences 上使用静态 getter 和 setter:

class Preferences extends ChangeNotifier {
  static late SharedPreferences _prefs;

  static Future init() async {
    _prefs = await SharedPreferences.getInstance();
  }

  static bool _isLoggedIn = false;
  static bool get isLoggedIn {
    return _prefs.getBool('loggedIn') ?? _isLoggedIn;
  }

  static set isLoggedIn(bool loggedIn) {
    _isLoggedIn = loggedIn;
    _prefs.setBool('loggedIn', _isLoggedIn);
  }
}

main.dart
中类似:

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Preferences.init();
  runApp(const AppState());
}

然后只需向路线添加条件:

MaterialApp(
initialRoute: Preferences.isLoggedIn? 'main': 'login',
...);

另外,如果您要使用这样的路由,我建议使用单独的类,例如

AppRoutes
,您可以在其中保存与它们相关的所有路由和逻辑,并且不需要失去
main.dart
的可读性。

© www.soinside.com 2019 - 2024. All rights reserved.