我正在尝试获取数据并使用FutureBuilder
显示。提取调用后,显示type 'int' is not a subtype of type 'String'
这是我的json模型:
class Featured {
final int id;
final String shop_type;
final String name;
final String name_bn;
final String price;
final String price_bn;
final bool old_price;
final String old_price_val;
final String old_price_val_bn;
final String image;
Featured(
{this.id,
this.shop_type,
this.name,
this.name_bn,
this.price,
this.price_bn,
this.old_price,
this.old_price_val,
this.old_price_val_bn,
this.image});
factory Featured.fromJson(Map<String, dynamic> json) {
return Featured(
id: json['id'],
shop_type: json['shop_type'],
name: json['name'],
name_bn: json['name_bn'],
price: json['price'],
price_bn: json['price_bn'],
old_price: json['old_price'],
old_price_val: json['old_price_val'],
old_price_val_bn: json['old_price_val_bn'],
image: json['image'][0]['image_mobile_feature_list']);
}
}
和主窗口小部件
class Products extends StatefulWidget {
@override
_ProductsState createState() => _ProductsState();
}
class _ProductsState extends State<Products> {
Future<List<Featured>> getProducts() async {
final response = await http.get(Uri.encodeFull(kIndexFeaturedUrl));
List<Featured> list = List();
if (response.statusCode == 200) {
var data = json.decode(response.body);
var rest = data["results"] as List;
list = rest.map<Featured>((json) => Featured.fromJson(json)).toList();
return list;
} else {
throw Exception('Network connection failed');
}
}
@override
Widget build(BuildContext context) {
return FutureBuilder(
future: getProducts(),
builder: (context, snapshot) {
if (snapshot.hasData) {
return Text(
'test',
textAlign: TextAlign.center,
overflow: TextOverflow.ellipsis,
style: TextStyle(fontWeight: FontWeight.bold),
);
} else if (snapshot.hasError) {
return Center(child: Text("Error: ${snapshot.error}"));
}
return Center(child: CircularProgressIndicator());
},
);
}
}
更新0:数据样本
{id: 1, name: example, name_bn: example, price: 88, price_bn: 80, old_price: false, old_price_val: null, old_price_val_bn: null, image: [{image_mobile_feature_list: https://xyz/media/CACHE/images/shop/product/IMG_1057_-_Copy_3FW1ZM7/1781f5617cc7efe708439802736d8ea7.webp, image_mobile_product_details: https://xyz/media/CACHE/images/shop/product/IMG_1057_-_Copy_3FW1ZM7/fe2589e7b7df5e542aaf37cb52c44523.webp}]}
更新1:
I/flutter ( 1961): int // id
I/flutter ( 1961): int // price
I/flutter ( 1961): String // price_bn
I/flutter ( 1961): Null // old_price_val
答案 0 :(得分:1)
将toString()
添加到您的price
属性中。
price: json['price'].toString(),
我打赌old_price_val
也是int
时,它也不为空。我也叫toString()
。