async-await - Flutter 在 main 中读取共享首选项,然后决定哪个启动页面?

标签 async-await dart flutter

我想在main中判断启动哪个页面(其实是登录页面和首页)。所以我必须阅读首选项中的 isLogin 。如何在 main 中做到这一点?

我绑定(bind)了这些代码:

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 是一个全局变量。出现错误:

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 中调用 async 有问题,如何让它工作?

最佳答案

这就是我所做的,

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

然后在Material App Build中

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

_checkUserLoggedIn 函数

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

关于async-await - Flutter 在 main 中读取共享首选项,然后决定哪个启动页面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50458526/

相关文章:

flutter - 如何在 flutter 中将嵌套的 JSON api 响应显示为 GridView ?

javascript - promise -如何处理已知错误

python - 为什么我要使用 `async def` 而不是 `@asyncio.coroutine`?

c# - 如果发生任何异常,如何使 Task.WaitAll() 中断?

flutter - Flutter异步/等待在两个Firebase功能之间不起作用

flutter - Flutter/Dart:窗口小部件中的文本根据哪个屏幕调用而变化?

.net - 在 Task.Run() 中包装同步调用以使其异步有益吗?

json - 如何在Dart中为 map ,多层 map 创建模型

flutter - 在 dart 中从 ' Map<String,ProductItem>myMap' 过滤并获取新的 Map

flutter - flutter 中的多选项卡/页面 View