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

Issue

I am new at flutter and in this simple code i am getting an error

NUll check operator used on a null value

i tried all the solutions that were present here (I run all the commands in my terminal like flutter upgrade and so on) but still i am getting the same error.

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

Solution

Try below code hope its help to you. add your widgets inside Form() and use TextButton instead of FlatButton because FlatButton is deprecated by flutter

refer form Validation 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')),
          ],
        ),
      ),

Answered By – Ravindra S. Patil

Answer Checked By – Candace Johnson (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *