gpt4 book ai didi

Flutter 错误,Null 检查运算符用于空值

转载 作者:行者123 更新时间:2023-12-02 16:09:28 24 4
gpt4 key购买 nike

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

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

处理手势时抛出以下 _CastError:用于空值的空检查运算符

当抛出异常时,这是堆栈

#0 _AuthorizationState.build。包:gr_space/screens/profile_screen.dart:244

#1 _InkResponseState._handleTap包: flutter/…/material/ink_well.dart:989

#2 GestureRecognizer.invokeCallbackpackage:flutter/…/gestures/recognizer.dart:182

#3 TapGestureRecognizer.handleTapUp

package:flutter/…/gestures/tap.dart:607

#4 BaseTapGestureRecognizer._checkUppackage:flutter/…/gestures/tap.dart:296

...处理程序:“onTap”识别器:TapGestureRecognizer#f8d29debugOwner:手势检测器状态:准备就绪赢得竞技场finalPosition: 偏移量(215.0, 716.5)finalLocalPosition: 偏移量(199.0, 16.0)按钮:1发送点击══════════════════════════════════════════════════ ═══════

这是我的授权屏幕。 Dart 文件

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

最佳答案

这是因为 _formKey.currentState 从未被分配 - 为了分配它,您需要将 key 传递给您的 Form 小部件,如下所示:

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

然后 Form 小部件将负责分配 currentState

如果 _formKey.currentState 为 null,以一种不一定会使您的应用程序崩溃的方式检查表单状态也是一个好主意。例如,在您的注册按钮中:

onPressed: () {
if (_formKey.currentState == null) {
print("_formKey.currentState is null!");
} else if (_formKey.currentState!.validate()) {
print("Form input is valid");
}
}

关于Flutter 错误,Null 检查运算符用于空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68410753/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com