Flutter在main中读取了共享的首选项,然后决定了哪个启动页面? [英] Flutter read shared preferences in main then decide which startup page?

查看:400
本文介绍了Flutter在main中读取了共享的首选项,然后决定了哪个启动页面?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to judge which page to start up in main (actually is login page and the home page). So I have to read isLogin in preferences. How to do that in main?

我绑定了以下代码:

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
  ));
}

以上代码,isLogin是全局变量.发生错误:

above code, isLogin is an global variable. There was an error:

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)

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

Seems there are issue to call async in main, how to get it to work?

推荐答案

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

Load the Homepage and if the user is not logged in, then replace it with your 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()),
      );
    }
  }

这篇关于Flutter在main中读取了共享的首选项,然后决定了哪个启动页面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