首页 > 解决方案 > Flutter 错误,手势捕获的异常,处理手势时引发以下 _CastError:Null check operator used on a null value

问题描述

每当我尝试登录并点击登录按钮时,我都会遇到用于空值的空检查运算符的此类问题。

这是我收到的错误消息:

════════ 手势捕捉到异常═════════════════════════════════════════════════════════ ═════</p>

The following _CastError was thrown while handling a gesture:

Null check operator used on a null value
When the exception was thrown, this was the stack

#0      _AuthFormState._trySubmit                 package://FlutterChat/widgets/auth_form.dart:46

#1     _InkResponseState._handleTap

#2      GestureRecognizer.invokeCallback

#3      TapGestureRecognizer.handleTapUp

#4      BaseTapGestureRecognizer._checkUp

Handler: "onTap"

Recognizer: TapGestureRecognizer#c9833

debugOwner: GestureDetector

state: possible

won arena

finalPosition: Offset(165.5, 228.0)

finalLocalPosition: Offset(19.0, 13.5)

button: 1

sent tap down

这是我的 auth_form.dart 文件:

    import 'package:flutter/material.dart';
import 'dart:io';
import './user_image_picker.dart';

class AuthForm extends StatefulWidget {
  AuthForm(this.submitFn, this.isLoading);

  final bool isLoading;
  final Future<void> Function(String email, String password, String username,
      File image, bool isLogin, BuildContext ctx) submitFn;
  @override
  _AuthFormState createState() => _AuthFormState();
}

class _AuthFormState extends State<AuthForm> {
  final _formKey = GlobalKey<FormState>();
  var _isLogin = true;
  dynamic _userEmail = '';
  dynamic _userName = '';
  dynamic _userPassword;
  File? _userImageFile;

  void _pickedImage(File? image) {
    _userImageFile = image;
  }

  //Form validation and save
  _trySubmit() {
    final isValid = _formKey.currentState?.validate();
    FocusScope.of(context).unfocus();

    if (_userImageFile == null && !_isLogin) {
      ScaffoldMessenger.of(context).showSnackBar(SnackBar(
        content: Text('Please Select an Image'),
        backgroundColor: Theme.of(context).errorColor,
      ));

      return;
    }
    if (isValid!) {
      _formKey.currentState?.save();
      widget.submitFn(
        _userEmail?.trim(),
        _userPassword?.trim(),
        _userName?.trim(),
        _userImageFile!,
        _isLogin,
        context,
      );
    }
  }

  //Form Widget

  @override
  Widget build(BuildContext context) {
    return new Builder(
      builder: (context) {
        return Center(
          child: Card(
            margin: EdgeInsets.all(20),
            child: SingleChildScrollView(
              child: Padding(
                padding: EdgeInsets.all(16),
                child: Form(
                  key: _formKey,
                  child: Column(
                    children: [
                      if (!_isLogin) UserImagePicker(_pickedImage),
                      TextFormField(
                        key: ValueKey('email'),
                        autocorrect: false,
                        textCapitalization: TextCapitalization.none,
                        enableSuggestions: false,
                        validator: (value) {
                          if (value?.isEmpty == null || !value!.contains('@')) {
                            return 'Please Enter valid Email Address.';
                          }
                          return null;
                        },
                        keyboardType: TextInputType.emailAddress,
                        decoration: InputDecoration(
                          labelText: 'Email Address',
                        ),
                        onSaved: (value) {
                          _userEmail = value;
                        },
                      ),
                      if (!_isLogin)
                        TextFormField(
                            key: ValueKey('username'),
                            autocorrect: true,
                            textCapitalization: TextCapitalization.words,
                            enableSuggestions: false,
                            validator: (value) {
                              if (value!.isEmpty) {
                                return 'Please Enter Username.';
                              }
                              return null;
                            },
                            decoration: InputDecoration(
                              labelText: 'Username',
                            ),
                            onSaved: (value) {
                              _userName = value;
                            }),
                      TextFormField(
                          key: ValueKey('password'),
                          validator: (value) {
                            if (value?.isEmpty == null || value!.length < 7) {
                              return 'Password must be atleast 7 characters long';
                            }
                            return null;
                          },
                          obscureText: true,
                          decoration: InputDecoration(
                            labelText: 'Password',
                          ),
                          onSaved: (value) {
                            _userPassword = value;
                          }),
                      SizedBox(
                        height: 12,
                      ),
                      if (widget.isLoading) CircularProgressIndicator(),
                      if (!widget.isLoading)
                        ElevatedButton(
                          child: Text(_isLogin ? 'Login' : 'Signup'),
                          onPressed: _trySubmit,
                        ),
                      if (!widget.isLoading)
                        TextButton(
                          child: Text(_isLogin
                              ? 'Create a new account'
                              : 'I already have an account'),
                          style: TextButton.styleFrom(primary: Colors.pink),
                          onPressed: () {
                            setState(() {
                              _isLogin = !_isLogin;
                            });
                          },
                        ),
                    ],
                  ),
                ),
              ),
            ),
          ),
        );
      },
    );
  }
}

