【问题标题】:How to use double value in Text widget in flutter如何在颤动的文本小部件中使用双值
【发布时间】:2022-01-19 05:23:40
【问题描述】:

我收到了来自 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 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};
}

【问题讨论】:

    标签: flutter text integer double


    【解决方案1】:

    试试下面的代码希望对你有帮助。

    你的 var 声明:

    double price = 109.95; 
    

    您的小部件:

    使用字符串插值:

        Text(
            'Price: $price',
          ),
    

    使用 toString():

      Text(
             price.toString() ,
          ),
    

    结果屏幕->

    【讨论】:

      【解决方案2】:

      @Ravindra 的答案是正确的,但您需要修复您的模型。

      首先,将价格类型更改为双倍

      二、改变

      price: json['price']
      

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

      【讨论】:

      • 我做到了,谢谢
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-03-10
      • 2022-01-25
      • 2021-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多