当前位置: 首页 > 知识库问答 >
问题:

Flutter错误,由手势捕获的异常,在处理手势时抛出了以下_casterror:Null检查操作符用于Null值

单于亮
2023-03-14

每当我尝试登录并点击登录按钮时,我就会遇到这种类型的问题,即对空值使用空检查操作符。

这是我得到的错误消息:

被打手势的例外情况被打手势的例外情况被打手势的例外情况被打手势的例外情况被打手势的例外情况被打手势的例外情况被打手势的例外情况被打手势的例外情况被打手势的例外情况被打手势的例外情况被打手势的例外情况被打手势的例外情况被打手势的例外情况被打手势的例外情况被打手势的例外情况被打手势的例外情况被打手势的例外情况被打手势的例外情况

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

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

共有1个答案

裴永年
2023-03-14

此错误是由于此行而发生的,

_userImageFile!,

我怀疑您的if子句,

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

并不保护它不为null,因为如果_islogin为true,尽管_userimageFile为null,if子句将为false。

_userImageFile, // while calling widget.submitFn
final Future<void> Function(String email, String password, String username,
  // add the ? for File image
  File? image, bool isLogin, BuildContext ctx) submitFn;
 类似资料:
  • Weex 封装了原生的触摸事件以提供手势系统。使用手势类似于在 Weex 中使用事件,只需在节点上监听手势即可。 手势类型 目前,仅支持以下四种手势类型: touch: 当触摸到一个点,移动或从触摸面移开时触发 touch 手势。触摸手势很精准,它会返回所有详细的事件信息。所以,监听 touch 手势可能很慢,即使只移动一丁点也需要处理大量事件。有三种类型的 touch 手势: type 描述 t

  • 本文向大家介绍Android触摸及手势操作GestureDetector,包括了Android触摸及手势操作GestureDetector的使用技巧和注意事项,需要的朋友参考一下 现在的智能手机不敢说百分百的都是触摸屏,也应该是百分之九九以上为触摸屏了,触摸屏为我们操作无键盘、无鼠标的手机系统带来了很多的便利。当用户触摸屏幕时会产生很多的触摸事件,down、up、move等等。View类有个Vie

  • 本文向大家介绍Android手势操作识别详解,包括了Android手势操作识别详解的使用技巧和注意事项,需要的朋友参考一下 首先,在Android系统中,每一次手势交互都会依照以下顺序执行。 1. 接触接触屏一刹那,触发一个MotionEvent事件。 2. 该事件被OnTouchListener监听,在其onTouch()方法里获得该MotionEvent对象。 3. 通过GestureDete

  • 本文向大家介绍Android 手势操作编程详解,包括了Android 手势操作编程详解的使用技巧和注意事项,需要的朋友参考一下       手势操作在我们使用智能设备的过程中奉献了不一样的体验。Android开发中必然会进行手势操作方面的编程。那么它的原理是怎样的呢?我们如何进行手势操作编程呢?        手势操作原理        首先,在Android系统中,每一次手势交互都会依照以下顺序

  • rank ▲ ✰ vote url 69 352 48 520 url 手动抛出异常 我想故意制造一个错误,所以我可以转到excepy:语句 我怎么做? 不能在Pythonic了; raise Exception("I know python!") 想得到更多信息,看这里