【问题标题】:Can not initialize jsonResponse in Flutter project无法在 Flutter 项目中初始化 jsonResponse
【发布时间】:2020-12-22 12:48:29
【问题描述】:

在我的项目中,我得到了我的 json 字符串,后来我尝试为它分配一个 jsonResponse 变量,但出现如下错误:无法将参数类型“响应”分配给参数类型“字符串”。

这是我的代码:

Future getMahalle() async {
    BaseOptions options = new BaseOptions(
      baseUrl: globals.PROD_URL,
      connectTimeout: 5000,
      receiveTimeout: 3000,
    );
    Dio dio = new Dio(options);
    dio.options.headers["Authorization"] = "Bearer ${globals.USER_TOKEN}";
    try {
      var response =
          await dio.get(globals.SELECT_URL); //'api/hizlirapor/selects'
      
      final jsonResponse = jsonDecode(response); //Here is the error line
      MahalleModel mahalleList =
          MahalleModel.fromJson(jsonDecode(response.data['mahalle']));

      return mahalleList;
    } on DioError catch (e) {
      debugPrint("ERRORR!!!!!!!!!!!!! ${e.error.toString()}");
      return null;
    }
  }

例如,我正在尝试实施this 文章并陷入困境。感谢您的帮助!

【问题讨论】:

    标签: json api flutter asynchronous dart


    【解决方案1】:

    由于您使用的是 dio,因此您不必解码返回的 json,dio 会为您完成。

    // if it's a single value than try this.
    MahalleModel mahalleList = response.data.map<MahalleModel>((mahalle) => MahalleModel.fromJson(mahalle));
    
    // if it's a list than try this.
    List<MahalleModel> mahalleList = response.data['mahalle'].map<MahalleModel>((mahalle) => MahalleModel.fromJson(mahalle)).toList();
    

    【讨论】:

    • 我尝试了你的第二个建议。现在我得到了一个调试控制台语句:“未处理的异常:NoSuchMethodError:类 '_InternalLinkedHashMap' 没有具有匹配参数的实例方法 'map'。”顺便感谢关于 dio 的信息。我是 dio 的新手。
    • 你的 frommap 是什么?
    • 请立即检查..在 response.data 之后错过“['mahalle']”...请立即尝试...
    • 这行得通吗?我已经编辑了我的答案...如果您的方法有效...其他尝试编辑... List mahalleList = response.data['mahalle'].map((mahalle) => MahalleModel.fromJson(mahalle)).toList();
    • 哦,我看到了您对答案的编辑。它完美地工作。感谢您提供的宝贵信息。
    猜你喜欢
    • 1970-01-01
    • 2020-08-29
    • 2020-08-22
    • 2019-06-19
    • 2022-08-04
    • 2020-12-21
    • 1970-01-01
    • 2021-12-30
    • 2023-02-13
    相关资源
    最近更新 更多