DropdownButton未更新颤动中的值



当我尝试从项目中选择任何值时。文本不会改变,它总是向我显示";音调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;

因此,它将始终是1本身,因为每次构建小部件时,值都被设置为1。

您必须将它定义为State类中的成员变量。

像这样,

class ExampleWidgetState extends State<ExampleWidget> {

int _value = 1;
@override
Widget build(BuildContext context) => Scaffold(

然后,你可以用同样的方式使用它,比如这个

DropdownButton<int>(
value: _value,

最后,你可以设置State来改变它的值,就像这个

onChanged: (value) {
setState(() {
_value = value!;
});
}),

最新更新