无法加载JSON数据以在ListView中显示

问题描述 投票:0回答:1

我需要通过提供get方法来在flutter应用程序中获取json数组数据。

我面临的问题是我无法将记录放入空列表carList中。

但是我得到的对象数组如下图所示(POSTMAN):>

print(json.decode(response.body))// // [在cars.dart文件中

因此,如果可以的话,请帮助我在

List carlist = [];

]中获取答复。Car_list.dart文件调用获取请求的方法。

如果您需要我提供的进一步信息,请告诉我。

谢谢

邮递员

[ { "id": "1", "carModel" : "Maruti swift", "carDescription" : "The car has a top speed of 180 km/hr" }, { "id": "1", "carModel" : "Hyundai santro", "carDescription" : "The car has a top speed of 150 km/hr" }, { "id": "1", "carModel" : "Hyundai creta", "carDescription" : "The car has a top speed of 160 km/hr" } ]

CarsModel.dart

class Cars with ChangeNotifier{ String userId; String carModel String carDescription; Cars( { this.userId = '1111', this.carModel, this.carDescription, } ); factory Cars.fromJSON(Map<String,dynamic> json) => Cars( userId : json['userId'], carModel : json['CarModel'], carDescription : json['carDescription'], ); toJSON() { return { 'userId':'111', 'carModel':carModel, 'carDescription' : carDescription }; }

cars.dart

class CarProvider with ChangeNotifier{ List<Cars> carlist = [ //Sample data to show the format in which the data needs to be shown as the listview gets populated from below records which we are supposed to get from postman //Cars ( // userid: 1111, // carModel: 'Maruti Alto', // carDescription: 'Top speed 140 km/hr' ), ]; Future<void> readListofCars(int id) async { print(id.toString()); const url = 'http://localhost/userlist'; // {'id': id.toString() Map<String, String> headers = { "Content-type": "application/json"}; try { final response = await http.get(url,headers: headers); List<dynamic> bodyCars = jsonDecode(response.body); List<Cars> loadedCars = bodyCars.map((dynamic item) => new Cars.fromJSON(item)).toList(); /* for (Map i in bodyCars) { _notificationitems.add(Cars.fromJSON(i)); } */ }); print(response.statusCode); carlist = loadedCars; print(json.decode(response.body)); notifyListeners(); }catch (error){ throw error; } }

Car_list.dart

class TabScreenCar extends StatefulWidget { final String userId; TabScreenCar(this.userId); @override _TabScreenCarState createState() => _TabScreenCarState(); } class _TabScreenCarState extends State<TabScreenCar> { @override void didChangeDependencies() { final id = 1111; Provider.of<CarProvider>(context).readListofCars(id); super.didChangeDependencies(); }

我需要通过提供get方法来在flutter应用程序中获取json数组数据。我面临的问题是我无法将记录放入空列表carList中。但我得到了...
json flutter dart
1个回答
0
投票
在模型类中,您有错误的变量无法获取json数据

为了简化过程,您可以查看此链接

© www.soinside.com 2019 - 2024. All rights reserved.