首页 > 解决方案 > Flutter - 未处理的异常:NoSuchMethodError:在 null 上调用了方法“验证”

问题描述

我有以下NoSuchMethodError异常:

W/IInputConnectionWrapper(15165): getTextAfterCursor on inactive InputConnection
W/IInputConnectionWrapper(15165): getTextBeforeCursor on inactive InputConnection
W/IInputConnectionWrapper(15165): getSelectedText on inactive InputConnection
W/IInputConnectionWrapper(15165): getTextAfterCursor on inactive InputConnection
E/flutter (15165): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: NoSuchMethodError: The method 'validate' was called on null.
E/flutter (15165): Receiver: null
E/flutter (15165): Tried calling: validate()
E/flutter (15165): #0      Object.noSuchMethod (dart:core-patch/object_patch.dart:53:5)
E/flutter (15165): #1      _SignUpState.build.<anonymous closure> (package:meds_at_home/pages/signup.dart:246:55)
E/flutter (15165): #2      _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:706:14)
E/flutter (15165): #3      _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:789:36)
E/flutter (15165): #4      GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:182:24)
E/flutter (15165): #5      TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:486:11)
E/flutter (15165): #6      BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:264:5)
E/flutter (15165): #7      BaseTapGestureRecognizer.acceptGesture (package:flutter/src/gestures/tap.dart:236:7)
E/flutter (15165): #8      GestureArenaManager.sweep (package:flutter/src/gestures/arena.dart:156:27)
E/flutter (15165): #9      GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:222:20)
E/flutter (15165): #10     GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:198:22)
E/flutter (15165): #11     GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:156:7)
E/flutter (15165): #12     GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:102:7)
E/flutter (15165): #13     GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:86:7)
E/flutter (15165): #14     _rootRunUnary (dart:async/zone.dart:1138:13)
E/flutter (15165): #15     _CustomZone.runUnary (dart:async/zone.dart:1031:19)
E/flutter (15165): #16     _CustomZone.runUnaryGuarded (dart:async/zone.dart:933:7)
E/flutter (15165): #17     _invoke1 (dart:ui/hooks.dart:273:10)
E/flutter (15165): #18     _dispatchPointerDataPacket (dart:ui/hooks.dart:182:5)

这是我的颤振医生

Doctor summary (to see all details, run flutter doctor -v):
[√] Flutter (Channel stable, v1.12.13+hotfix.8, on Microsoft Windows [Version 10.0.18363.657], locale en-US)

[√] Android toolchain - develop for Android devices (Android SDK version 29.0.3)
[√] Android Studio (version 3.6)
[!] VS Code (version 1.42.1)
    X Flutter extension not installed; install from
      https://marketplace.visualstudio.com/items?itemName=Dart-Code.flutter
[√] Connected device (1 available)

! Doctor found issues in 1 category.

这是我的注册码:

import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:meds_at_home/pages/home.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

import '../db/users.dart';

class SignUp extends StatefulWidget {
  @override
  _SignUpState createState() => _SignUpState();
}

class _SignUpState extends State<SignUp> {
  final FirebaseAuth firebaseAuth = FirebaseAuth.instance;
  final _formKey = GlobalKey<FormFieldState>();
  UserServices _userServices = UserServices();
  TextEditingController _email = TextEditingController();
  TextEditingController _password = TextEditingController();
  TextEditingController _name = TextEditingController();
  TextEditingController _confirmPassword = TextEditingController();
  String gender;
  String groupvalue = "Male";
  bool hidePass = true;
  bool hidePass1 = true;
  bool loading = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(children: <Widget>[
        Image.asset(
          'images/back1.webp',
          fit: BoxFit.fill,
          width: double.infinity,
          height: double.infinity,
        ),
//            Container(
//              alignment: Alignment.topRight,
//              child: Image.asset('images/logo.png'),
//              width: 240.0,
//              height: 200.0,
//            ),
        Container(
          color: Colors.black12.withOpacity(0.4),
          width: double.infinity,
          height: double.infinity,
        ),
        Center(
          child: Padding(
            padding: const EdgeInsets.only(top: 150.0),
            child: Center(
              child: Form(
                  key: _formKey,
                  child: ListView(
                    children: <Widget>[
                      Padding(
                        padding:
                        const EdgeInsets.fromLTRB(14.0, 4.0, 14.0, 4.0),
                        child: Material(
                          borderRadius: BorderRadius.circular(10.0),
                          color: Colors.white.withOpacity(0.8),
                          elevation: 0.0,
                          child: Padding(
                            padding: const EdgeInsets.only(left: 12.0),
                            child: TextFormField(
                              controller: _name,
                              decoration: InputDecoration(
                                border: InputBorder.none,
                                hintText: "Full Name",
                                icon: Icon(Icons.person),
                              ),
                              validator: (value) {
                                if (value.isEmpty) {
                                  return "The name field cannot be empty";
                                }
                                return null;
                              },
                            ),
                          ),
                        ),
                      ),
                      Padding(
                        padding:
                        const EdgeInsets.fromLTRB(14.0, 4.0, 14.0, 4.0),
                        child: new Container(
                          color: Colors.white.withOpacity(0.2),
                          child: Row(
                            children: <Widget>[
                              Expanded(
                                  child: ListTile(
                                    title: Text(
                                      "Male",
                                      textAlign: TextAlign.end,
                                      style: TextStyle(color: Colors.white),
                                    ),
                                    trailing: Radio(
                                        value: "Male",
                                        groupValue: groupvalue,
                                        onChanged: (e) => valueChanged(e)),
                                  )),
                              Expanded(
                                  child: ListTile(
                                    title: Text(
                                      "Female",
                                      textAlign: TextAlign.end,
                                      style: TextStyle(color: Colors.white),
                                    ),
                                    trailing: Radio(
                                        value: "Female",
                                        groupValue: groupvalue,
                                        onChanged: (e) => valueChanged(e)),
                                  )),
                            ],
                          ),
                        ),
                      ),
                      Padding(
                        padding:
                        const EdgeInsets.fromLTRB(14.0, 4.0, 14.0, 4.0),
                        child: Material(
                          borderRadius: BorderRadius.circular(10.0),
                          color: Colors.white.withOpacity(0.8),
                          elevation: 0.0,
                          child: Padding(
                            padding: const EdgeInsets.only(left: 12.0),
                            child: TextFormField(
                              controller: _email,
                              decoration: InputDecoration(
                                border: InputBorder.none,
                                hintText: "Email",
                                icon: Icon(Icons.email),
                              ),
                              // ignore: missing_return
                              validator: (value) {
                                if (value.isEmpty) {
                                  Pattern pattern =
                                      r'^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$';
                                  RegExp regex = new RegExp(pattern);
                                  if (!regex.hasMatch(value))
                                    return 'Please make sure your email address is valid';
                                  else
                                    return null;
                                }
                              },
                            ),
                          ),
                        ),
                      ),
                      Padding(
                        padding:
                        const EdgeInsets.fromLTRB(14.0, 4.0, 14.0, 4.0),
                        child: Material(
                          borderRadius: BorderRadius.circular(10.0),
                          color: Colors.white.withOpacity(0.8),
                          elevation: 0.0,
                          child: Padding(
                            padding: const EdgeInsets.only(left: 12.0),
                            child: ListTile(
                              title: TextFormField(
                                controller: _password,
                                obscureText: hidePass,
                                decoration: InputDecoration(
                                  border: InputBorder.none,
                                  hintText: "Password",
                                  icon: Icon(Icons.lock_outline),
                                ),
                                validator: (value) {
                                  if (value.isEmpty) {
                                    return "The password field cannot be empty";
                                  } else if (value.length < 6) {
                                    return "The password should have  at least 6 characters ";
                                  }
                                  return null;
                                },
                              ),
                              trailing: IconButton(
                                  icon: Icon(Icons.remove_red_eye),
                                  onPressed: () {
                                    setState(() {
                                      if (hidePass == false) {
                                        hidePass = true;
                                      } else {
                                        hidePass = false;
                                      }
                                    });
                                  }),
                            ),
                          ),
                        ),
                      ),
                      Padding(
                        padding:
                        const EdgeInsets.fromLTRB(14.0, 4.0, 14.0, 4.0),
                        child: Material(
                          borderRadius: BorderRadius.circular(10.0),
                          color: Colors.white.withOpacity(0.8),
                          elevation: 0.0,
                          child: Padding(
                            padding: const EdgeInsets.only(left: 12.0),
                            child: ListTile(
                              title: TextFormField(
                                controller: _confirmPassword,
                                obscureText: hidePass1,
                                decoration: InputDecoration(
                                  border: InputBorder.none,
                                  hintText: "Confirm Password",
                                  icon: Icon(Icons.lock_outline),
                                ),
                                validator: (value) {
                                  if (value.isEmpty) {
                                    return "The password field cannot be empty";
                                  } else if (value.length < 6) {
                                    return "The password should have  at least 6 characters";
                                  } else if (_password.text != value) {
                                    return "Password Don't match";
                                  }
                                  return null;
                                },
                              ),
                              trailing: IconButton(
                                  icon: Icon(Icons.remove_red_eye),
                                  onPressed: () {
                                    setState(() {
                                      if (hidePass1 == false) {
                                        hidePass1 = true;
                                      } else {
                                        hidePass1 = false;
                                      }
                                    });
                                  }),
                            ),
                          ),
                        ),
                      ),
                      Padding(
                        padding:
                        const EdgeInsets.fromLTRB(14.0, 4.0, 14.0, 4.0),
                        child: Material(
                            borderRadius: BorderRadius.circular(20.0),
                            color: Colors.blueAccent,
                            elevation: 0.0,
                            child: MaterialButton(
                              onPressed: () async {
                                _formKey.currentState.validate();
                              },
//                  async{
//                    if(_formKey.currentState.validate()){
//                      if(!await user.signIn(_email.text, _password.text))
//                        _key.currentState.showSnackBar(SnackBar(content: Text("Sign in failed")));
//                    }
//                  },
                              minWidth: MediaQuery
                                  .of(context)
                                  .size
                                  .width,
                              child: Text(
                                "Register",
                                textAlign: TextAlign.center,
                                style: TextStyle(
                                    color: Colors.white,
                                    fontWeight: FontWeight.bold,
                                    fontSize: 20.0),
                              ),
                            )),
                      ),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                        children: <Widget>[
                          Padding(
                              padding: const EdgeInsets.all(6.0),
                              child: InkWell(
                                  onTap: () {
                                    Navigator.pop(context);
                                  },
                                  child: Text(
                                    "I already have an account",
                                    textAlign: TextAlign.center,
                                    style: TextStyle(
                                        color: Colors.black,
                                        fontWeight: FontWeight.bold,
                                        fontSize: 16),
                                  ))),
                        ],
                      ),
                    ],
                  )),
            ),
          ),
        ),

        Visibility(
            visible: loading ?? true,
            child: Center(
              child: Container(
                alignment: Alignment.center,
                color: Colors.white.withOpacity(0.2),
                child: CircularProgressIndicator(
                  valueColor: AlwaysStoppedAnimation<Color>(Colors.blueAccent),
                ),
              ),
            )),
      ]),

