I ran into a bit of a problem in flutter that I could not figure out myself.
So I have the following code (only the important parts of the code are pasted),
class _PrimaryDetailsEditState extends State<PrimaryDetailsEdit> {
String bankName; <---------- I have this variable inside my state class
void _getFormData() {
BackendApi.call(
endpoint: APIEndPoints.GET_FORM_DATA,
data: {'id': widget.jobId},
onSuccess: (data) {
setState(() {
bankName = data['clientBank']['name']; <-------------- I assign a new value to the above variable here
print('Bank name is $bankName'); <-------------- This print confirms that the new value has been indeed assigned to the variable
});
},
onFailed: (error) {
print('Failed to get data');
});
}
@override
void initState() {
_getFormData(); <------- I call the _getFormData function declared above right here.
super.initState();
}
In the above code,
I have a class variable called bankName
that is of data type string.
_getFormData
method defined below the bankName
, calls another static method called BackendApi.call()
which is responsible for making an http request to fetch some data. The BackendApi.call()
takes 4 named parameters and two of the important parameters are onSuccess
and onFailed
. These two parameters take callback functions to be called in cases where the data fetching is successful or not.
As you can see, on onSuccess
callback I assign some of the data that is received from the http request to the bankName
variable.
I also call the _getFormData
inside the @override initState()
to make sure that request is issued before the widget is mounted.
Problem
Even though bankName
holds the data I want, when that variable is passed down to a widget, my UI is not updated!
➡ I am passing the correct variable to the widget to update the UI. I confirmed this by commenting out the _getFormData
function and initially assigning a value to the bankName
a value like bankName = 'Hello'
. If I do this, the UI is updated with the value Hello
. So I am passing the correct variable to the widget.
Thank you!