我必须从 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,
}),
],
)
最佳答案
编辑原始问题在步骤 3 中描述
修改后的问题已在第 2 步中描述,需要更多信息,例如来自用户的 JSON 字符串格式
第 1 步:从 mysql/PHPMyAdminservice 获取 JSON 字符串
第 2 步:将此 JSON 字符串传输到 map 列表
步骤3:将其转换为DropdownButton的项目,即生成DropdownMenuItem
来自Flutter populate dropdownmenu with JSON的代码片段
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(),
),
),
);
}
关于mysql - 如何使用 flutter 以下拉形式从 phpmyadmin 检索数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57487524/