我必须从PHPMyAdmin提取数据并将其显示为下拉菜单,但是在如何在下拉菜单中显示数据时遇到问题。我想创建注册表单并从数据库中获取下拉菜单列表。
这是我的编码
class RegisterForm extends StatefulWidget{
@override
RegisterFormState createState(){
return RegisterFormState();
}
}
class RegisterFormState extends State<RegisterForm>{
String _mySelection;
List data=[];
final _formKey = GlobalKey<FormState>();
@override
void initState(){
fetchData();
super.initState();
}
void fetchData() async{
final response = await http.get('http://10.0.2.2/Shazay/getData.php');
if (response.statusCode == 200) {
setState(() {
data = json.decode(response.body);
});
}
}
这是下拉菜单的代码:
new Row(
children: <Widget>[
new Text("Energy Bubble ",style: new TextStyle(fontSize: 18.0,color: Colors.blue),),
new DropdownButton(
items: data.map((item){
return new DropdownMenuItem(
child:new Text(item['EbName']),
value: item['EbName'].toString(),
);
}).toList(),
onChanged: (newVal){
setState(() {
_mySelection=newVal;
});
},
value: _mySelection,
}),
],
)
答案 0 :(得分:0)
编辑原始问题,请参见步骤3
修订后的问题先前已在步骤2中进行了描述,并且需要更多信息,例如来自用户的JSON字符串格式
第1步:从mysql / PHPMyAdminservice获取JSON字符串
第2步:将此JSON字符串传输到地图列表
步骤3:将其转换为DropdownButton项,即生成DropdownMenuItem
代码段
String _mySelection;
List<Map> _myJson = [{"id":0,"name":"<New>"},{"id":1,"name":"Test Practice"}];
@override
Widget build(BuildContext context) {
return new Scaffold(
body: new Center(
child: new DropdownButton<String>(
isDense: true,
hint: new Text("Select"),
value: _mySelection,
onChanged: (String newValue) {
setState(() {
_mySelection = newValue;
});
print (_mySelection);
},
items: _myJson.map((Map map) {
return new DropdownMenuItem<String>(
value: map["id"].toString(),
child: new Text(
map["name"],
),
);
}).toList(),
),
),
);
}