我正在學習顫振和飛鏢,我試圖在練習中實作狀態管理和 REST API 資料,但自 2 天以來我得到了同樣的錯誤。我的程序與教程鏈接相同,但我在資料服務的某個地方出錯了
import 'dart:convert';
import 'package:flutter_cubit/model/data_model.dart';
import 'package:http/http.dart' as http;
class DataServices {
String baseUrl = "https://61f969ae69307000176f7243.mockapi.io";
Future<List> getInfo() async {
var apiUrl = '/DevMobile';
http.Response res = await http.get(Uri.parse(baseUrl apiUrl));
try {
if (res.statusCode == 200) {
List<dynamic> list = json.decode(res.body);
print('donnees service non formaté $list');
return list.map((e) => DataModel.fromJson(e)).toList();
} else {
return <DataModel>[];
}
} catch (e) {
//print(e);
return <DataModel>[];
}
}
}
和資料模型
class DataModel {
String name;
String img;
int price;
int people;
int stars;
String description;
String location;
dynamic createdAt;
DataModel({
required this.name,
required this.img,
required this.price,
required this.people,
required this.stars,
required this.description,
required this.location,
});
factory DataModel.fromJson(Map<String, dynamic> json) {
return DataModel(
name: json["name"],
img: json["img"],
price: json["price"],
people: json["people"],
stars: json["stars"],
description: json["description"],
location: json["location"],
);
print('Données du model $DataModel');
}
}
經過大量列印以了解問題出在哪里,它表明所有資料都在資料服務上消失了,就在我這樣list.map((e) => DataModel.fromJson(e)).toList();
做時,我按照教程中的方式進行了所有操作,但它不起作用。
感謝您的幫助
uj5u.com熱心網友回復:
DataModel類包含價格欄位,它是int但 api 以String的形式為您提供,因此您可以將其決議為 int 或將型別更改為String
String price;
- - - - 或者 - - - -
從Json方法更改為
factory DataModel.fromJson(Map<String, dynamic> json) {
return DataModel(
name: json["name"],
img: json["img"],
price: num.parse(json["price"]).toDouble(), // here it is changed
people: json["people"],
stars: json["stars"],
description: json["description"],
location: json["location"],
);
}
只需復制并粘貼它就可以了??
還將價格型別更改為 dobule,因為它轉換為double
double price
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/496453.html
上一篇:提供者:如何在`StreamBuilder()`中`notifyListener()`?它會導致錯誤“setState()或markNeedsBuild()在構建期間呼叫”
