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;
});
};
},
),
],
),
);
}
}
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 storenull
Now code part nicely answered here.