0

I have shown snackbar after incorrect login in flutter. But after appearing once, the snackbar is appearing repeatedly without even pressing the submit button. Where am I doing wrong? Please help. Here is my code below. In the snapshot.data.status == '2' portion I have showing the snackbar. I want the snackbar to be displayed only when the login falis i.e. when snapshot.data.status == '2' satisfies.

class MyApp extends StatefulWidget {
  final UserDataStorage storage;

  MyApp({Key key, @required this.storage}) : super(key: key);
  @override
  State<StatefulWidget> createState() {
    return _TextControl();
  }
}

class _TextControl extends State<MyApp> {
  final _formKey = GlobalKey<FormState>();
  bool snackBarActive = false;
  @override
  void initState() {
    super.initState();
    widget.storage.readCounter().then((int value) {
      if (value > 0) {
        Navigator.push(
          context,
          MaterialPageRoute(
              builder: (context) => TextInput(storage: GetDataStorage())),
        );
      }
    });
  }

  final TextEditingController _controller = TextEditingController();
  final TextEditingController _controller2 = TextEditingController();

  @override
  void dispose() {
    _controller.dispose();
    _controller2.dispose();
    super.dispose();
  }

  Future<Login> _futureLogin;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        backgroundColor: Colors.purple[400],
        title: Text('Login'),
      ),
      body: Container(
          padding: EdgeInsets.only(left: 15, top: 20, right: 15, bottom: 20),
          child: Column(
            children: <Widget>[
              Center(
                child: Image(image: AssetImage('assets/images/logo.png')),
              ),
              Container(
                padding: EdgeInsets.only(left: 0, top: 20, right: 0, bottom: 0),
                child: Form(
                    key: _formKey,
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: <Widget>[
                        Column(
                          children: <Widget>[
                            TextFormField(
                              controller: _controller,
                              decoration: InputDecoration(hintText: 'Email'),
                              keyboardType: TextInputType.emailAddress,
                              validator: (value) {
                                if (value.isEmpty || !value.isValidEmail()) {
                                  return 'Please enter valid email.';
                                }
                                return null;
                              },
                            ),
                            TextFormField(
                              controller: _controller2,
                              decoration: InputDecoration(hintText: 'Password'),
                              obscureText: true,
                              validator: (value) {
                                if (value.isEmpty) {
                                  return 'Please enter password.';
                                }
                                return null;
                              },
                            ),
                            Container(
                              margin: EdgeInsets.only(top: 10.0),
                              child: RaisedButton(
                                color: Colors.purple[400],
                                padding: EdgeInsets.only(
                                    left: 130, top: 10, right: 130, bottom: 10),
                                textColor: Colors.white,
                                onPressed: () {
                                  if (_formKey.currentState.validate()) {
                                    setState(() {
                                      _futureLogin = userLogin(
                                          _controller.text, _controller2.text);
                                    });
                                    Scaffold.of(context)
                                        .removeCurrentSnackBar();
                                  }
                                },
                                child: Text('Login',
                                    style: TextStyle(fontSize: 18.0)),
                              ),
                            ),
                          ],
                        ),
                        (_futureLogin != null)
                            ? FutureBuilder<Login>(
                                future: _futureLogin,
                                builder: (context, snapshot) {
                                  if (snapshot.hasData) {
                                    if (snapshot.data.status == '1') {
                                      widget.storage
                                          .writeCounter(snapshot.data.usrid);
                                      Navigator.push(
                                        context,
                                        MaterialPageRoute(
                                            builder: (context) => TextInput(
                                                storage: GetDataStorage())),
                                      );
                                    } else if (snapshot.data.status == '2') {
                                      snackBarActive = true;
                                      if (snackBarActive) {
                                        Scaffold.of(context)
                                            .showSnackBar(SnackBar(
                                              content: Text(
                                                  "Invalid login credentials.",
                                                  style: TextStyle(
                                                      color: Colors.red[100])),
                                            ))
                                            .closed
                                            .whenComplete(() {
                                          setState(() {
                                            snackBarActive = false;
                                          });
                                        });
                                      }

                                      return Text('');
                                    }
                                  } else if (snapshot.hasError) {
                                    return Text("${snapshot.error}");
                                  }
                                  return Center(
                                      child: CircularProgressIndicator());
                                },
                              )
                            : Text(''),
                      ],
                    )),
              ),
            ],
          )),
    );
  }
}
Ayan
  • 165
  • 1
  • 1
  • 9
  • Yes I am doing exactly this. If you think any other way to do it, please mention. I was previously using showSnackBar() in the snapshot.data.status == '2' block. But in this case, after login fails once, snackbar was appearing even the login succeeded. If you suggest any other way, please share. – Ayan Dec 11 '20 at 11:06

2 Answers2

0

Have you tried changing the status variable to 1 after checking snapshot.data.status == '2', try that and it might help you stop the continuous snackbar widget showing up.

RobHG
  • 115
  • 6
  • Thanks for the help. But I cannot set status to 1 because it is the login success status and after login success user will be redirected to another screen. – Ayan Dec 14 '20 at 07:38
0

Write this code before calling snackbar,

ScaffoldMessenger.of(context).hideCurrentSnackBar();

example;

getSnackBar(BuildContext context, String snackText) {
ScaffoldMessenger.of(context).hideCurrentSnackBar();
ScaffoldMessenger.of(context)
    .showSnackBar(SnackBar(content: Text(snackText)));

}