[英]DropdownButton not updating the value in flutter
当我尝试从物品中挑选任何价值时。 文字没有改变,它总是向我显示“Tone 1”。
@override
Widget build(BuildContext context)
{
// Set landscape orientation
int _value=1;
SystemChrome.setPreferredOrientations([
DeviceOrientation.landscapeLeft,
DeviceOrientation.landscapeRight,
]);
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Tones'),
backgroundColor: Colors.black,
actions: <Widget>[
DropdownButton<int>(
value: _value,
dropdownColor:Colors.black26,
items: [
DropdownMenuItem(
child: Text("Tone 1",
style: TextStyle(
color: Colors.white ,
fontSize: 20,
letterSpacing: 0.5,
),
),
value: 1,
),
DropdownMenuItem(
child: Text("Tone 2"
,
style: TextStyle(
color: Colors.white ,
fontSize: 20,
letterSpacing: 0.5,
),),
value: 2,
),
DropdownMenuItem(
child: Text("Tone 3",
style: TextStyle(
color: Colors.white ,
fontSize: 20,
letterSpacing: 0.5,
),),
value: 3
),
DropdownMenuItem(
child: Text("Tone 4",
style: TextStyle(
color: Colors.white ,
fontSize: 20,
letterSpacing: 0.5,
),),
value: 4
)
,
DropdownMenuItem(
child: Text("Tone 5",
style: TextStyle(
color: Colors.white ,
fontSize: 20,
letterSpacing: 0.5,
),),
value: 5
)
],
onChanged: (value) {
setState(() {
_value = value!;
});
}),
IconButton(
icon: Icon(
Icons.send,
color: Colors.white,
),
onPressed: () async {
// do something
List<int> pressedToneList = [];
final FirebaseFirestore _firebase = FirebaseFirestore.instance;
switch (_value) {
case 1:
pressedToneList=song1;
break;
case 2:
pressedToneList=song2;
break;
case 3:
pressedToneList=song3;
break;
case 4:
pressedToneList=song4;
break;
case 5:
pressedToneList=song5;
break;
case 6:
pressedToneList=song6;
break;
case 7:
pressedToneList=song7;
break;
case 8:
pressedToneList=song8;
break;
case 9:
pressedToneList=song9;
break;
case 10:
pressedToneList=song10;
}
await _firebase.collection('Tones').doc('tone').set({"Keys": pressedToneList});
pressedToneList.clear();
},
),
IconButton(
icon: Icon(
Icons.home,
color: Colors.white,
),
onPressed: () async {
// do something
Navigator.pop(context);
},
),
],
),
body: SafeArea(
child: Row(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
myTone(1),
myToneOpposite(3),
myTone(5),
myToneOpposite(7),
myTone(9),
],
),
),
),
);
}
}
您似乎已经定义了int _value=1;
在您的构建 function 内部。
因此,它本身始终为1
,因为每次构建小部件时,该值都设置为 1。
您必须在State
class 中将其定义为成员变量。
像这样,
class ExampleWidgetState extends State<ExampleWidget> {
int _value = 1;
@override
Widget build(BuildContext context) => Scaffold(
然后,你可以用同样的方式使用它,像这样
DropdownButton<int>(
value: _value,
最后,您可以 setState 像这样更改它的值
onChanged: (value) {
setState(() {
_value = value!;
});
}),
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.