简体   繁体   English

如何在 flutter 的文本小部件中使用双精度值

[英]How to use double value in Text widget in flutter

I got a response from API which is我收到了 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}},

I'm display price into Text widget but it gives me this error我在Text小部件中显示price ,但它给了我这个错误

type 'double' is not a subtype of type 'int' please let me know how to display double value in text widget type 'double' is not a subtype of type 'int'请告诉我如何在文本小部件中显示双精度值

ProductModel class:产品型号 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};
}

Try below code hope its help to you.试试下面的代码希望它对你有帮助。

Your var declaration:您的 var 声明:

double price = 109.95; 

Your Widget:您的小部件:

Using String Interpolation:使用字符串插值:

    Text(
        'Price: $price',
      ),

OR Using toString():使用 toString():

  Text(
         price.toString() ,
      ),

Result Screen->结果屏幕-> 在此处输入图像描述

Answer of @Ravindra is correct but you need to fix your model. @Ravindra 的答案是正确的,但您需要修复您的 model。

First, change price type to double一、将价格类型改为双倍

Second, change二、改变

price: json['price']

to

price: (json['price'] as num)?.toDouble()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM