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;

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

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.


>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(),  


if(_lastNameController!=null) MyTextField(controller : _lastNameController,  

Leave a Reply Cancel reply