M.ArslanKhan
M.ArslanKhan

Reputation: 3918

How to call sharedprefrence before first screen

I am implementing remember me option on the login screen, want to call shared preference before the widget is created. we have the one and only entry point that is the main function, but how we can call a function here to read primitive data (email/password).

void main() {
           setupLocator();
           runApp(MaterialApp(
           debugShowCheckedModeBanner: false,
           theme: new ThemeData(fontFamily: 'OpenSans-Light'),
           initialRoute: "/",
           onGenerateRoute: Router.generateRoute,
   ));
}

reading bool value

 Future<bool> read(String key) async {
    final prefs = await SharedPreferences.getInstance();
     return prefs.getbool(key);
  }

I also try to run a asyn function before route


String firstNav;
void main() {

  setupLocator();
  readSharedPref();
  if(firstNav!=null)
    runApp(MaterialApp(
      debugShowCheckedModeBanner: false,
      theme: new ThemeData(fontFamily: 'OpenSans-Light'),
      initialRoute: firstNav,
      onGenerateRoute: Router.generateRoute,
    ));
  }

  void readSharedPref() async {
    Utiles df=Utiles();
    String isRem=await df.read("remember");
    if (isRem.contains("true")) {
      firstNav='homeview';
    } else {
      firstNav='/';
    }
}


Upvotes: 1

Views: 111

Answers (2)

Ademir Villena Zevallos
Ademir Villena Zevallos

Reputation: 1561

You need to set your main function as async, and add an await and a line of code:

void main() async{
    //Add this lines is necessary now that your main is async
    WidgetsFlutterBinding.ensureInitialized();
    //Now you have to "await" the readSharedPref() function
    await readSharedPref();
    // And here comes all your code
}

Upvotes: 2

dlohani
dlohani

Reputation: 2591

Instead of waiting waiting for sharedPreference to load before building any widgets, just show a loader widget with progress indicator until the shared preference is loaded, and when it's loaded, show the required view based on the value loaded from sharedPreference, here is how you can modify your code, (replace HomeView and RootView widgets with your respective widgets for your homeView and / routes)

void main() {
  setupLocator();
    runApp(MaterialApp(
      debugShowCheckedModeBanner: false,
      theme: new ThemeData(fontFamily: 'OpenSans-Light'),
      initialRoute: Loader(),
      onGenerateRoute: Router.generateRoute,
    ));

}

class Loader extends StatefulWidget {
  @override
  _LoaderState createState() => _LoaderState();
}

class _LoaderState extends State<Loader> {
  Widget firstNav;
  @override
  void initState() { 
    super.initState();
    readSharedPref();
  }
  void readSharedPref() async {
    Utiles df=Utiles();
    String isRem=await df.read("remember");
    if (isRem.contains("true")) {
      setState(() {
        // firstNav='homeview';
        firstNav=HomeView(); // replace HomeView with the widget you use for homeview route
      });
    } else {
      setState(() {
        // firstNav='/';
        firstNav=RootView(); // replace RootView with the widget you use for / route
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return firstNav != null ? firstNav : Center(child: CircularProgressIndicator(),);
  }
}

Upvotes: 1

Related Questions