FormKey makes error 'Null check operator used on a null value'

483 Views Asked by At

This is a block of flutter code to generate qr code using textformfield and a elevatedbutton, validation keeps failing and gives error 'Null check operator used on a null value'. I'm using a formKey to check whether it's valid to submit or not. How can I use it properly and how can I fix this problem?

Help would be appreciated. Thank you.

class MyHomePage extends StatefulWidget{
  const MyHomePage({super.key});
  
  @override
  State<MyHomePage> createState(){
    return MyHomePageState();
  }
}
class MyHomePageState extends State<MyHomePage>{
  final _formKey = GlobalKey<FormState>();
  final TextEditingController qrController = TextEditingController();
  var inputUser = '';
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Generate QR code"),
      ),
      body: Column(
        children: <Widget>[
          Center(
            child: QrImage(
              data: inputUser,
              version: QrVersions.auto,
              size: 250,
              gapless: false,
              embeddedImage: const AssetImage('assets/images/pokeballimage.png'),
              embeddedImageStyle: QrEmbeddedImageStyle(
                size: Size(10, 10),
                color: Colors.black87
              ),
            ),
          ),
          TextFormField(
            key:_formKey,
            controller: qrController,
            keyboardType: TextInputType.text,
            validator: (value){
              if (value == null || value.isEmpty){
                return 'Enter something';
              }
              return null;
            },
            onSaved: (value){
              qrController.text = value!;
            },
            decoration: InputDecoration(
              hintText: 'Enter smth'
            ),
          ),

          ElevatedButton(
            child: const Text('Submit'),
            onPressed: () {
              if (_formKey.currentState!.validate()) {
                setState(() {
                  inputUser = qrController.text;
                });
              };
            },
          ),
        ],
      ),
    );
  }
}

3

There are 3 best solutions below

0
On

Null check operator used on a null value

This is the error. So to understand this:
Q. What is Null check operator ?
A. This is Null check operator ==> !

Q. Meaning of used on a null value ?
A. Variable before Null check operator ! is null and you are using the operator.

Q. When to use Null check operator ! ?
A. Very simple. When you have no doubt that the variable is never going to be null despite having the capacity to store null

Now code part nicely answered here.

0
On

You need to use Form widget to use the _formKey.

body: Form(
  key:_formKey,
   child: Column

And remove key from textFileds.

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key});

  @override
  State<MyHomePage> createState() {
    return MyHomePageState();
  }
}

class MyHomePageState extends State<MyHomePage> {
  final _formKey = GlobalKey<FormState>();
  final TextEditingController qrController = TextEditingController();
  var inputUser = '';
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Generate QR code"),
      ),
      body: Form(
        key: _formKey,
        child: Column(
          children: <Widget>[
            Center(
              child: QrImage(
                data: inputUser,
                version: QrVersions.auto,
                size: 250,
                gapless: false,
                embeddedImage:
                    const AssetImage('assets/images/pokeballimage.png'),
                embeddedImageStyle: QrEmbeddedImageStyle(
                    size: Size(10, 10), color: Colors.black87),
              ),
            ),
            TextFormField(
              controller: qrController,
              keyboardType: TextInputType.text,
              validator: (value) {
                if (value == null || value.isEmpty) {
                  return 'Enter something';
                }
                return null;
              },
              onSaved: (value) {
                qrController.text = value!;
              },
              decoration: InputDecoration(hintText: 'Enter smth'),
            ),
            ElevatedButton(
              child: const Text('Submit'),
              onPressed: () {
                if (_formKey.currentState?.validate() ?? false) {
                  setState(() {
                    inputUser = qrController.text;
                  });
                }
              },
            ),
          ],
        ),
      ),
    );
  }
}
0
On

you need to wrap TextFormField With Form in order to use form global key like this

class MyHomePage extends StatefulWidget{
  const MyHomePage({super.key});
  
  @override
  State<MyHomePage> createState(){
    return MyHomePageState();
  }
}
class MyHomePageState extends State<MyHomePage>{
  final _formKey = GlobalKey<FormState>();
  final TextEditingController qrController = TextEditingController();
  var inputUser = '';
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Generate QR code"),
      ),
      body: Column(
        children: <Widget>[
          Center(
            child: QrImage(
              data: inputUser,
              version: QrVersions.auto,
              size: 250,
              gapless: false,
              embeddedImage: const AssetImage('assets/images/pokeballimage.png'),
              embeddedImageStyle: QrEmbeddedImageStyle(
                size: Size(10, 10),
                color: Colors.black87
              ),
            ),
          ),
          Form(
            key: _formKey,
            child: TextFormField(
              controller: qrController,
              keyboardType: TextInputType.text,
              validator: (value){
                if (value == null || value.isEmpty){
                  return 'Enter something';
                }
                return null;
              },
              onSaved: (value){
                qrController.text = value!;
              },
              decoration: InputDecoration(
                hintText: 'Enter smth'
              ),
            ),
          ),

          ElevatedButton(
            child: const Text('Submit'),
            onPressed: () {
              if (_formKey.currentState!.validate()) {
                setState(() {
                  inputUser = qrController.text;
                });
              };
            },
          ),
        ],
      ),
    );
  }
}