[英]I am trying to fetch data from the api and display it in a DropDownButton. problem is that snapshot is returning null
snapshot.hasData 返回 null 並且下拉按鈕永遠不會顯示。
我正在嘗試從 api 獲取數據並將其顯示在下拉按鈕中。 當我嘗試打印它時,response.body 被正確獲取,因為它被打印出來。 但是當我嘗試打印 listOfOperators 時,沒有打印任何內容。 看起來 listOfOperators 是空的,因此快照沒有任何數據。 我不明白為什么會這樣
JSON數據:
{"status": "success", "OperatorType": "GAS", "data": {"MAHANAGAR_GAS_LTD": {"name": "Mahanagar Gas Limited", "authenticator3": null, "label": "Customer Account Number (12 位以 21 開頭)", "note": null, "account_label": "Bill Group Number (1 - 8 characters + numbers)", "authenticator3_options": null}, "TRIPURA_NATURAL_GAS_COMPANY_LTD": {"name": "Tripura Natural Gas Company Ltd", "authenticator3": null, "label": "Consumer Number (1 - 20 numbers)", "note": null, "account_label": null, "authenticator3_options": null}, "HARAYANA_CITY_GAS ": {"name": "Haryana City gas", "authenticator3": null, "label": "CRN Number (8-12 numbers)", "note": null, "account_label": null, "authenticator3_options": null}, "GUJARAT_GAS_COMPANY_LTD": {"name": "Gujarat Gas company Limited", "authenticator3": null, "label": "Service Number (1-15 numbers)", "note": null, "account_label": null, "authenticator3_options": null}, "VADODARA_GAS_LTD": {"name": "Aavantika Gas Ltd", "authenticator3": null, "label": "Customer Number (10-15 Alphanumeric)", "note": null, "account_label": null, "authenticator3_options": null}, "SGL": {"name": "Sabarmati Gas Limited (SGL)", "authenticator3": null, "label": "客戶 ID (12 位)", "note": null, "account_label": null, "authenticator3_options": null}, "SITI_ENERGY": {"name": "Siti Energy", "authenticator3 ": null, "label": "ARN Number (7 - 9 digit)", "note": null, "account_label": null, "authenticator3_options": null}, "UCPGPL": {"name": "Unique Central Piped Gases Pvt Ltd (UCPGPL)", "authenticator3": null, "label": "Customer Number (8 bits + character)", "note": null, "account_label": null, "authenticator3_options": null}, " IGL": {"name": "IGL (Indraprasth Gas Limited)", "authenticator3": null, "label": "Consumer Number (10 digits)", "note": null, "account_label": null, "authenticator3_options ": null}, "ADANI_GAS": {"name": "ADANI GAS", "authenticator3": null, "label": "客戶 ID (10 位)", "note": null, "account_label": null, “authenticator3_options”: 空值}}}
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:flutter/material.dart';
class JsonApiDropdown extends StatefulWidget {
@override
JsonApiDropdownState createState() {
return new JsonApiDropdownState();
}
}
class JsonApiDropdownState extends State<JsonApiDropdown> {
Operators _currentOperator;
final String uri = "https://stage.linq.store/recharge-bill-payments?load=GetOperators&type=GAS";
Future<List<Operators>> _fetchdata() async {
var response = await http.get(uri,
headers: {
"Content-Type" : "application/json",
"MyToken" : "Token d5c9912f-4d4a-4776-88c4-545779804040",
"Request-Type" : "mobile_api",
}
);
if (response.statusCode == 200) {
final operators = jsonDecode(response.body).cast<Map<String, dynamic>>();
List<Operators> listOfOperators = operators.map<Operators>((json) {
return Operators.fromJson(json);
}).toList();
return listOfOperators;
} else {
throw Exception('Failed to load internet');
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Gas Bill Payment'),
backgroundColor: Colors.orangeAccent,
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
mainAxisSize: MainAxisSize.max,
children: <Widget>[
FutureBuilder<List<Operators>>(
future: _fetchdata(),
builder: (BuildContext context,
AsyncSnapshot<List<Operators>> snapshot) {
if (!snapshot.hasData) return CircularProgressIndicator();
return DropdownButton<Operators>(
items: snapshot.data
.map((operator) => DropdownMenuItem<Operators>(
child: Text(operator.name),
value: operator,
))
.toList(),
onChanged: (Operators value) {
setState(() {
_currentOperator = value;
});
},
isExpanded: false,
value: _currentOperator,
hint: Text('Select Operator'),
);
}),
SizedBox(height: 20.0),
_currentOperator != null
? Text("Name: " +
_currentOperator.name +
"\n Label: " +
_currentOperator.label +
"\n Account Label: " +
_currentOperator.accountLabel)
: Text("No Operator selected"),
],
),
),
);
}
}
class Operators {
String name;
String label;
String accountLabel;
Operators({
this.name,
this.label,
this.accountLabel
});
factory Operators.fromJson(Map<String, dynamic> json) {
return Operators(
name: json['name'],
label: json['label'],
accountLabel: json['account_label'],
);
}
}
根據您的 json 創建了我自己的示例,並在本地加載您的 json,否則一切都相同。 查看下面的代碼,我提供了 json、模型類和主 dart 文件。
您的 json 文件如下:
{
"status": "success",
"OperatorType": "GAS",
"data": {
"MAHANAGAR_GAS_LTD": {
"name": "Mahanagar Gas Limited",
"authenticator3": null,
"label": "Customer Account Number (12 digits start with 21)",
"note": null,
"account_label": "Bill Group Number (1 - 8 characters + digits)",
"authenticator3_options": null
},
"TRIPURA_NATURAL_GAS_COMPANY_LTD": {
"name": "Tripura Natural Gas Company Ltd",
"authenticator3": null,
"label": "Consumer Number (1 - 20 digits)",
"note": null,
"account_label": null,
"authenticator3_options": null
},
"HARAYANA_CITY_GAS": {
"name": "Haryana City gas",
"authenticator3": null,
"label": "CRN Number (8-12 digits)",
"note": null,
"account_label": null,
"authenticator3_options": null
},
"GUJARAT_GAS_COMPANY_LTD": {
"name": "Gujarat Gas company Limited",
"authenticator3": null,
"label": "Service Number (1-15 digits)",
"note": null,
"account_label": null,
"authenticator3_options": null
},
"VADODARA_GAS_LTD": {
"name": "Aavantika Gas Ltd",
"authenticator3": null,
"label": "Customer Number (10-15 Alphanumeric)",
"note": null,
"account_label": null,
"authenticator3_options": null
},
"SGL": {
"name": "Sabarmati Gas Limited (SGL)",
"authenticator3": null,
"label": "Customer ID (12 digits)",
"note": null,
"account_label": null,
"authenticator3_options": null
},
"SITI_ENERGY": {
"name": "Siti Energy",
"authenticator3": null,
"label": "ARN Number (7 - 9 digits)",
"note": null,
"account_label": null,
"authenticator3_options": null
},
"UCPGPL": {
"name": "Unique Central Piped Gases Pvt Ltd (UCPGPL)",
"authenticator3": null,
"label": "Customer Number (8 digits + character)",
"note": null,
"account_label": null,
"authenticator3_options": null
},
"IGL": {
"name": "IGL (Indraprasth Gas Limited)",
"authenticator3": null,
"label": "Consumer Number (10 digits)",
"note": null,
"account_label": null,
"authenticator3_options": null
},
"ADANI_GAS": {
"name": "ADANI GAS",
"authenticator3": null,
"label": "Customer ID (10 digits)",
"note": null,
"account_label": null,
"authenticator3_options": null
}
}
}
為您提供的 json 定義的模型類:
// To parse this JSON data, do
//
// final operators = operatorsFromJson(jsonString);
import 'dart:convert';
Operators operatorsFromJson(String str) => Operators.fromJson(json.decode(str));
String operatorsToJson(Operators data) => json.encode(data.toJson());
class Operators {
String status;
String operatorType;
Map<String, Datum> data;
Operators({
this.status,
this.operatorType,
this.data,
});
factory Operators.fromJson(Map<String, dynamic> json) => Operators(
status: json["status"],
operatorType: json["OperatorType"],
data: Map.from(json["data"])
.map((k, v) => MapEntry<String, Datum>(k, Datum.fromJson(v))),
);
Map<String, dynamic> toJson() => {
"status": status,
"OperatorType": operatorType,
"data": Map.from(data)
.map((k, v) => MapEntry<String, dynamic>(k, v.toJson())),
};
}
class Datum {
String name;
dynamic authenticator3;
String label;
dynamic note;
String accountLabel;
dynamic authenticator3Options;
Datum({
this.name,
this.authenticator3,
this.label,
this.note,
this.accountLabel,
this.authenticator3Options,
});
factory Datum.fromJson(Map<String, dynamic> json) => Datum(
name: json["name"],
authenticator3: json["authenticator3"],
label: json["label"],
note: json["note"],
accountLabel:
json["account_label"] == null ? null : json["account_label"],
authenticator3Options: json["authenticator3_options"],
);
Map<String, dynamic> toJson() => {
"name": name,
"authenticator3": authenticator3,
"label": label,
"note": note,
"account_label": accountLabel == null ? null : accountLabel,
"authenticator3_options": authenticator3Options,
};
}
這是我為包含您的數據的下拉列表編寫的主文件
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:sample_testing_project/models.dart';
main() => runApp(MyApp());
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
List<Datum> data = List();
bool _isLoading = false;
String selectedOperator;
@override
void initState() {
// TODO: implement initState
super.initState();
loadYourData();
}
Future<String> loadFromAssets() async {
return await rootBundle.loadString('json/parse.json');
}
loadYourData() async {
setState(() {
_isLoading = true;
});
// Loading your json locally you can make an api call, when you get the response just pass it to the operatorsFromJson method
String jsonString = await loadFromAssets();
final operators = operatorsFromJson(jsonString);
operators.data.forEach((k, v) {
data.add(v);
});
print(data.length);
setState(() {
_isLoading = false;
});
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: _isLoading
? Text('Loading')
: Container(
child: Padding(
padding: const EdgeInsets.all(30.0),
child: Container(
height: 50,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(5.0),
border: Border.all(
color: Colors.red,
style: BorderStyle.solid,
width: 0.80),
),
child: DropdownButton(
value: selectedOperator,
isExpanded: true,
icon: Padding(
padding: const EdgeInsets.only(left: 15.0),
child: Icon(Icons.arrow_drop_down),
),
iconSize: 25,
underline: SizedBox(),
onChanged: (newValue) {
setState(() {
selectedOperator = newValue;
});
},
hint: Padding(
padding: const EdgeInsets.all(8.0),
child: Text('Select'),
),
items: data.map((data) {
return DropdownMenuItem(
value: data.name,
child: Padding(
padding: const EdgeInsets.only(left: 10.0),
child: Text(
data.name,
style: TextStyle(
fontSize: 18,
color: Colors.black,
),
),
),
);
}).toList()),
),
),
),
),
);
}
}
我已經從 loadFromAssets 方法本地加載了您的 json,但您可以調用您的 api,然后將 response.body 傳遞給 operatorsFromJson 方法。
否則,每件事都是一樣的,我剛剛從鍵值映射中刪除了每個值(即對象),並將其添加到列表中,並將其顯示在下拉列表中。 讓我知道它是否有效。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.