[英]DropDownButton item not being selected
I am trying to put a DropdownButton
on one of my screens.我正在尝试在我的一个屏幕上放置一个
DropdownButton
。 I have followed several examples but I can not get it to show the selected item.我已经遵循了几个示例,但我无法让它显示所选项目。 It keeps showing the first item in the list.
它一直显示列表中的第一项。
String _trxnStatus = 'Listed';
DropdownButton<String>(
hint: Text('Please choose transaction status'),
value: _trxnStatus,
onChanged: (value) {
setState(() {
_trxnStatus = value;
});
},
items: <String>['Listed', 'Under Contract', 'Closed'].map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
),
I have traced the value through the debugger.我已经通过调试器跟踪了该值。
onChange
works fine and shows the selected value. onChange
工作正常并显示所选值。 However, when it comes to mapping the list and returning the DropdownMenuItem
the var value = 'Listed'
.但是,当涉及到映射列表并返回
DropdownMenuItem
时, var value = 'Listed'
。
How do I get this to work?我怎样才能让它工作? Thanks.
谢谢。
You are possibly initializing the _trxnStatus within the build function.您可能正在构建 function 中初始化 _trxnStatus。 You need to initialize _trxnStatus outside of the build function.
您需要在构建 function 之外初始化 _trxnStatus。 Please see the working code below:
请参阅下面的工作代码:
import 'package:flutter/material.dart';
final Color darkBlue = const Color.fromARGB(255, 18, 32, 47);
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData.dark().copyWith(scaffoldBackgroundColor: darkBlue),
debugShowCheckedModeBanner: false,
home: Scaffold(
body: Center(
child: MyWidget(),
),
),
);
}
}
class MyWidget extends StatefulWidget {
@override
_MyWidgetState createState() => _MyWidgetState();
}
class _MyWidgetState extends State<MyWidget> {
String _trxnStatus = 'Listed';
@override
Widget build(BuildContext context) {
return DropdownButton<String>(
hint: Text('Please choose transaction status'),
value: _trxnStatus,
onChanged: (value) {
setState(() {
_trxnStatus = value;
});
},
items: <String>['Listed', 'Under Contract', 'Closed']
.map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.