我從 api 得到這樣的回應:
[
{
"PollId": "5241851",
"Long": 74.25142,
"Lat": 31.47104,
"Speed": 0.0,
"IsGPSAvailable": true,
"Status": "IGNITION OFF",
"Ign": false,
"Distance": 0.023,
"Direction": 136.0,
},
{
"PollId": "5255637",
"Long": 74.25131,
"Lat": 31.47095,
"Speed": 0.0,
"IsGPSAvailable": true,
"Status": "IGNITION OFF",
"Ign": false,
"Distance": 0.028,
"Direction": 136.0,
},
]
如何從兩者中獲得 lat 和 lang。
uj5u.com熱心網友回復:
您可以使用此創建模型
// To parse this JSON data, do
//
// final location = locationFromJson(jsonString);
import 'dart:convert';
List<Location> locationFromJson(String str) => List<Location>.from(json.decode(str).map((x) => Location.fromJson(x)));
String locationToJson(List<Location> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class Location {
Location({
this.pollId,
this.long,
this.lat,
this.speed,
this.isGpsAvailable,
this.status,
this.ign,
this.distance,
this.direction,
});
String pollId;
double long;
double lat;
int speed;
bool isGpsAvailable;
String status;
bool ign;
double distance;
int direction;
factory Location.fromJson(Map<String, dynamic> json) => Location(
pollId: json["PollId"],
long: json["Long"].toDouble(),
lat: json["Lat"].toDouble(),
speed: json["Speed"],
isGpsAvailable: json["IsGPSAvailable"],
status: json["Status"],
ign: json["Ign"],
distance: json["Distance"].toDouble(),
direction: json["Direction"],
);
Map<String, dynamic> toJson() => {
"PollId": pollId,
"Long": long,
"Lat": lat,
"Speed": speed,
"IsGPSAvailable": isGpsAvailable,
"Status": status,
"Ign": ign,
"Distance": distance,
"Direction": direction,
};
}
然后使用 futurebuilder 和 listview 來獲取回應
FutureBuilder(
future: _future,
builder: (context, AsyncSnapshot<List<Location>> snapshot) {
return snapshot.data?.length == 0
? const Center(
child: Text("No Item"),
)
: ListView.builder(
shrinkWrap: true,
itemBuilder: (context, index) {
final data = snapshot.data[index];
print(data.long, data.lat);
// return UI
},
itemCount: snapshot.data?.length ?? 0,
);
},
)
uj5u.com熱心網友回復:
Flutter 有大量的檔案。您可以閱讀有關從 Internet 獲取資料并在檔案中處理這些資料的所有資訊。
您的問題的答案在Convert the response into a custom Dart object 部分。他們以專輯為例來做這件事,但我相信你可以為你的資料結構做這件事。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/373732.html
