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.

...
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,  

Leave a Reply