//
    );
  }

  valueChanged(e) {
    setState(() {
      if (e == "Male") {
        groupvalue = e;
        gender = e;
      } else if (e == "Female") {
        groupvalue = e;
        gender = e;
      }
    });
  }

  Future validate() async {
    FormFieldState formState = _formKey.currentState;

    if (_formKey.currentState.validate()) {
      formState.reset();
      FirebaseUser user = await firebaseAuth.currentUser();
      if (user == null) {
        firebaseAuth
            .createUserWithEmailAndPassword(
            email: _email.text, password: _password.text)
            .then((authResult) =>
        {
          _userServices.createUser(
              user.uid,
              {
                "username": user.displayName,
                "email": user.email,
                "gender": gender,
              }
          )
        }).catchError((err) => {print(err.toString())});
        Navigator.pushReplacement(
            context, MaterialPageRoute(builder: (context) => HomePage()));
      }
    }
  }

}

这是我的数据库/用户页面

import 'package:firebase_database/firebase_database.dart';


class UserServices {
  FirebaseDatabase _database = FirebaseDatabase.instance;
  String ref = "users";

  createUser(String uid,Map value) {
    _database
        .reference()
        .child("$ref/$uid")
        .set(value)
        .catchError((e) => {print(e.toString())});
  }
}

我尝试了很多事情来解决,但没有奏效。

标签: flutterdart

解决方案


也许您应该检查是否所有表单变量都分配了值,其中一个是 null 这就是您收到错误的原因


推荐阅读