0

I am developing a feature where users can press a button to add a new group of text fields to the screen. Each group of text fields is stored in its own stateful widget. The abridged code to add the new widget is shown below:

List<EducationField> fieldList = [];
List<GlobalKey<EducationFieldState>> keyList = [];

// Function that adds new widgets to the list view
onTap: () {
    GlobalKey<EducationFieldState> key = new GlobalKey<EducationFieldState>();

    setState(() {
        fieldList.add(EducationField(key: key));
        keyList.add(key);
    });
},

I can dynamically add the new widgets just fine. However when I try to access the state of the widgets, I get an error saying that the state of the respective widget is null. There is a function in each widget state that gets the values from their text fields. The code I'm using to do that is also shown below:

void _getUserData(){
    List<EducationModel> modelList = [];

    for(int i = 0; i < fieldList.length; i++){
      modelList.add(keyList[i].currentState!.getData()); // this line is causing the error
      modelList.last.printModel();
    }
}

I have done a lot of research on this issue and still have no idea why I am getting a null error. Is my approach wrong or is it something more minor? I can also give more code if necessary.

Thanks in advance!

1 Answers1

0

Checkout GlobalKey docs.

Your dynamically added Text widget doesn't exist in the Widget tree yet, as you just created it and you're trying to add it to the Widget tree. So it doesn't have a current state.

Maybe this helps?

keyList[i].currentState?.getData() ?? '' // I'm guessing getData return a String

Something else you could try:

// only call _getUserData() after widget finished building
WidgetsBinding.instance!.addPostFramecallback(() => _getUserData());
Eric Omine
  • 489
  • 4
  • 15