Can someone please help me solve the problem with the change state in the dropdown menu?
The item does not change when I select the a menu. it remains on index[0].
class RegionalDailyTableStats extends StatefulWidget {
final String getString;
final String getBargraphString;
final String getAreagraphString;
final String getGraphString;
final String getLineGraphString;
final String getPDFString;
final String getPieChartString;
const RegionalDailyTableStats({
super.key,
required this.getString,
required this.getBargraphString,
required this.getAreagraphString,
required this.getGraphString,
required this.getLineGraphString,
required this.getPDFString,
required this.getPieChartString,
});
@override
State<RegionalDailyTableStats> createState() =>
_RegionalDailyTableStatsState();
}
class _RegionalDailyTableStatsState extends State<RegionalDailyTableStats> {
@override
Widget build(BuildContext context) {
final screenHeight = MediaQuery.of(context).size.height;
final screenWidth = MediaQuery.of(context).size.width;
List<String> graphs = [
widget.getGraphString,
widget.getBargraphString,
widget.getAreagraphString,
widget.getLineGraphString,
widget.getPieChartString,
];
String? selectedGraph = graphs[0];
return Container(
height: screenHeight,
width: screenWidth,
child: SizedBox(
width: screenWidth * 0.1,
child: Column(
children: [
DropdownButton<String>(
value: selectedGraph,
items: graphs.map((e) {
return DropdownMenuItem(
value: e,
child: Text(e),
);
}).toList(),
onChanged: (val) {
setState(() {
val = selectedGraph;
});
}),
],
)
);
}
}
I have edited the code. Please take a look at it. This is the full code for what I wanted to do. But it’s still not working
4
Answers
You are assigning incorrectly the value returned by dropdown to you variable.
You should modify you code:
On your setState method inside OnChange.
Invert val = selectedGraph, like below
The issue in your code lies within the onChanged callback of your dropdown button. You’re assigning the value of selectedGraph to value, instead of assigning value to selectedGraph.
You should not be initalising variables within the build method of your code. Build methods run everytime the screen is refreshed, so even if you fixed the assignment issue that other people have pointed out
The build method would be called again to run
selectedGraph = graphs[0]
.To properly initalise the state, use the StatefulWidget’s
initState()
method.