代码之家  ›  专栏  ›  技术社区  ›  PeakGen

Flutter:如何正确地从JSON中读取字段?

  •  0
  • PeakGen  · 技术社区  · 4 年前

    请检查以下颤振代码

    import 'package:flutter/material.dart';
    import 'package:http/http.dart' as http;
    import 'dart:convert' as convert;
    import 'dart:io';
    
    
    class UserService with ChangeNotifier {
      NavLinks _navLinks = NavLinks();
      late User _user;
    
      Future<int> saveUser(User user, String authToken) async {
        print(convert.json.encode(user.toJson()));
        int responsetag = 0;
        try {
          await http.post(Uri.parse(_navLinks.saveUser()),
              body: convert.json.encode(user.toJson()),
              headers: {
                "Accept": "application/json",
                "content-type": "application/json",
                HttpHeaders.authorizationHeader: "Bearer $authToken"
              }).then((http.Response response) {
            final int statusCode = response.statusCode;
    
            print("RESPONSE: " + response.body);
            print("STATUS CODE: " + statusCode.toString());
    
            if (statusCode < 200 || statusCode > 400) {
              throw new Exception("Error while fetching data");
            } else {
              Map<String, dynamic> data = convert.jsonDecode(response.body);
    
              responsetag = int.parse(data["insertId"]);
            }
          });
    
          return responsetag;
        } catch (error) {
          throw (error);
        }
      }
    }
    

    在这里我需要提取 insertId ,将其转换为int并传递。但我总是以错误告终 [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: Exception: type 'int' is not a subtype of type 'String' .

    这里出了什么问题?

    0 回复  |  直到 4 年前
        1
  •  1
  •   Nirmal Code    4 年前

    根据您的代码 data["insertId"] 应该是字符串。

    如果 数据[“insertId”] 是字符串,

    responsetag = int.parse(data["insertId"]);
    

    如果 数据[“insertId”] 是int,

    responsetag = data["insertId"];
    
        2
  •  0
  •   Narul Hidayah    4 年前

    尝试更改:

    responsetag = int.parse(data["insertId"]);
    

    对此

    responsetag = int.parse(data["insertId"].toString());