首页 > 解决方案 > 颤振断言错误:颤振:'package:firebase_auth_platform_interface/src/method_channel/method_channel_user_credential.dart':断言失败

问题描述

我正在使用 Firebase 并在单击“注册”按钮时不断收到这条烦人的消息:

颤振:'package:firebase_auth_platform_interface/src/method_channel/method_channel_user_credential.dart':断言失败:第 14 行 pos 16:'data != null':不正确。

代码工作正常。该应用程序已构建并成功运行。当我输入我的手机、电子邮件和密码并单击注册按钮时,就会发生这种情况。我的代码是:

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();
                      }
                    });
                  },
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}

标签: firebaseflutterdartfirebase-authentication

解决方案


问题在于:

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

单击此按钮时,您正在使用setState并分配willLogin等于 false,因此它甚至没有调用_signup(),因为它正在立即调用该build()方法。所以现在你有了willLogin = false,它在屏幕上向你展示了这个小部件:

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();
                }
              },
            ),

根据您的代码,如果 willLogin 为 false,则显示Sign up文本和调用_login()方法。由于您正在调用_login()注册方法,因此您收到此错误,因为用户甚至没有在 firebase 身份验证中注册。


您需要做的是更改逻辑,或者 remove setState,这样_signup()方法将被调用,或者保持原样但更改_login()_signup().

尝试以下操作:

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();
                }
              },
            ),

推荐阅读