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

颤振错误,对空值使用空检查运算符

单于俊智
2023-03-14

每当我尝试注册并点击注册按钮时,我都会遇到这种类型的空值检查运算符的问题。我收到了这个错误消息

══════ 异常捕获手势 ════════════════════

在处理手势时引发了以下_CastError:对空值使用空检查运算符

当抛出异常时,这是堆栈

#0\u授权状态。建筑包装:gr_空间/屏幕/配置文件_屏幕。省道:244

#1(香港)地产_handleTap包装:颤振/材料/墨水井。省道:989

#2 GestureRecognizer.invoke回调包:flutter/.../手势/recognizer.dart:182

#3 t手势识别器。手摇

软件包:颤振/../signatures/tap。省道:607

#4 BaseTapgestureRecognitor_检查包:颤振/手势/轻触。省道:296

... 处理程序:“onTap”识别器:TapGestureRecognizer#f8d29调试所有者:GestureDetector状态:就绪赢得竞技场最终位置:偏移(215.0716.5)最终位置:偏移(199.0,16.0)按钮:1发送点击═════════════════════════════════════════════════════════

这是我的授权屏幕。省道锉

import 'package:flutter/material.dart';

enum AuthMode { Signup, Login }

class ProfileScreen extends StatelessWidget {
  static const routeName = '/profile';
  @override
  Widget build(BuildContext context) {
    return AnimatedContainer(
      duration: Duration(milliseconds: 300),
      child: Authorization(),
    );
  }
}

class Authorization extends StatefulWidget {
  @override
  _AuthorizationState createState() => _AuthorizationState();
}

