Flutter Assertion Error: flutter: 'package:firebase_auth_platform_interface/src/method_channel/method_channel_user_credential.dart': Failed assertion

*爱你&永不变心* 提交于 2021-01-29 05:00:50

问题


I am using Firebase and keep getting this annoying message when I click on the Sign Up button :

flutter: 'package:firebase_auth_platform_interface/src/method_channel/method_channel_user_credential.dart': Failed assertion: line 14 pos 16: 'data != null': is not true.

The code works fine. The app is built and run successfully. This happens when I enter my phone, email and password and click on the signup button. My code is:

import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';

class Auth extends StatefulWidget {
  @override
  _AuthState createState() => _AuthState();
}

class _AuthState extends State<Auth> {
  final _formKey = GlobalKey<FormState>();
  final _password = TextEditingController(),
      _email = TextEditingController(),
      _phone = TextEditingController();
  final _auth = FirebaseAuth.instance;

  bool willLogin = true;
  bool showPassword = false;
  void _login() async {
    _formKey.currentState.validate();
    try {
      final existingUser = await _auth.signInWithEmailAndPassword(
          email: _email.text, password: _password.text);
      if (existingUser != null) {
        Navigator.pushNamed(context, '/home');
      }
    } catch (e) {
      print(e);
    }
  }

  void _signup() async {
    _formKey.currentState.validate();
    try {
      final newUser = await _auth.createUserWithEmailAndPassword(
          email: _email.text, password: _password.text);
      if (newUser != null) {
        Navigator.pushNamed(context, '/home');
      }
    } catch (e) {
      print(e);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Dog SOS"),
        leading: Icon(Icons.pets),
      ),
      body: Form(
        key: _formKey,
        child: ListView(
          padding: const EdgeInsets.all(24),
          children: [
            const SizedBox(
              height: 10,
            ),
            Center(
              child: CircleAvatar(
                backgroundColor: Theme.of(context).primaryColor,
                child: Icon(
                  Icons.shield,
                  color: Colors.white,
                  size: 50,
                ),
                radius: 60,
              ),
            ),
            const SizedBox(
              height: 20,
            ),
            if (!willLogin) ...[
              TextFormField(
                decoration: InputDecoration(
                  labelText: "Phone",
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(8),
                  ),
                ),
                keyboardType: TextInputType.phone,
                textInputAction: TextInputAction.next,
                controller: _phone,
                validator: (value) =>
                    value.isEmpty ? "Please Enter Phone Number" : null,
              ),
              const SizedBox(
                height: 10,
              ),
            ],
            TextFormField(
              decoration: InputDecoration(
                labelText: "Email",
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(8),
                ),
              ),
              keyboardType: TextInputType.emailAddress,
              textInputAction: TextInputAction.next,
              controller: _email,
              validator: (value) => value.isEmpty ? "Please Enter Email" : null,
            ),
            const SizedBox(
              height: 10,
            ),
            TextFormField(
              decoration: InputDecoration(
                labelText: "Password",
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(8),
                ),
                suffixIcon: IconButton(
                  icon: Icon(
                    showPassword
                        ? Icons.visibility_off_outlined
                        : Icons.visibility_outlined,
                  ),
                  onPressed: () {
                    setState(() {
                      showPassword = !showPassword;
                    });
                  },
                ),
              ),
              obscureText: !showPassword,
              textInputAction: TextInputAction.done,
              controller: _password,
              validator: (value) =>
                  value.isEmpty ? "Please Enter Password" : null,
            ),
            const SizedBox(
              height: 10,
            ),
            RaisedButton(
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(8),
              ),
              child: Text(
                willLogin ? "\nLOGIN\n" : "\nSIGN UP\n",
                style: Theme.of(context)
                    .textTheme
                    .button
                    .copyWith(color: Colors.white),
              ),
              color: Theme.of(context).primaryColor,
              onPressed: () {
                if (_formKey.currentState.validate()) {
                  _formKey.currentState.save();
                  _login();
                }
              },
            ),
            Row(
              children: [
                Text(willLogin
                    ? "Don't have an account?"
                    : "Already have an account?"),
                FlatButton(
                  child: Text(
                    willLogin ? "Create One." : "Login.",
                    style: Theme.of(context).textTheme.button.copyWith(
                          color: Theme.of(context).primaryColor,
                        ),
                  ),
                  onPressed: () {
                    setState(() {
                      willLogin = !willLogin;
                      if (_formKey.currentState.validate()) {
                        _formKey.currentState.save();
                        _signup();
                      }
                    });
                  },
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}

回答1:


The problem is that here:

  onPressed: () {
                    setState(() {
                      willLogin = !willLogin;
                      if (_formKey.currentState.validate()) {
                        _formKey.currentState.save();
                        _signup();
                      }
                    });
                  },

on click of this button, you are using setState and assign willLogin equal to false, therefore it is not even calling _signup() since it is immediately calling the build() method. So now you have willLogin = false, which is showing you this in the screen this widget:

child: Text(
                willLogin ? "\nLOGIN\n" : "\nSIGN UP\n",
                style: Theme.of(context)
                    .textTheme
                    .button
                    .copyWith(color: Colors.white),
              ),
              color: Theme.of(context).primaryColor,
              onPressed: () {
                if (_formKey.currentState.validate()) {
                  _formKey.currentState.save();
                  _login();
                }
              },
            ),

Here according to your code if willLogin is false then show Sign up text and call _login() method. Since you are calling _login() method for sign up you are getting this error since the user is not even registered in firebase authentication.


What you need to do is change the logic, either remove setState, this way _signup() method will be called, or keep it as it is but change _login() to _signup().

Try the following:

child: Text(
                willLogin ? "\nLOGIN\n" : "\nSIGN UP\n",
                style: Theme.of(context)
                    .textTheme
                    .button
                    .copyWith(color: Colors.white),
              ),
              color: Theme.of(context).primaryColor,
              onPressed: () {
                if (_formKey.currentState.validate()) {
                  _formKey.currentState.save();
                  willLogin ? _login() : _signup();
                }
              },
            ),


来源:https://stackoverflow.com/questions/65337850/flutter-assertion-error-flutter-packagefirebase-auth-platform-interface-src

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!