我正在尝试使用 List Tile Builder 在 Future Builder 中打印 JSON 的值。但我不知道如何从嵌套 JSON 获取特定值到列表平铺文本小部件。有人可以帮助我吗?
这是 JSON 文件及其链接:
{
"result":"success",
"data":[
{
"Id":1,
"LucasTvsPartNo":"26080177",
"PartImage":"LFAA 5031.png",
"FilterType":"Air Filter",
"CustomerPartNo":"LFAA-5031",
"Model":"Bajaj GC 1000",
"ModelImage":"bajajgc1000.png",
"Segment":"3W",
"Descriptions":"Air Filter - Polyurethane Type",
"OEMName":"BAJAJ",
"OEMImage":"bajaj.png",
"OEMPartNo":null,
"ListPrice":156.87,
"MRPPrice":189.0,
"MasterCartonSize":32
}
]
}
此 JSON 中的数据字段有很多记录,最多 10 条。
这是使用 JSON 到 Dart 的数据模型:
class Temperatures {
final String result;
final List<Datum> data;
Temperatures({
required this.result,
required this.data,
});
}
class Datum {
final int id;
final String lucasTvsPartNo;
final String partImage;
final String filterType;
final String customerPartNo;
final String model;
final String modelImage;
final String segment;
final String descriptions;
final String oemName;
final String oemImage;
final dynamic oemPartNo;
final double listPrice;
final int mrpPrice;
final int masterCartonSize;
Datum({
required this.id,
required this.lucasTvsPartNo,
required this.partImage,
required this.filterType,
required this.customerPartNo,
required this.model,
required this.modelImage,
required this.segment,
required this.descriptions,
required this.oemName,
required this.oemImage,
required this.oemPartNo,
required this.listPrice,
required this.mrpPrice,
required this.masterCartonSize,
});
}
我的使用未来构建器将数据从类打印到 UI 的代码:
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:sample_app/DbHelper/Product.dart';
class Home extends StatefulWidget {
const Home({super.key});
@override
State<Home> createState() => _HomeState();
}
class _HomeState extends State<Home> {
late Future _futureData;
@override
void initState() {
WidgetsFlutterBinding.ensureInitialized();
_futureData = getData();
super.initState();
}
Future getData() async {
var url = Uri.parse(
'http://35.154.214.176/LucasfilterAPI/api/Values/GetPricelist');
var response = await http.get(url, headers: {
"Accept": "application/json",
"content-type": "application/json"
});
Map<String, dynamic> jsonMap = json.decode(response.body);
print(response.statusCode);
print(response.body);
List<Product> Products =
List<Product>.from(jsonMap['data'].map((x) => Data.fromJson(x)));
return Products;
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: FutureBuilder(
future: _futureData,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(
child: CircularProgressIndicator(),
);
} else if (snapshot.hasError) {
return Center(
child: Text('Error fetching data'),
);
} else {
List Data = snapshot.data;
return ListView.builder(
itemCount: Data.length,
itemBuilder: (context, index) {
return ListTile(
title: Text('Result: ${Data[index].result}'),
subtitle: Text('Data: ${Data[index].data.toString()}'),
);
},
);
}
}),
);
}
}
它向我展示了获取数据的错误。我不知道如何处理嵌套的 JSON 数据。这就是所描述的问题。如果您想进一步澄清。我也可以提供。
您可以参考this链接了解如何解析和显示来自API的数据,而且我认为您使用了错误的数据解析模型,您应该这样做
List<Datum>.from(jsonMap['data'].map((x) => Datum.fromJson(x)));
您需要在
Datum
类中创建 fromJson 函数,以便您可以使用 Json Serialized 包。
class Datum {
final int id;
final String lucasTvsPartNo;
final String partImage;
final String filterType;
final String customerPartNo;
final String model;
final String modelImage;
final String segment;
final String descriptions;
final String oemName;
final String oemImage;
final double listPrice;
final double mrpPrice;
final int masterCartonSize;
Datum({
required this.id,
required this.lucasTvsPartNo,
required this.partImage,
required this.filterType,
required this.customerPartNo,
required this.model,
required this.modelImage,
required this.segment,
required this.descriptions,
required this.oemName,
required this.oemImage,
required this.listPrice,
required this.mrpPrice,
required this.masterCartonSize,
});
factory Datum.fromJson(Map<String, dynamic> json) {
return Datum(
id: json['Id'],
lucasTvsPartNo: json['LucasTvsPartNo'],
partImage: json['PartImage'],
filterType: json['FilterType'],
customerPartNo: json['CustomerPartNo'],
model: json['Model'],
modelImage: json['ModelImage'],
segment: json['Segment'],
descriptions: json['Descriptions'],
oemName: json['OEMName'],
oemImage: json['OEMImage'],
listPrice: json['ListPrice'].toDouble(),
mrpPrice: json['MRPPrice'].toDouble(),
masterCartonSize: json['MasterCartonSize'],
);
}
}
class Temperatures {
String? result;
List<Datum?>? data;
Temperatures({this.result, this.data});
Temperatures.fromJson(Map<String, dynamic> json) {
result = json['result'];
if (json['data'] != null) {
data = <Datum>[];
json['data'].forEach((v) {
data!.add(Datum.fromJson(v));
});
}
}
}
并且从互联网获取数据:
Future fetchData() async {
try {
var url = Uri.parse(u);
var response = await http.get(url, headers: {
"Accept": "application/json",
"content-type": "application/json"
});
if (response.statusCode == 200) {
return Temperatures.fromJson(
jsonDecode(response.body) as Map<String, dynamic>);
} else {
throw Exception('Failed to load ');
}
} catch (e) {
print(e.toString());
}
}