I want my Dropdownbutton to change according to the item selected by the user. These are my variable declarations:
class _HomeState extends State<Home> {
final gb_controller = TextEditingController();
final brutto_controller = TextEditingController();
final bAV_controller = TextEditingController();
int steuerklassen_value = 1;
String selectedValue = "Steuerklasse";
String hintValue = "Steuerklasse 1";
bool loading = false;
final formkey = GlobalKey<FormState>();
final steuerklassen = ['I', 'II', 'III', 'IV', 'V', 'VI'];
and this is my DropDownButton:
child: DropdownButton<String>(
hint: Text(hintValue),
iconSize: 20,
items: steuerklassen
.map((String dropDownStringItem) {
return DropdownMenuItem(
value: dropDownStringItem,
child: Text(dropDownStringItem),
);
}).toList(),
onChanged: (selectedValue) {
setState(() {
for (int i = 1;
i <= steuerklassen.length;
i++)
if (steuerklassen[i] ==
selectedValue) {
this.steuerklassen_value = i + 1;
}
hintValue =
"Steuerklasse $selectedValue";
return steuerklassen_value;
});
},
),
I want the hint value to change when a new item is selected. I thought I do this with hintValue = "Steuerklasse $selectedValue";
but obviously not.
This is my app:
And the text on the drop-down button should change but it doesn't.
You can copy paste run full code below
Your code has runtime error RangeError (index): Invalid value: Not in inclusive range
You can change from
for (int i = 1; i <= steuerklassen.length; i++)
to
for (int i = 0; i < steuerklassen.length; i++)
working demo
full code
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int steuerklassen_value = 1;
String selectedValue = "Steuerklasse";
String hintValue = "Steuerklasse 1";
final steuerklassen = ['I', 'II', 'III', 'IV', 'V', 'VI'];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
DropdownButton<String>(
hint: Text("$hintValue"),
iconSize: 20,
items: steuerklassen.map((String dropDownStringItem) {
return DropdownMenuItem(
value: dropDownStringItem,
child: Text(dropDownStringItem),
);
}).toList(),
onChanged: (selectedValue) {
setState(() {
for (int i = 0; i < steuerklassen.length; i++)
if (steuerklassen[i] == selectedValue) {
this.steuerklassen_value = i + 1;
}
hintValue = "Steuerklasse $selectedValue";
return steuerklassen_value;
});
},
),
],
),
),
);
}
}