我正在使用 Flutter 制作 Instagram,并在提要項下添加評論功能。但是,當我按下評論提交按鈕時,會出現錯誤“Null check operator used on a null value”。
我正在使用 formKey 來檢查提交是否有效。如何正確使用它以及如何解決此問題?謝謝!
class CommentInput extends StatefulWidget {
const CommentInput({Key? key, required this.snapshot, required this.postId})
: super(key: key);
final snapshot;
final postId;
@override
State<CommentInput> createState() => _CommentInputState();
}
class _CommentInputState extends State<CommentInput> {
final _commentController = TextEditingController();
final _formKey = GlobalKey<FormState>();
@override
void dispose() {
super.dispose();
_commentController.dispose();
}
@override
Widget build(BuildContext context) {
return Form(
child: Container(
height: 55.0,
margin: const EdgeInsets.symmetric(horizontal: 8.0),
child: Row(
children: [
Flexible(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 12.0),
child: TextFormField(
validator: (input) {
if (input == null) {
return "Please enter comment";
}
},
controller: _commentController,
decoration: const InputDecoration(
hintText: "Add a comment...",
),
),
),
),
GestureDetector(
child: Container(
margin: const EdgeInsets.only(right: 8.0),
child: const Text('Post', style: TextStyle(color: Colors.blue)),
),
onTap: () {
final isValid = _formKey.currentState!.validate(); //Error Null check operator used on a null value
if (isValid) {
_formKey.currentState!.save();
context.read<HomeData>().uploadComment(
widget.snapshot.uid,
widget.postId,
_commentController.text,
widget.snapshot.username,
widget.snapshot.photoUrl);
}
},
)
],
),
),
);
}
}
uj5u.com熱心網友回復:
嘿,你還沒有提供你的 from 鍵到 Form 小部件——
我已經更新了你的代碼檢查它 -
@override
Widget build(BuildContext context) {
return Form(
key:_formKey,
child: Container(
height: 55.0,
margin: const EdgeInsets.symmetric(horizontal: 8.0),
child: Row(
children: [
Flexible(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 12.0),
child: TextFormField(
validator: (input) {
if (input == null) {
return "Please enter comment";
}
},
controller: _commentController,
decoration: const InputDecoration(
hintText: "Add a comment...",
),
),
),
),
GestureDetector(
child: Container(
margin: const EdgeInsets.only(right: 8.0),
child: const Text('Post', style: TextStyle(color: Colors.blue)),
),
onTap: () {
final isValid = _formKey.currentState!.validate(); //Error Null check operator used on a null value
if (isValid) {
_formKey.currentState!.save();
context.read<HomeData>().uploadComment(
widget.snapshot.uid,
widget.postId,
_commentController.text,
widget.snapshot.username,
widget.snapshot.photoUrl);
}
},
)
],
),
),
);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/494763.html
上一篇:如何在@@之后驗證電子郵件?
下一篇:如何將缺口曲線應用于小部件?
