2021年1月2日星期六

Unable to navigate to homepage based on auth state

Im trying to navigate to homepage after login, this works, i followed this one tutorial:

https://www.youtube.com/watch?v=oJ5Vrya3wCQ&t=307s

But, my problem is when i go to register button > register an user and it takes me straight to the login page but when I fill in the login forms and log in, nothing happens, i must to do a "hot restart" to see my homepage, it is as if some widget did not rebuild. So i should do any better clean way to do this statemanagement?

Main:

import 'package:firebase_auth/firebase_auth.dart';  import 'package:firebase_core/firebase_core.dart';  import 'package:flutter/material.dart';  import 'package:plantsapp/screens/login_page.dart';  import 'package:plantsapp/screens/plant_screen.dart';  import 'package:plantsapp/screens/register_page.dart';  import 'package:plantsapp/screens/shop_scree_page.dart';  import 'package:plantsapp/services/authentication_service.dart';  import 'package:provider/provider.dart';    void main() async {    WidgetsFlutterBinding.ensureInitialized();    await Firebase.initializeApp();    runApp(MyApp());  }    class MyApp extends StatelessWidget {    // This widget is the root of your application.    @override    Widget build(BuildContext context) {      return MultiProvider(        providers: [          ChangeNotifierProvider<AuthenticationService>(            create: (_) => AuthenticationService(FirebaseAuth.instance),          ),          StreamProvider(create: (context) => context.read<AuthenticationService>().authStateChanges)        ],        child: MaterialApp(          title: 'Flutter Plant Shop UI',          debugShowCheckedModeBanner: false,          home: AuthenticationWrapper(),          routes: {            'registerpage': (context) => RegisterPage(),            'loginpage': (context) => LoginPage(),            'homepage': (context) => PlantScreen(),          },                    //theme: ThemeData.dark(),        ),      );    }  }    // ignore: must_be_immutable  class AuthenticationWrapper extends StatelessWidget with ChangeNotifier{    @override    Widget build(BuildContext context) {      final firebaseuser = context.watch<User>();      notifyListeners();      if(firebaseuser != null) {        notifyListeners();        return ShopScreen();       } else {        notifyListeners();        return LoginPage();      }    }  }  

Authentication service:

import 'package:firebase_auth/firebase_auth.dart';  import 'package:flutter/cupertino.dart';        class AuthenticationService with ChangeNotifier{    final FirebaseAuth _firebaseAuth;      AuthenticationService(this._firebaseAuth);      Stream<User> get authStateChanges => _firebaseAuth.authStateChanges();      Future<String> signIn({String email, String password}) async {      try {        await _firebaseAuth.signInWithEmailAndPassword(email: email, password: password);        notifyListeners();        return "Signed in";      } on FirebaseAuthException catch (e) {        print(e);        return e.message;      }    }      Future<String> signUp({String email, String password, BuildContext context}) async{      try {        await _firebaseAuth.createUserWithEmailAndPassword(email: email, password: password);        print('USUARIO REGISTRADO');        Navigator.pushReplacementNamed(context, 'loginpage');        return "Signed Up";      } on FirebaseAuthException catch (e) {        print(e.message);        return e.message;      }    }      Future<void> signOut() async{      await _firebaseAuth.signOut();      notifyListeners();    }    }  

LoginPage:

import 'package:flutter/material.dart';  import 'package:plantsapp/services/authentication_service.dart';  import 'package:provider/provider.dart';    class LoginPage extends StatefulWidget{    @override    _LoginPageState createState() => _LoginPageState();  }    class _LoginPageState extends State<LoginPage>{    final TextEditingController emailController = TextEditingController();    final TextEditingController passwordController = TextEditingController();      @override    Widget build(BuildContext context) {      return Scaffold(        body: SingleChildScrollView(          child: Container(            margin: EdgeInsets.symmetric(horizontal: 20, vertical: 80),            padding: EdgeInsets.symmetric(horizontal: 20, vertical: 80),            child: Column(              mainAxisAlignment: MainAxisAlignment.center,              children: <Widget>[                Text(                  'Login',                  style: TextStyle(fontSize: 20),                ),                _emailForm(),                _passwordForm(),                _button(),                _buttonRegister(),              ],            ),          ),        ),      );    }      Widget _emailForm() {      return TextField(        controller: emailController,        decoration: InputDecoration(hintText: ('Email')),      );    }      Widget _passwordForm() {      return TextField(        controller: passwordController,        decoration: InputDecoration(hintText: ('Password')),      );    }      Widget _button() {      return RaisedButton(        child: Text('Login'),        onPressed: () {          Provider.of<AuthenticationService>(context, listen: false).signIn(              email: emailController.text.trim(),              password: passwordController.text.trim());        },      );    }      _buttonRegister() {      return RaisedButton(        child: Text('Registrarse'),        onPressed: () {          Navigator.pushReplacementNamed(context, 'registerpage');        },      );    }  }  

RegisterPage:

import 'package:flutter/material.dart';  import 'package:plantsapp/services/authentication_service.dart';  import 'package:provider/provider.dart';    class RegisterPage extends StatefulWidget {    RegisterPage({Key key}) : super(key: key);      @override    _RegisterPageState createState() => _RegisterPageState();  }    class _RegisterPageState extends State<RegisterPage> {    final TextEditingController emailController = TextEditingController();    final TextEditingController passwordController = TextEditingController();      @override    Widget build(BuildContext context) {      return Scaffold(        body: SingleChildScrollView(          child: Container(            margin: EdgeInsets.symmetric(horizontal: 20, vertical: 80),            padding: EdgeInsets.symmetric(horizontal: 20, vertical: 80),            child: Column(              mainAxisAlignment: MainAxisAlignment.center,              children: <Widget>[                Text(                  'Registrarse',                  style: TextStyle(fontSize: 30),                ),                _emailForm(),                _passwordForm(),                _button(),              ],            ),          ),        ),      );    }      Widget _emailForm() {      return TextField(        controller: emailController,        decoration: InputDecoration(hintText: ('Email')),      );    }      Widget _passwordForm() {      return TextField(        controller: passwordController,        decoration: InputDecoration(hintText: ('Password')),      );    }      Widget _button() {      return RaisedButton(        child: Text('Registrarse'),        onPressed: () {          Provider.of<AuthenticationService>(context, listen: false).signUp(              email: emailController.text.trim(),              password: passwordController.text.trim(),              context: context);        },      );    }  }  
https://stackoverflow.com/questions/65543267/unable-to-navigate-to-homepage-based-on-auth-state January 03, 2021 at 03:36AM

没有评论:

发表评论