Home > Net >  Flutter show Login or Home screen based on preferences data
Flutter show Login or Home screen based on preferences data

Time:10-10

I know this question has been asked by many but I have tried to work on the code with no success. I'm using shared preferences to store my email once the user login and once logged out the email should be deleted. That is working fine. When the app start, it should read email from phone using shared preferences and if the email exist, the user is logged in and should be navigated to Home() screen else if the email does not exist, the user is not logged in and so should be navigated to Login() screen. Below is my code which when I start the app it is always showing the Home() screen even if the user is logged out. Anybody to help me know where I'm not doing the right thing. Thanks in advance.

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(MyApp());
}

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

  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  Future<String> getSharedPrefs() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String _email = prefs.getString('email') ?? '';
    return _email;
  }

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'chat app',
      home: FutureBuilder<String>(
        future: getSharedPrefs(),
        builder: (
          BuildContext context,
          AsyncSnapshot<String> snapshot,
        ) {
          if (snapshot.connectionState == ConnectionState.waiting) {
            return CircularProgressIndicator();
          } else if (snapshot.connectionState == ConnectionState.done) {
            if (snapshot.hasError) {
              return const Text('Error');
            } else if (snapshot.hasData) {
              return Home();
            } else {
              return Login();
            }
          } else {
            return Text('State: ${snapshot.connectionState}');
          }
        },
      ),
    );
  }
}

CodePudding user response:

Your snapshot.hasData will always be true, as you return the empty string in the getSharedPrefs method if the email does not exist.

You should modify it to snapshot.hasData && snapshot.data.isNotEmpty for it to work as you expect it to.

  • Related