Home > Net >  Get a sharedPreferences when user start the App Flutter
Get a sharedPreferences when user start the App Flutter

Time:02-23

I would like that when the user opens the app : if it is already connected in the past it opens directly the app otherwise if it has just installed it then it opens a login page

In Android studio I do like that :

@Override
    protected void onStart() {
        super.onStart();
        
        SharedPreferencesOpti sp = new SharedPreferencesOpti(this);
        boolean isConnected = sp.getBooleanSharedPreferences("isConnected");
        UserModel.setConnected(isConnected);
        
        if (!UserModel.isConnected())
        {
            Intent intent = new Intent(MainActivity.this, LoginActivity.class);
            startActivity(intent);
        }
    }

Here's my Flutter code :

class MyApp extends StatefulWidget {

  const MyApp({Key? key}) : super(key: key);

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {


  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Demo',
      initialRoute: '/',
      onGenerateRoute: (settings) => RouteGenerator.generateRoute(settings),
      theme: ThemeData(
        primarySwatch: ColorsHelp.getPrimaryColor(),
      ),
      home: const MyHomePage(),
    );
  }
}

HomePage() is the App and I have a LoginScreen() too (LoginScreen is a Stateful Widget)

But I don't know how to do this in Flutter. I tried many things but nothing worked.

My idea is to use Shared_Preferences like in Android Studio I think it's a good solution but maybe not the best one.

CodePudding user response:

You could access SharedPreferences before runApp() by ensuring that WidgetsFlutterBinding.ensureInitialized():

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

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  SharedPreferences prefs = await SharedPreferences.getInstance();
  bool loggedIn = prefs.getBool("loggedIn");
  runApp(MyApp(loggedIn: loggedIn);
}
  • Related