Flutter在main中读取共享的首选项,然后确定哪个启动页面?

Nic*_*ela 5 async-await dart flutter

我想判断要从哪个页面开始(实际上是登录页面和主页)。因此,我必须在首选项中阅读isLogin。主要如何做?

我绑了这些代码:

Future<Null> checkIsLogin() async {
  String _token = "";
  // If token exist already, then HomePage
  SharedPreferences prefs = await SharedPreferences.getInstance();
  _token = prefs.getString("token");
  print('get token from prefs: ' +  _token);
  if (_token != "" && _token != null) {
    // already login
    print("alreay login.");
    isLogin = true;
  }
}

void main() {
  App.init();
  // if we have token then go to HomePage directly otherwise go to LoginPage.
  Widget _defaultHome = new LoginPage();
  checkIsLogin();
  if (isLogin) {
    _defaultHome = new HomePage();
  }

  runApp(new MaterialApp(
      debugShowCheckedModeBanner: false,
      theme: globalThemeData,
      home: _defaultHome
  ));
}
Run Code Online (Sandbox Code Playgroud)

上面的代码中,isLogin是一个全局变量。有一个错误:

Performing full restart...                                       
Restarted app in 2,810ms.
[VERBOSE-2:dart_error.cc(16)] Unhandled exception:
Invalid argument(s)
#0      _StringBase.+ (dart:core/runtime/libstring_patch.dart:245:57)
#1      checkIsLogin (file:///Volumes/xs/awesome/uranus/clients/flutter/flutter_asgard/lib/main.dart:17:34)
<asynchronous suspension>
#2      main (file:///Volumes/xs/awesome/uranus/clients/flutter/flutter_asgard/lib/main.dart:29:3)
#3      _startIsolate.<anonymous closure> (dart:isolate/runtime/libisolate_patch.dart:279:19)
#4      _RawReceivePortImpl._handleMessage (dart:isolate/runtime/libisolate_patch.dart:165:12)
Run Code Online (Sandbox Code Playgroud)

似乎在main中调用异步存在问题,如何使其工作?

Kav*_*ody 10

这就是我所做的

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  SharedPreferences.getInstance().then((instance) {
    StorageService().sharedPreferencesInstance = instance; // Storage service is a service to manage all shared preferences stuff. I keep the instance there and access it whenever i wanted.
    runApp(MyApp());
  });
}
Run Code Online (Sandbox Code Playgroud)

然后在 Material App Build 中

@override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'App Title',
      home: _checkUserLoggedIn()
          ? HomeScreen()
          : LoginPage(),
    );
  }
Run Code Online (Sandbox Code Playgroud)

_checkUserLoggedIn 函数

bool _checkUserLoggedIn() {
    return _storageService.getFromShared('isLoggedIn'); //  Just a get method from shared preferences
}
Run Code Online (Sandbox Code Playgroud)


蔡旻袁*_*蔡旻袁 5

您需要等待 checkIsLogin。

这是我的代码:

Future<Null> main() async {
  SystemChrome.setPreferredOrientations([
    DeviceOrientation.landscapeRight,
    DeviceOrientation.landscapeLeft,
  ]);
  Screen.keepOn(true);
  SharedService.sharedPreferences = await SharedPreferences.getInstance();
  account = SharedService.sharedPreferences.getString("Account");
  password = SharedService.sharedPreferences.getString("Password");
  runApp(new MyApp());
}
Run Code Online (Sandbox Code Playgroud)


Shy*_*hil 3

加载主页,如果用户未登录,则将其替换为您的 LoginPage()

@override
  void initState() {
    super.initState();
    checkIsLogin();
 }   


Future<Null> checkIsLogin() async {
    String _token = "";
    SharedPreferences prefs = await SharedPreferences.getInstance();
    _token = prefs.getString("token");
    if (_token != "" && _token != null) {
      print("alreay login.");
      //your home page is loaded
    }
    else
    {
      //replace it with the login page
      Navigator.pushReplacement(
        context,
        MaterialPageRoute(builder: (context) => new LoginPage()),
      );
    }
  }
Run Code Online (Sandbox Code Playgroud)

  • 如果主页本身就是登录页面怎么办? (2认同)