这是我的 auth_screen.dart 文件:

import 'package:FlutterChat/screens/conversion_screen.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../widgets/auth_form.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'dart:io';
import 'package:firebase_storage/firebase_storage.dart';
//import 'package:firebase_core/firebase_core.dart';

class AuthScreen extends StatefulWidget {
  
  @override
  _AuthScreenState createState() => _AuthScreenState();
}

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

  //Submit AuthCredential Function

  Future<void> submitAuthForm(String? email, String? password, String? username,
      File? image, bool isLogin, BuildContext ctx) async {
    UserCredential userCredential;

    try {
      setState(() {
        _isLoading = true;
      });

      if (isLogin) {
        userCredential = await FirebaseAuth.instance
            .signInWithEmailAndPassword(email: email!, password: password!);
        Navigator.push(
            context,
            MaterialPageRoute(
                builder: (context) => ConversionScreen()));
      } else {
        userCredential = await FirebaseAuth.instance
            .createUserWithEmailAndPassword(email: email!, password: password!);
        Navigator.push(
            context,
            MaterialPageRoute(
                builder: (context) => ConversionScreen()));

        final ref = FirebaseStorage.instance
            .ref()
            .child('user_image')
            .child(userCredential.user!.uid + '.jpg');

        await ref.putFile(image!).whenComplete(() => print('Image Upload'));

        final url = await ref.getDownloadURL();

        await FirebaseFirestore.instance
            .collection('users')
            .doc(userCredential.user?.uid)
            .set({
          'username': username,
          'email': email,
          'imageUrl': url,
        });
      }
    } on PlatformException catch (error) {
      dynamic message = 'An error occured, please check your credentials!';

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

      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text(message),
          backgroundColor: Theme.of(ctx).errorColor,
        ),
      );
      setState(() {
        _isLoading = false;
      });
    } catch (error) {
      print(error);
      setState(() {
        _isLoading = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Theme.of(context).primaryColor,
      body: AuthForm(submitAuthForm, _isLoading),
    );
  }
}

如果有人知道,请帮助我。

标签: androidflutterdart

解决方案


由于这条线而发生错误,

_userImageFile!,

我怀疑你的if条款,

if (_userImageFile == null && !_isLogin) {

没有保护它不为 not null,因为尽管为空,但如果为真,则该if子句将为假。_isLogin_userImageFile

解决此问题的一种方法是删除bang运算符,因为您也可以submitFn在您_isLogin为真时调用 the ,在这种情况下,您肯定不会有非 null _userImageFile

_userImageFile, // while calling widget.submitFn

然后确保将“submitFn”函数类型更改为

final Future<void> Function(String email, String password, String username,
  // add the ? for File image
  File? image, bool isLogin, BuildContext ctx) submitFn;

既然您submitAuthForm已经说过File? image,那里没有什么可改变的。


推荐阅读