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
use sharedpreferences package to know if a user is previously logged in.
https://pub.dev/packages/shared_preferences
Use the https://pub.dev/packages/shared_preferences package.
pubspec.yaml
file.