class _AuthorizationState extends State<Authorization> {
  final GlobalKey<FormState> _formKey = GlobalKey();
  AuthMode _authMode = AuthMode.Login;
  final _passwordController = TextEditingController();
  Map<String, String> _authData = {
    'firstName': '',
    'lastName': '',
    'username': '',
    'email': '',
    'phoneNumber': '',
    'dateOfBirth': '',
    'password': '',
    'confirmPassword': '',
    'city': '',
    'gender': '',
  };
  void _switchAuthMode() {
    if (_authMode == AuthMode.Login) {
      setState(() {
        _authMode = AuthMode.Signup;
      });
    } else {
      setState(() {
        _authMode = AuthMode.Login;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    final deviceSize = MediaQuery.of(context).size;

    return Container(
      height: _authMode == AuthMode.Signup ? 320 : 260,
      constraints:
          BoxConstraints(minHeight: _authMode == AuthMode.Signup ? 620 : 660),
      width: deviceSize.width,
      padding: EdgeInsets.all(16.0),
      child: Form(
        child: SingleChildScrollView(
          child: Column(
            children: [
              TextFormField(
                decoration: InputDecoration(labelText: 'First name'),
                keyboardType: TextInputType.name,
                // ignore: missing_return
                validator: (value) {
                  if (value!.isEmpty) {
                    return 'Required';
                  }
                },
                onSaved: (value) {
                  _authData['firstName'] = value!;
                },
              ),
              TextFormField(
                decoration: InputDecoration(labelText: 'Last name'),
                keyboardType: TextInputType.emailAddress,
                // ignore: missing_return
                validator: (value) {
                  if (value!.isEmpty) {
                    return 'Required';
                  }
                },
                onSaved: (value) {
                  _authData['lastName'] = value!;
                },
              ),
              TextFormField(
                decoration: InputDecoration(labelText: 'Username'),
                keyboardType: TextInputType.name,
                // ignore: missing_return
                validator: (value) {
                  if (value!.isEmpty) {
                    return 'Required';
                  }
                },
                onSaved: (value) {
                  _authData['username'] = value!;
                },
              ),
              TextFormField(
                decoration: InputDecoration(labelText: 'E-Mail'),
                keyboardType: TextInputType.emailAddress,
                // ignore: missing_return
                validator: (value) {
                  if (value!.isEmpty || !value.contains('@')) {
                    return 'Invalid email!';
                  }
                },
                onSaved: (value) {
                  _authData['email'] = value!;
                },
              ),
              TextFormField(
                decoration: InputDecoration(labelText: 'Password'),
                obscureText: true,
                controller: _passwordController,
                // ignore: missing_return
                validator: (value) {
                  if (value!.isEmpty || value.length < 5) {
                    return 'Password is too short!';
                  }
                },
                onSaved: (value) {
                  _authData['password'] = value!;
                },
              ),
              (_authMode == AuthMode.Login)
                  ? Container(
                      child: Column(children: [
                        TextFormField(
                          enabled: _authMode == AuthMode.Signup,
                          decoration:
                              InputDecoration(labelText: 'Confirm Password'),
                          obscureText: true,
                          validator: _authMode == AuthMode.Signup
                              // ignore: missing_return
                              ? (value) {
                                  if (value != _passwordController.text) {
                                    return 'Passwords do not match!';
                                  }
                                }
                              : null,
                          onSaved: (value) {
                            _authData['confirmPassword'] = value!;
                          },
                        ),
                        TextFormField(
                          decoration:
                              InputDecoration(labelText: 'Phone Number'),
                          keyboardType: TextInputType.phone,
                          // ignore: missing_return
                          validator: (value) {
                            if (value!.isEmpty || value.length < 7) {
                              return 'Invalid phone number!';
                            }
                          },
                          onSaved: (value) {
                            _authData['phone number'] = value!;
                          },
                        ),
                        TextFormField(
                          decoration: InputDecoration(labelText: 'City'),
                          keyboardType: TextInputType.emailAddress,
                          // ignore: missing_return
                          validator: (value) {
                            if (value!.isEmpty) {
                              return 'Required';
                            }
                          },
                          onSaved: (value) {
                            _authData['city'] = value!;
                          },
                        ),
                        TextFormField(
                          decoration: InputDecoration(labelText: 'Gender'),
                          keyboardType: TextInputType.emailAddress,
                          // ignore: missing_return
                          validator: (value) {
                            if (value!.isEmpty) {
                              return 'Required';
                            }
                          },
                          onSaved: (value) {
                            _authData['gender'] = value!;
                          },
                        ),
                      ]),
                    )
                  : SizedBox(
                      height: 10,
                    ),
              SizedBox(
                height: 20,
              ),
              MaterialButton(
                height: 40,
                color: Theme.of(context).primaryColor,
                minWidth: double.infinity,
                onPressed: () {
                  if(_formKey.currentState!.validate()){
                    print('yess');
                  }
                },
                elevation: 0,
                //shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
                child: Text(
                  'Register',
                  style: TextStyle(
                    color: Colors.white,
                  ),
                ),
              ),
              Divider(
                color: Colors.black,
              ),
              MaterialButton(
                height: 40,
                color: Color.fromARGB(255, 222, 82, 69),
                minWidth: double.infinity,
                onPressed: () {},
                elevation: 0,
                //shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Image.asset(
                      'assets/gmail_logo.png',
                      height: 25,
                      width: 25,
                    ),
                    SizedBox(
                      width: 15,
                    ),
                    Text(
                      'Register with gmail',
                      style: TextStyle(
                        color: Colors.white,
                      ),
                    ),
                  ],
                ),
              ),
              MaterialButton(
                height: 40,
                color: Color.fromARGB(255, 65, 103, 178),
                minWidth: double.infinity,
                onPressed: () {},
                elevation: 0,
                //shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Image.asset(
                      'assets/facebook_logo.png',
                      height: 25,
                      width: 25,
                    ),
                    SizedBox(
                      width: 15,
                    ),
                    Text(
                      'Register with Facebook',
                      style: TextStyle(
                        color: Colors.white,
                      ),
                    ),
                  ],
                ),
              ),
              SizedBox(
                height: 20,
              ),
              Text(
                'Already have an account?',
              ),
              SizedBox(
                height: 10,
              ),
              TextButton(
                onPressed: _switchAuthMode,
                child: Text(
                  'Sign In',
                  style: TextStyle(
                    color: Colors.blue,
                    decoration: TextDecoration.underline,
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

共有1个答案

苏富
2023-03-14

这是因为\u formKey。currentState从未分配-为了分配它,您需要将密钥传递给表单小部件,如下所示:

Form(
  key: _formKey,
  child: ...
)

然后,Form小部件将负责分配当前状态

如果_formKState为空,检查表单状态不一定会导致应用崩溃也是一个好主意ey.current。例如,在您的注册按钮中:

onPressed: () {
  if (_formKey.currentState == null) {
    print("_formKey.currentState is null!");
  } else if (_formKey.currentState!.validate()) {
    print("Form input is valid");
  }
}
 类似资料:
  • E/flatter(26872):[错误:flatter/lib/ui/ui\u dart\u state.cc(199)]未处理的异常:在空值E/flatter(26872)上使用的空检查运算符:#0 MethodChannelFirebaseMessaging。registerBackgroundMessageHandler(包:firebase\u messaging\u platform\

  • 注意:同样的代码,当使用在另一个帐户的firebase工作,我似乎不能解决问题。

  • 问题内容: 在Java代码中执行空检查时,如果您为空值抛出IllegalArgumentExceptions,那么您将使用哪种消息模板? 我们倾向于使用这样的东西 哪个更好:“ is null”或“ was null”,为什么? 对我来说,“是空的”感觉更自然。 问题答案: 由于由于失败的前提条件检查而引发,因此,我认为除了陈述事实以外,还应说明已违反的 要求 。 就是说,而不是说。 关于使用库进

  • Xcode的输出:在文件中包含从 /Users/dani/development/flutter/.pub-cache/hosted/pub.dartlang.org/url_launcher-6.0.3/ios/Classes/FLTURLLauncherPlugin.m: 7: /Users/dani/development/flutter/.pub-cache/hosted/pub.dart

  • 我正在Linux Ubuntu上配置Flatter SDK 我在文件中为和指定了,但我在运行时收到此错误:

  • 我得到这个错误: InvalidRequest:服务器错误:code=2200[无效查询]消息="Java源代码编译失败: 第1行:运算符!=对于参数类型long, null 第1行:运算符!=对于参数类型long, null未定义" 而在手册中,这些比较似乎是可以的(例如这里)。我使用的是Cassandra 4.0.3(通过docker图像)。