Home > Software design >  Flutter : SnackBar not showing upon authentication error
Flutter : SnackBar not showing upon authentication error

Time:10-13

I am trying to show a snackBar when an error occurs during login and signup with FirebaseAuth. My snackBar is not showing. I only see the error message printed in my terminal. Please assist, I am not sure what I am doing wrong. I seem to have missed something...

I've tried everything, still no luck

Auth Screen

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_svg/svg.dart';
import '../widgets/auth/auth_form.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

class AuthScreen extends StatefulWidget {
  const AuthScreen({Key? key}) : super(key: key);
  static const routeName = '/auth_screen';
  @override
  _AuthScreenState createState() => _AuthScreenState();
}

class _AuthScreenState extends State<AuthScreen> {
  final _auth = FirebaseAuth.instance;
  var _isLoading = false;

  

  void _submitAuthForm(
    String email,
    String password,
    String displayName,
    String phoneNumber,
    bool isLogin,
    BuildContext ctx,
  ) async {
    UserCredential authResult;

    try {
      setState(() {
        _isLoading = true;
      });
      if (isLogin) {
        authResult = await _auth.signInWithEmailAndPassword(
          email: email,
          password: password,
        );
      } else {
        authResult = await _auth.createUserWithEmailAndPassword(
            email: email, password: password);

        await FirebaseFirestore.instance
            .collection('userProfile')
            .doc(authResult.user!.uid)
            .set(
          {
            'displayName': displayName,
            'email': email,
            'phoneNumber': phoneNumber,
            'uid': authResult.user!.uid,
          },
        );
      }
    } on PlatformException catch (err) {
      var message = 'An error occured. Please check your credentials.';

      if (err.message != null) {
        message = err.message!;
      }

      ScaffoldMessenger.of(ctx).showSnackBar(
        SnackBar(
          content: Text(message),
          backgroundColor: Theme.of(ctx).errorColor,
        ),
      );

      setState(() {
        _isLoading = false;
      });
    } catch (err) {
      print(err);
      setState(() {
        _isLoading = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        margin: const EdgeInsets.only(top: 25.0),
        padding: const EdgeInsets.all(35.0),
        child: SingleChildScrollView(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              SizedBox(
                height: MediaQuery.of(context).size.height * 0.3,
                child: SvgPicture.asset('images/login.svg'),
              ),
              const SizedBox(
                height: 20.0,
              ),
              const SizedBox(
                height: 10.0,
              ),
              AuthForm(
                _submitAuthForm,
                _isLoading,
              )
            ],
          ),
        ),
      ),
    );
  }
}

CodePudding user response:

You are printing errors that are not PlatformException.

    } on PlatformException catch (err) {
      var message = 'An error occured. Please check your credentials.';

      if (err.message != null) {
        message = err.message!;
      }

      ScaffoldMessenger.of(ctx).showSnackBar(
        SnackBar(
          content: Text(message),
          backgroundColor: Theme.of(ctx).errorColor,
        ),
      );

      setState(() {
        _isLoading = false;
      });
    } catch (err) {
      print(err);

      // Missing snackbar
      ScaffoldMessenger.of(ctx).showSnackBar(
        SnackBar(
          content: Text('$err'), // Change to something to show a meaningful error message
          backgroundColor: Theme.of(ctx).errorColor,
        ),
      );

      setState(() {
        _isLoading = false;
      });
    }

CodePudding user response:

Use this function to call snackbar.

showsnackbar(String message, context) {
final snackbar = SnackBar(
  content: Text(message),
  duration: Duration(seconds: 2),
);
ScaffoldMessenger.of(context).hideCurrentSnackBar();
ScaffoldMessenger.of(context).showSnackBar(snackbar);
 }
  • Related