svraluca1
svraluca1

Reputation: 47

Keep the user logged in flutter

I am doing an app in flutter and i am working on the authentication part.I want to know how i can keep my user logged in after i reload the app . This is the code that i used for logging and i already used shared preferences but still didn't work.What i should add to the code or change?Should i add something to the Homepage() too? I forgot to mention that my first page when i opened the app it's the main.dart and second it's the LoginScreen( where u can choose what type of account you are logging in with ex: facebook, google, email )

import 'package:flutter/material.dart';
import 'SignUp.dart';
import 'brazierContainer.dart';
import 'package:google_fonts/google_fonts.dart';
import 'LoginScreen.dart';
import 'HomePage.dart';
import 'auth.dart';
import 'package:shared_preferences/shared_preferences.dart';

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  SharedPreferences prefs = await SharedPreferences.getInstance();
  var email = prefs.getString('email');
  print(email);
  runApp(MaterialApp(home: email == null ? LoginPage() : Homepage()));
}

class LoginPage extends StatefulWidget {
  LoginPage({Key key, this.title}) : super(key: key);

  final String title;

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

class _LoginPageState extends State<LoginPage> {
  final _formKey = GlobalKey<FormState>();
  String email = '';
  String password = '';
  String error = '';
  bool loading = false;
  final Authentication authentication = Authentication();
  @override
  Widget build(BuildContext context) {
    return loading
        ? Homepage()
        : Scaffold(
            resizeToAvoidBottomInset: false,
            resizeToAvoidBottomPadding: false,
            body: Container(
              height: 900.0,
              width: 500.0,
              child: Column(
                children: <Widget>[
                  Padding(
                    padding: const EdgeInsets.only(top: 50.0),
                    child: Row(
                      children: <Widget>[
                        IconButton(
                          icon: Icon(Icons.arrow_back_ios, color: Colors.blue),
                          onPressed: () {
                            Navigator.pushReplacement(
                                context,
                                MaterialPageRoute(
                                    builder: (context) => LoginScreen()));
                          },
                        )
                      ],
                    ),
                  ),
                  Padding(
                    padding: const EdgeInsets.only(top: 40.0),
                    child: RichText(
                      text: TextSpan(
                        text: 'Tariffo',
                        style: TextStyle(
                            color: Colors.blue,
                            fontFamily: 'SignPainter',
                            fontSize: 60),
                      ),
                    ),
                  ),
                  SizedBox(
                      height: 400.0,
                      child: Form(
                        key: _formKey,
                        child: Column(
                          children: <Widget>[
                            Padding(
                              padding: const EdgeInsets.only(
                                  left: 40.0, right: 40.0, top: 40.0),
                              child: TextFormField(
                                validator: (val) =>
                                    val.isEmpty ? 'enter email' : null,
                                onChanged: (val) {
                                  setState(() => email = val);
                                },
                                style: TextStyle(color: Colors.black),
                                decoration: InputDecoration(
                                    hintText: 'enter email',
                                    hintStyle: TextStyle(
                                        fontFamily: 'Antra',
                                        fontSize: 12.0,
                                        color: Colors.black)),
                              ),
                            ),
                            Padding(
                              padding: const EdgeInsets.only(
                                  left: 40.0, right: 40.0, top: 40.0),
                              child: TextFormField(
                                validator: (val) => val.length < 8
                                    ? 'enter password > 8 digits'
                                    : null,
                                onChanged: (val) {
                                  setState(() => password = val);
                                },
                                style: TextStyle(color: Colors.black),
                                decoration: InputDecoration(
                                    hintText: 'enter password',
                                    hintStyle: TextStyle(
                                        fontFamily: 'Antra',
                                        fontSize: 12.0,
                                        color: Colors.black)),
                                obscureText: true,
                              ),
                            ),
                            SizedBox(height: 50),
                            Padding(
                              padding: const EdgeInsets.only(top: 40.0),
                              child: MaterialButton(
                                height: 50,
                                minWidth: 300,
                                shape: RoundedRectangleBorder(
                                    borderRadius: BorderRadius.circular(10)),
                                color: Colors.blue,
                                onPressed: () async {
                                  SharedPreferences prefs =
                                      await SharedPreferences.getInstance();
                                  prefs.setString(
                                      'email', '[email protected]');
                                  if (_formKey.currentState.validate()) {
                                    setState(() => loading = true);
                                    dynamic result = await authentication
                                        .signUpWithEmailAndPassword(
                                            email, password);
                                    if (result == null) {
                                      setState(() => error =
                                          'Sorry,These credentials will not work out');
                                      loading = false;
                                    }
                                  }
                                },
                                child: Text(
                                  'Sign in',
                                  style: TextStyle(
                                      fontFamily: 'Antra', color: Colors.white),
                                ),
                              ),
                            ),
                            Container(
                              padding: EdgeInsets.symmetric(
                                  vertical: 10, horizontal: 10),
                              alignment: Alignment.centerRight,
                              child: Text('Forgot Password ?',
                                  style: TextStyle(
                                      fontSize: 14,
                                      fontWeight: FontWeight.w500)),
                            ),
                          ],
                        ),
                      )),
                  _createAccountLabel(),
                ],
              ),
            ),
          );
  }

  Widget _createAccountLabel() {
    return InkWell(
      onTap: () {
        Navigator.push(
            context, MaterialPageRoute(builder: (context) => SignupPage()));
      },
      child: Container(
        margin: EdgeInsets.symmetric(vertical: 20),
        padding: EdgeInsets.all(15),
        alignment: Alignment.bottomCenter,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              "Don't you have an account ?",
              style: TextStyle(fontSize: 13, fontWeight: FontWeight.w600),
            ),
            SizedBox(
              width: 10,
            ),
            Text(
              'Register',
              style: TextStyle(
                  color: Colors.blue,
                  fontSize: 13,
                  fontWeight: FontWeight.w600),
            ),
          ],
        ),
      ),
    );
  }
}

And my main.dart

import 'package:flutter/material.dart';
import 'dart:async';
import 'LoginScreen.dart';

void main() => runApp(new MaterialApp(
      home: new MyApp(),
    ));

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => new _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  void initState() {
    super.initState();
    new Future.delayed(
        const Duration(seconds: 3),
        () => Navigator.push(
              context,
              MaterialPageRoute(builder: (context) => LoginScreen()),
            ));
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Welcome to Flutter',
      home: Scaffold(
          backgroundColor: Colors.blue,
          body: Center(
            child: Text(
              "Tariffo",
              style: TextStyle(
                  color: Colors.white, fontFamily: 'SignPainter', fontSize: 60),
            ),
          )),
    );
  }
}

Upvotes: 0

Views: 349

Answers (1)

Captivity
Captivity

Reputation: 338

You must show the main.dart file Do you download information from SharedPreferences in main.dart? If so, you need to check if you already have some data downloaded from SharedPreferences before going to the login page and not open the login page.

Upvotes: 1

Related Questions