'Null check operator used on a null value in TexformField

Here is my code for TextFormField and i am getting the error That "Null check operator used on a Null value" and if i remove the null check operator from the currentstate then it throws another exception.

import 'package:firebase/sign_up.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:google_sign_in/google_sign_in.dart';

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

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

    class _First_PageState extends State<First_Page> {
      final key= GlobalKey<FormState>();
      final _auth=FirebaseAuth.instance;
      final  User_email_id=TextEditingController();
      final user_Passowrd=TextEditingController();
       @override
      Widget build(BuildContext context) {
      final email_id=TextFormField(
      controller: User_email_id,
      key: key,
     validator: (value){
     if(value!.isEmpty){
      return "Please enter a value";
     }
   },
   decoration:InputDecoration(
     contentPadding:EdgeInsets.fromLTRB(20, 15, 20, 15),
     prefixIcon: Icon(
       Icons.mail,
     ),
     hintText: "Email-id",
     border: OutlineInputBorder(
       borderRadius: BorderRadius.circular(10)
     ),
   ),
 );

Here is my Button code and Onpressed..

          Container(
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(10),
          gradient: LinearGradient(
            colors: <Color>[
              Colors.yellow,
              Colors.greenAccent,
            ]
          )
        ),
        child: ButtonTheme(
          padding:EdgeInsets.fromLTRB(20, 15, 20, 15) ,
          minWidth: 350,
          child: FlatButton(
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(10)
            ),
            onPressed: (){
               if(key.currentState!.validate()){
                 print('Successful');
               }
            },
            child: Text(
                'Sign-in',
              style: TextStyle(
                fontSize: 15,
                fontWeight: FontWeight.bold,
              ),
            ),
        ),
        ),
      ),

And Here are the errors that i am getting

======== Exception caught by gesture 
  ===============================================================
    The following _CastError was thrown while handling a gesture:
    Null check operator used on a null value

    When the exception was thrown, this was the stack: 
    #0      _First_PageState.build.<anonymous closure> (package:firebase/Sign_In.dart:119:39)
    #1      _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:989:21)
    #2      GestureRecognizer.invokeCallback 
            (package:flutter/src/gestures/recognizer.dart:193:24)
    #3      TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:608:11)
    #4      BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:296:5)
    #5      BaseTapGestureRecognizer.acceptGesture 
    (package:flutter/src/gestures/tap.dart:267:7)
    #6      GestureArenaManager.sweep (package:flutter/src/gestures/arena.dart:157:27)
    #7      GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:444:20)
    #8      GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:420:22)
    #9      RendererBinding.dispatchEvent (package:flutter/src/rendering/binding.dart:278:11)
    #10     GestureBinding._handlePointerEventImmediately 
        (package:flutter/src/gestures/binding.dart:374:7)
    #11     GestureBinding.handlePointerEvent 
        (package:flutter/src/gestures/binding.dart:338:5)
    #12     GestureBinding._flushPointerEventQueue 
      (package:flutter/src/gestures/binding.dart:296:7)
    #13     GestureBinding._handlePointerDataPacket 
       (package:flutter/src/gestures/binding.dart:279:7)
    #17     _invoke1 (dart:ui/hooks.dart:185:10)
    #18     PlatformDispatcher._dispatchPointerDataPacket 
       (dart:ui/platform_dispatcher.dart:293:7)
    #19     _dispatchPointerDataPacket (dart:ui/hooks.dart:98:31)
        (elided 3 frames from dart:async)
    Handler: "onTap"
    Recognizer: TapGestureRecognizer#b49fb
     debugOwner: GestureDetector
     state: ready
     won arena
     finalPosition: Offset(172.0, 531.6)
     finalLocalPosition: Offset(150.6, 23.6)
     button: 1
     sent tap down

If i remove the null operator from Currentstate then it shows the error 'The method 'validate' can't be unconditionally invoked because the receiver can be 'null'.'



Solution 1:[1]

The bang operator ! you use only if you are sure that the value is not null. Otherwise use question mark ?

// Good
if(value?.isEmpty ?? false){ // Here says If the value is null or is empty equal to the true. Operator `??` tells what you want to return if the value is null.
  return "Please enter a value";
}

// Bad
if(value!.isEmpty){ // Here says If the value not null and is empty equal to the true
  return "Please enter a value";
}
//...

In your code key.currentState or value is null, but you say to Dart that is no null here.

Solution 2:[2]

Update your dart SDK to current version , and now the current version is 2.16.1

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Ali Abdullah