Reputation: 65
i have an AlertDialog and want to use a DropdownButton for changing a value. At first there should be the hint visible. After choosing a value, the value should be visible. But when i use the hint, it never shows the value and vice versa.
DropdownButton(
items: <String>['team1','team2'].map((String val) => DropdownMenuItem<String>(
value: val,
child: Text(val),
)).toList(),
//value: 'team1',
hint: Text('Enter team'),
onChanged: (value) {
teteam.text = value;
}
),
It has the correct function, but visibility isnt quite like i expect.
Upvotes: 4
Views: 2620
Reputation: 2744
I'm posting a fully working code at the bottom
For future projects in order to 'activate the hint' ability you have to meet two conditions:
Set the initial value to null and the dropdown is enabled( list of strings and onChanged are non-null. Or so the official documentation says so.
Code below:
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,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
String? theTeam = null;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: DropdownButton(
value: theTeam,
items: <String>['team1', 'team2']
.map((String val) => DropdownMenuItem<String>(
value: val,
child: Text(val),
))
.toList(),
hint: Text('Enter team'),
onChanged: (String? value) {
setState(() {
theTeam = value!;
});
},
),
),
);
}
}
Upvotes: 2
Reputation: 2714
You have to use setState
since you want to change the UI of your app. Simply change the onchanged
onChanged: (value) {
setState(() {
teteam.text = value;
});
},
..
Working example right here: https://www.developerlibs.com/2019/09/flutter-drop-down-menu-list-example.html
setState from library: https://api.flutter.dev/flutter/widgets/State/setState.html
EDIT:
I assume you are trying to use setState
in a stateless widget, which is immutable(unable to change).
Use a stateful widget to do so, like this:
class AddTodoDialog extends StatefulWidget{
AddTodoDialog createState()=> AddTodoDialog();
}
class AddTodoDialog extends State<AddTodoDialog>{
//Your code here
}
Upvotes: 0