[英]JSON data coming from API not showing in the dropdownlist
我正在使用 JSON API 將數據放入 Flutter 的下拉列表中。 但是,每當我單擊下拉列表時,數據都不會出現在列表中。
以下是我的代碼:
class ItemSelection extends StatefulWidget{
@override
_ItemSelectionState createState() => _ItemSelectionState();
}
class _ItemSelectionState extends State<ItemSelection> {
@override
Widget build(BuildContext context) {
// TODO: implement build
return Scaffold(
body: Container(
height: MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width,
padding: EdgeInsets.all(20.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text("Dropdown",
style: TextStyle(
fontSize: 20.0,
),
textAlign: TextAlign.center,
),
SizedBox(
height: 20.0,
),
DropDownField(
controller: cityselected,
hintText: "Select an item",
enabled: true,
itemsVisibleInDropdown: 5,
items: items,
onValueChanged: (value){
setState(() {
selectedcity = value;
});
}
)
],
),
),
);
}
}
final List<String> items = [];
Future getitem() async {
var response = await http.get(
"basic json url here",
headers: {
"Accept": "application/json"
}
);
if(response.statusCode == 200){
List<GetItem> getitem = getItemFromJson(response.body);
for(int i =0; i< getitem.length; i++){
items.add(getitem[i].itemName);
}
print(items);
}
}
GetItem.dart:
import 'dart:convert';
List<GetItem> getItemFromJson(String str) => List<GetItem>.from(json.decode(str).map((x) => GetItem.fromJson(x)));
String getItemToJson(List<GetItem> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class GetItem {
GetItem({
this.sLNo,
this.itemName,
this.category,
});
String sLNo;
String itemName;
String category;
factory GetItem.fromJson(Map<String, dynamic> json) => GetItem(
sLNo: json["S/L NO"],
itemName: json["Item Name"] == null ? null : json["Item Name"],
category: json["Category"] == null ? null : json["Category"],
);
Map<String, dynamic> toJson() => {
"S/L NO": sLNo,
"Item Name": itemName == null ? null : itemName,
"Category": category == null ? null : category,
};
}
一旦我單擊下拉列表,我希望來自 JSON API 的數據顯示在其中。 有人可以幫我嗎?
您可以在下面復制粘貼運行完整代碼
您可以使用FutureBuilder
代碼片段
Future<List<String>> _future;
@override
void initState() {
_future = getitem();
...
FutureBuilder(
future: _future,
builder: (context, AsyncSnapshot<List<String>> snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
return Text('none');
case ConnectionState.waiting:
return Center(child: CircularProgressIndicator());
case ConnectionState.active:
return Text('');
case ConnectionState.done:
if (snapshot.hasError) {
return Text(
'${snapshot.error}',
style: TextStyle(color: Colors.red),
);
} else {
return DropDownField(
controller: cityselected,
hintText: "Select an item",
enabled: true,
itemsVisibleInDropdown: 5,
items: snapshot.data,
onValueChanged: (dynamic value) {
setState(() {
selectedcity = value;
});
});
工作演示
完整代碼
import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:dropdownfield/dropdownfield.dart';
import 'package:http/http.dart' as http;
List<GetItem> getItemFromJson(String str) =>
List<GetItem>.from(json.decode(str).map((x) => GetItem.fromJson(x)));
String getItemToJson(List<GetItem> data) =>
json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class GetItem {
GetItem({
this.sLNo,
this.itemName,
this.category,
});
String sLNo;
String itemName;
String category;
factory GetItem.fromJson(Map<String, dynamic> json) => GetItem(
sLNo: json["S/L NO"],
itemName: json["Item Name"] == null ? null : json["Item Name"],
category: json["Category"] == null ? null : json["Category"],
);
Map<String, dynamic> toJson() => {
"S/L NO": sLNo,
"Item Name": itemName == null ? null : itemName,
"Category": category == null ? null : category,
};
}
class ItemSelection extends StatefulWidget {
@override
_ItemSelectionState createState() => _ItemSelectionState();
}
class _ItemSelectionState extends State<ItemSelection> {
TextEditingController cityselected = TextEditingController();
String selectedcity;
Future<List<String>> _future;
@override
void initState() {
_future = getitem();
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
height: MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width,
padding: EdgeInsets.all(20.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text(
"Dropdown",
style: TextStyle(
fontSize: 20.0,
),
textAlign: TextAlign.center,
),
SizedBox(
height: 20.0,
),
FutureBuilder(
future: _future,
builder: (context, AsyncSnapshot<List<String>> snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
return Text('none');
case ConnectionState.waiting:
return Center(child: CircularProgressIndicator());
case ConnectionState.active:
return Text('');
case ConnectionState.done:
if (snapshot.hasError) {
return Text(
'${snapshot.error}',
style: TextStyle(color: Colors.red),
);
} else {
return DropDownField(
controller: cityselected,
hintText: "Select an item",
enabled: true,
itemsVisibleInDropdown: 5,
items: snapshot.data,
onValueChanged: (dynamic value) {
setState(() {
selectedcity = value;
});
});
}
}
})
],
),
),
);
}
}
final List<String> items = [];
Future<List<String>> getitem() async {
/*var response = await http
.get("basic json url here", headers: {"Accept": "application/json"});*/
String jsonString = '''
[{
"S/L NO":"1",
"Item Name":"item 1",
"Category": "c1"
},
{
"S/L NO":"2",
"Item Name":"item 2",
"Category": "c2"
},
{
"S/L NO":"3",
"Item Name":"item 3",
"Category": "c3"
},
{
"S/L NO":"4",
"Item Name":"item 4",
"Category": "c4"
},
{
"S/L NO":"5",
"Item Name":"item 5",
"Category": "c5"
}
]
''';
http.Response response = http.Response(jsonString, 200);
if (response.statusCode == 200) {
List<GetItem> getitem = getItemFromJson(response.body);
print(getitem.length);
for (int i = 0; i < getitem.length; i++) {
items.add(getitem[i].itemName);
}
}
return items;
}
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: ItemSelection(),
);
}
}
setState(() {
for(int i =0; i< getitem.length; i++){
items.add(getitem[i].itemName);
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.