Держите пользователя авторизованным во флаттере - PullRequest
0 голосов
/ 03 августа 2020
• 1000 Это код, который я использовал для ведения журнала, и я уже использовал общие настройки, но все еще не работал. Что я должен добавить в код или изменить? Должен ли я добавить что-то на домашнюю страницу ()? Я забыл упомянуть, что моя первая страница, когда я открывал приложение, это main.dart, а вторая - LoginScreen (где вы можете выбрать, с какой учетной записью вы входите, например: 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', 'useremail@gmail.com');
                                  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),
            ),
          ],
        ),
      ),
    );
  }
}

И мой 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),
            ),
          )),
    );
  }
}

1 Ответ

1 голос
/ 03 августа 2020

Вы должны показать файл main.dart. Вы загружаете информацию из SharedPreferences в main.dart? Если это так, вам необходимо проверить, есть ли у вас уже загруженные данные из SharedPreferences, прежде чем переходить на страницу входа и не открывать страницу входа.

...