skip to Main Content

I’m using amazon amplify-cognito to authenticate users for my flutter app. When the user launches the app, i want him to be directed to ‘login’ page if he is not logged in, else to ‘home’ if he is logged in. I already implemented the login page and it is working well. The issue with my code is that, anytime the user launches the app, it takes him to ‘login’ page, even if he is already logged in

import 'package:flutter/material.dart';
import 'package:amplify_flutter/amplify_flutter.dart';
import 'package:amplify_auth_cognito/amplify_auth_cognito.dart';

import 'amplifyconfiguration.dart';
import 'package:ingeyaa/login.dart';
import 'package:ingeyaa/signIn.dart';
import 'home.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  configureAmplify();

  try {
    AuthSession res = await Amplify.Auth.fetchAuthSession();
    runApp(MyApp(isLoggedIn: res.isSignedIn));
  } catch (e) {
    runApp(const MyApp(isLoggedIn: false));
  }
}

Future<void> configureAmplify() async {

  final authPlugin = AmplifyAuthCognito();
  await Amplify.addPlugin(authPlugin);

  try {
    await Amplify.configure(amplifyconfig);
  } on AmplifyAlreadyConfiguredException {
    safePrint("Tried to reconfigure Amplify; this can occur when your app restarts on Android.");
  }
}

class MyApp extends StatelessWidget {
  final bool isLoggedIn;

  const MyApp({Key? key, required this.isLoggedIn});

  
  @override
  Widget build(BuildContext context) {
    const whiteSwatch = MaterialColor(
      0xFFFFFFFF,
      <int, Color>{
        50 : Colors.white,
        100 : Colors.white,
        200 : Colors.white,
        300 : Colors.white,
        400 : Colors.white,
        500 : Colors.white,
        600 : Colors.white,
        700 : Colors.white,
        800 : Colors.white,
        900 : Colors.white,
      },
    );

    return  MaterialApp(
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
      primarySwatch: whiteSwatch,
    ),
      home: isLoggedIn ? Home() : Login(),
    );
  }
}

2

Answers


  1. use sharedpreferences package to know if a user is previously logged in.
    https://pub.dev/packages/shared_preferences

    Login or Signup to reply.
  2. Use the https://pub.dev/packages/shared_preferences package.

    1. Add dependencies to pubspec.yaml file.
    dependencies:
      flutter:
        sdk: flutter
      shared_preferences: ^2.0.16
    
    1. When logging in, ID/Password is validated and saved.
    Widget _loginButton(Size size){
     
        return GestureDetector(
          onTap: () async {
            if(_idController.text.isEmpty ||_pwController.text.isEmpty){
              setState(() {
                strRes = 'input id and password pls';
              });
            }
            else{
              final loginResult = await _checkValidLoginInfo(); //check your id/password
              if(loginResult == true){
                  prefs.setString('id', _idController.text); //write id
                  prefs.setString('pw', _pwController.text); //write pw
    
                  Navigator.push(context, MaterialPageRoute(builder: (context) => MainHomeScreen()))
                      : Navigator.push(context, CupertinoPageRoute(builder: (context) => MainHomeScreen()));
            }
          },
          child: Container(
            width: size.width,
            height: size.height * 0.06,
            alignment: Alignment.center,
            margin: EdgeInsets.only(top: marginHeight, left: marginWidth, right: marginWidth),
            child: Text('login'),
          ),
        );
      }
    
    1. Delete login information when logging out
    Widget _logoutButton(Size size){
      final prefs = await SharedPreferences.getInstance();
    
        return GestureDetector(
            onTap: () async {
             final prefs = await SharedPreferences.getInstance();
                prefs.clear(); //remove login info
    
                Platform.isAndroid ?
                Navigator.push(context, MaterialPageRoute(builder: (context) => const LoginScreen()))
                    : Navigator.push(context, CupertinoPageRoute(builder: (context) => const LoginScreen()));
            },
            child: Container(
              width: size.width,
              height: size.height * 0.06,
              alignment: Alignment.center,
              child: Text('log out'),
            ),
          );
      }
    
    1. Screen conversion after checking login information
    bool bIsLogin = false;
    
      _checkLoginInfo(){
        final prefs = await SharedPreferences.getInstance();
    
        if(prefs != null) {
          final _id = prefs.getString('id');
          final _pw = prefs.getString('pw');
    
          final loginResult = await _checkValidLoginInfo();;
          if (loginResult == true) {
            bIsLogin = true;
          }
        }
      }
    
     @override
      Widget build(BuildContext context) {  
    
        return Scaffold(
          body: FutureBuilder(
            future: _checkLoginInfo(),
            builder: (context, snapshot) {
              if(snapshot.connectionState == ConnectionState.waiting){
                return CircularProgressIndicator();
              }
              else{
                if(bIsLogin){
                  return const MainHomeScreen();
                }
                return const LoginScreen():
              }
            },
          ),
        );
      }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search