如何在 Flutter 的文本小部件中使用双精度值
How to use double value in Text widget in flutter
我收到了 API 的回复
{"id":1,"title":"Fjallraven - Foldsack No. 1 Backpack, Fits 15 Laptops","price":109.95,"description":"Your perfect pack for everyday use and walks in the forest. Stash your laptop (up to 15 inches) in the padded sleeve, your everyday","category":"men's clothing","image":"https://fakestoreapi.com/img/81fPKd-2AYL._AC_SL1500_.jpg","rating":{"rate":3.9,"count":120}},
我将 price
显示到 Text
小部件中,但它给我这个错误
type 'double' is not a subtype of type 'int'
请让我知道如何在文本小部件中显示双精度值
ProductModel class:
class ProductModel {
ProductModel(
{required this.title,
required this.id,
required this.urlImage,
required this.price});
String title;
int id;
String urlImage;
String price;
factory ProductModel.fromJson(Map<String, dynamic> json) => ProductModel(
id: json["id"],
title: json["price"],
urlImage: json["image"],
price: json["price"]);
Map<String, dynamic> toJson() =>
{"id": id, "title": title, "image": urlImage, "price": price};
}
试试下面的代码希望对你有帮助。
您的 var 声明:
double price = 109.95;
您的小部件:
使用字符串插值:
Text(
'Price: $price',
),
或使用toString():
Text(
price.toString() ,
),
结果屏幕->
@Ravindra 的回答是正确的,但你需要修复你的模型。
首先,将价格类型更改为双倍
二、改变
price: json['price']
至
price: (json['price'] as num)?.toDouble()
我收到了 API 的回复
{"id":1,"title":"Fjallraven - Foldsack No. 1 Backpack, Fits 15 Laptops","price":109.95,"description":"Your perfect pack for everyday use and walks in the forest. Stash your laptop (up to 15 inches) in the padded sleeve, your everyday","category":"men's clothing","image":"https://fakestoreapi.com/img/81fPKd-2AYL._AC_SL1500_.jpg","rating":{"rate":3.9,"count":120}},
我将 price
显示到 Text
小部件中,但它给我这个错误
type 'double' is not a subtype of type 'int'
请让我知道如何在文本小部件中显示双精度值
ProductModel class:
class ProductModel {
ProductModel(
{required this.title,
required this.id,
required this.urlImage,
required this.price});
String title;
int id;
String urlImage;
String price;
factory ProductModel.fromJson(Map<String, dynamic> json) => ProductModel(
id: json["id"],
title: json["price"],
urlImage: json["image"],
price: json["price"]);
Map<String, dynamic> toJson() =>
{"id": id, "title": title, "image": urlImage, "price": price};
}
试试下面的代码希望对你有帮助。
您的 var 声明:
double price = 109.95;
您的小部件:
使用字符串插值:
Text(
'Price: $price',
),
或使用toString():
Text(
price.toString() ,
),
结果屏幕->
@Ravindra 的回答是正确的,但你需要修复你的模型。
首先,将价格类型更改为双倍
二、改变
price: json['price']
至
price: (json['price'] as num)?.toDouble()