我需要通过提供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中。但我得到了...
为了简化过程,您可以查看此链接