使用 Textformfield 在 flutter 中对空值使用空检查运算符

Null check operator used on a null value in flutter using Textformfield

我是 flutter 的新手,在这个简单的代码中我遇到了错误

NUll check operator used on a null value

我尝试了此处提供的所有解决方案(我 运行 我终端中的所有命令,如 flutter upgrade 等等)但我仍然遇到相同的错误。

 import 'package:flutter/material.dart';

   Future<void> main() async{
    WidgetsFlutterBinding.ensureInitialized();

   runApp(MaterialApp(
   home: Home(),
   ));
  }

  class Home extends StatefulWidget {
  const Home({Key? key}) : super(key: key);

  @override
 _HomeState createState() => _HomeState();
  }

  class _HomeState extends State<Home> {

 final  _key =GlobalKey<FormState>();
  final textformfield=TextEditingController();

 @override
  Widget build(BuildContext context) {
  return Scaffold(
   body: Center(
     child: Container(
      child: Column(
        children: [
          SizedBox(height: 300,),
          TextFormField(
            controller: textformfield,
            key: _key,
            validator: (value){
              if(value!.isEmpty){
                return "Please enter your email";
              }
              else return null;
            },
          ),
          FlatButton(
              onPressed: (){
                 if(_key.currentState!.validate()){
                            print("validate");
                 }
                 else print('NUll');
              },
              child: Text('Validate')
                ),
              ],
            ),
         ),
        ),
      );
     }
    }

首先,您需要有一个Form Widget 并将TextFormFields 放入其中。 https://docs.flutter.dev/cookbook/forms/validation

return Form(
  key: _key,
  child: Column(
    children: <Widget>[
      // Add TextFormFields and ElevatedButton here.
    ],
  ),
);

试试下面的代码希望对你有帮助。在 Form() 中添加您的小部件并使用 TextButton 而不是 FlatButton,因为 FlatButton 已被 flutter 弃用

参考表单验证here

  Form(
        key: _key,
        child: Column(
          children: [
            SizedBox(
              height: 300,
            ),
            TextFormField(
              controller: textformfield,
              validator: (value) {
                if (value!.isEmpty) {
                  return "Please enter your email";
                } else
                  return null;
              },
            ),
            TextButton(
                onPressed: () {
                  if (_key.currentState!.validate()) {
                    print("validate");
                  } else
                    print('NUll');
                },
                child: Text('Validate')),
          ],
        ),
      ),