簡體   English   中英

如何在 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}},

我在Text小部件中顯示price ,但它給了我這個錯誤

type 'double' is not a subtype of type 'int'請告訴我如何在文本小部件中顯示雙精度值

產品型號 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 的答案是正確的,但您需要修復您的 model。

一、將價格類型改為雙倍

二、改變

price: json['price']

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM