Reputation: 73
I am using Flutter and are planning to make a dropdownbutton for user to select from. Upon selecting one of the option it will still shows the hint instead of the option that the user chose.
this is the code:
DropdownButton<String>(
isExpanded: true,
items: <String>['student', 'driver'].map((String value) {
return DropdownMenuItem<String>(
value: value,
child: new Text(value),
);
}).toList(),
hint: new Text ("Select a Role"),
onChanged: (value) => _role = value,
),
Thank you in advance for helping.
Upvotes: 0
Views: 427
Reputation: 597
you should like this
DropdownButton<String>(
isExpanded: true,
items: <String>['student', 'driver'].map((String value) {
return DropdownMenuItem<String>(
value: value,
child: new Text(value),
);
}).toList(),
value:_role,
hint: new Text ("Select a Role"),
onChanged: (value) => setState((){
_role = value
}),
),
Upvotes: 1
Reputation: 5736
You need to call setState
inside the onChanged
. You've to assign _role
to the value
property of DropdownButton
.
Here is the DartPad I've created.
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: MyWidget(),
),
),
);
}
}
class MyWidget extends StatefulWidget {
@override
_MyWidgetState createState() => _MyWidgetState();
}
class _MyWidgetState extends State<MyWidget> {
String? _role = 'student';
@override
Widget build(BuildContext context) {
return DropdownButton<String>(
isExpanded: true,
items: <String>['student', 'driver'].map((String value) {
return DropdownMenuItem<String>(
value: value,
child: new Text(value),
);
}).toList(),
value: _role,
hint: new Text("Select a Role"),
onChanged: (value) => setState(() => _role = value),
);
}
}
Upvotes: 1