Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter read shared preferences in main then decide which startup page?

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?

I tied these codes:

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

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)

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

like image 539
Nicholas Jela Avatar asked May 22 '18 01:05

Nicholas Jela


People also ask

Can I store list in SharedPreferences Flutter?

To do so, we'll encode our object into a JSON string and save it in the SharedPreferences space. When we want to read the saved data, we only have to decode from a JSON string back to our object. Saving data in SharedPreferences is an easy solution when you want to save small amounts of data.


2 Answers

Here is what you can do

import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

void main() async {

  String initialRoute;

  // handle exceptions caused by making main async
  WidgetsFlutterBinding.ensureInitialized();

  // init a shared preferences variable
  SharedPreferences prefs = await SharedPreferences.getInstance();
  
  // read token
  String token = prefs.getString('token');

  // use dart's null safety operater
  if (token?.isEmpty ?? true)
    initialRoute = 'login';
  else
    initialRoute = '/';

  // create a flutter material app as usual
  Widget app = MaterialApp(
    ...
    initialRoute: initialRoute,
  );

  // mount and run the flutter app
  runApp(app);
}

For more details, you can refer to this article: https://www.ravsam.in/blog/dynamic-home-route-in-flutter-app/

like image 197
Ravgeet Dhillon Avatar answered Sep 17 '22 17:09

Ravgeet Dhillon


This is what i did,

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

Then in the Material App Build

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

_checkUserLoggedIn Function

bool _checkUserLoggedIn() {
    return _storageService.getFromShared('isLoggedIn'); //  Just a get method from shared preferences
}
like image 37
Kavinda Jayakody Avatar answered Sep 19 '22 17:09

Kavinda Jayakody