I am having trouble understanding state management in flutter I have the folloing build method:
Widget build(BuildContext context) {
print("calling build with selectedItem: $selectedItem");
// TODO: implement build
return SafeArea(
child: SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
mainAxisSize: MainAxisSize.min,
children: [
Flexible(
fit: FlexFit.loose,
child: DropdownButton<String>(
value: selectedItem,
style: const TextStyle(color: Colors.black),
underline: Container(height: 2, color: Colors.deepPurpleAccent),
icon: Icon(Icons.arrow_downward),
iconSize: 20,
elevation: 16,
items: widget.streetNamesList
.map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value, child: Text(value));
}).toList(),
onChanged: (String? value) {
setState(() {
selectedItem = value;
});
},
),
),
SizedBox(height: 10.0,),
CarListPerStreetWidgetV2(streetName: selectedItem,)
],
),
)),
);
}
The CarListPerStreetWidget implements a future provider that uses the streetname to fetch data from the database.
The problem is that when I choose a new value from the drop down menu although the build method gets executed, the build method of CarListPerStreetWidgetV2
also gets executed, but the widget does not get re-initialized with the new selectedItem
I am guessing Widgets get initialized once, but how do I pass a state changed from a widget to another?
2
Answers
Can you share the CarListPerStreetWidgetV2 widget? If this widget is a
StatefulWidget
, you must update that widget in thedidUpdateWidget
.For example:
The code seems to be correct, but there are a few things you haven’t shared so check if these things are correct.
initState
.Also check these things which you might have missed.
CarListPerStreetWidgetV2
is using the passed in value not something local to it.If it still doesn’t work, you should share the other parts of the code.