【问题标题】:How to get Local JSON in flutter normal class如何在颤振普通类中获取本地 JSON
【发布时间】:2021-12-25 09:59:30
【问题描述】:

服务-> math_logic.dart 它只是数学计算页面,所以我不用于 StateFul Widget 我收到 Futur 的错误不是 String 的子类型 future 不是一个类型 String 作为 cast...

import 'package:flutter/services.dart';

class Logic {
//Get JSON
  final response =
      rootBundle.loadString('assets/file/Data.json').then((value) => value);
  
//Vehicle Age Method
  vehicleAge(DateTime doPurchase, DateTime doRenewel) {
    var vAge = doPurchase.difference(doRenewel).abs().inDays.toInt();
    return vAge;
  }

 

// below Five Years Method

  belowFiveYear(int age, int fiveyear, int getInt, String zone,
      String odBasicRate, int basicTP) {
    response.then((value) => {print(value)});

    if (age <= fiveyear && getInt == 76150 && zone == 'Zone A') {
      odBasicRate = response[0]['Zone A']; //Error Here, don't get a json Data
      basicTP = 752;
      return [odBasicRate, basicTP];
    }
    
    
  }
}

在我的 json 数据下面给出 数据.json

[
  
  {
    "Product no": 1,
    "Type of Vehicle": "Two Wheeler",
    "Vehicle Age": "Vehicle Age <= 5 years",
    "CC": "Upto 150 CC",
    "Zone A": "1.708",
    "Zone B": "1.676",
    "Zone C": "NA",
    "TP Premium": "-",
    "Per passenger": "-",
    "LT TP Premium": "-",
    "Option 1": "-",
    "Option 2": "-",
    "Discount": "-",
    "Rate percentage": "-"

  }etc..

[My code page is below][1]
  
]

【问题讨论】:

  • 你的json解码了吗?

标签: json flutter dart


【解决方案1】:

loadString 是一个异步方法,因此返回一个Future&lt;String&gt;Future&lt;T&gt;.then() 方法也返回一个 Future,所以你的 response 变量实际上是 Future&lt;String&gt; 类型的

简而言之,您需要在某处定义为async 的方法到await 才能完成该方法。 This thread 提供了一些关于初始化依赖于异步调用的实例成员的见解和示例。

【讨论】:

  • 谢谢老兄...它对我更有帮助
猜你喜欢
  • 2021-09-06
  • 2020-05-30
  • 2019-12-10
  • 2020-04-02
  • 2019-04-20
  • 2021-03-26
  • 2020-05-02
  • 2021-03-17
  • 2021-04-24
相关资源
最近更新 更多