Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I want to use Provider in InitState() but got an exception: Null check operator used on a null value

Hi I’m new to flutter.

I am using Provider and want to use the data I get from it as the initial value of textfield. So I decided to define the controller as a nullable value and put the text to it in initState().

Here is the code.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

...
TextEditingController? _lastNameController;
TextEditingController? _firstNameController;

@override
void initState() {
  super.initState();
   WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
    MyProvider myProvider = Provider.of(context, listen : false);
    _lastNameController  = TextEditingController(text : myProvider.lastName);
    _firstNameController = TextEditingController(text : myProvider.firstName);
  });
}

@override
Widget build(BuildContext context) {
  return Row(
    children : [
      // this is an extension of TextField
      MyTextField(controller : _lastNameController!,  hintText : 'Last Name'),
      const Spacer(),
      MyTextField(controller : _firstNameController!, hintText : 'First Name')
...

And I got an exception Null check operator used on a null value.

Please let me know if you have any solution.

Thanks,

>Solution :

WidgetsBinding.instance.addPostFrameCallback will calls after the 1st frame is build. So initially MyTextField is getting null from both _lastNameController and _firstNameController.

You can do

 MyTextField(controller : _lastNameController??TextEditingController(),  

or

if(_lastNameController!=null) MyTextField(controller : _lastNameController,  
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading