【问题标题】:Error HTTP Post Request Unhandled Exception: type 'List<dynamic>' is not a subtype of type 'Map<String, dynamic>'错误 HTTP Post 请求未处理异常:类型 'List<dynamic>' 不是类型 'Map<String, dynamic>' 的子类型
【发布时间】:2021-05-25 09:53:22
【问题描述】:

我想发出一个 post 请求,但突然收到此错误 'List' is not a subtype of type 'Map' 我的 post 请求有问题,因为我一直在尝试发出 post 请求....请任何人都可以帮助我解决我一直遇到的这个错误。

PostData.dart

class PostData extends StatefulWidget {
  final Future postData;
  const PostData({Key key, this.postData}) : super(key: key);

  @override
  _PostDataState createState() => _PostDataState(postData);
}

class _PostDataState extends State<PostData> {
  _PostDataState(this.postData);

  Future createPost(String url, {Map body}) async {
    return http.post(url, body: body).then((http.Response response) {
      final int statusCode = response.statusCode;

      if (statusCode < 200 || statusCode > 400 || json == null) {
        throw new Exception("Error while fetching data");
      }
      return Post.fromJson(json.decode(response.body));
    });
  }

  final Future postData;

  static final cREATE_POST_URL =
      'https://my-json-server.typicode.com/HakimRahim46/mockjson/postData';

  final TextEditingController namalokasi = TextEditingController();
  final TextEditingController kodlokasi = TextEditingController();
  final TextEditingController nama = TextEditingController();
  final TextEditingController bodyController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        resizeToAvoidBottomInset: false,
        resizeToAvoidBottomPadding: false,
        appBar: AppBar(
          title: Text('Create Data Example'),
          backgroundColor: Colors.blueAccent[700],
        ),
        body: Container(
            child: Column(children: <Widget>[
          ListTile(
              title: TextField(
                maxLines: null,
                decoration: InputDecoration(
                  labelText: "Kod Lokasi:",
                ),
                controller: kodlokasi,
              ),
              leading: IconButton(icon: Icon(Icons.map), onPressed: () {})),
          ListTile(
            title: TextField(
              maxLines: null,
              decoration: const InputDecoration(labelText: "Nama Lokasi:"),
              controller: namalokasi,
            ),
            leading: IconButton(
              icon: Icon(Icons.map_rounded),
              onPressed: () {},
            ),
          ),
          ListTile(
              title: TextField(
                maxLines: null,
                decoration: InputDecoration(
                  labelText: "Nama Pegawai:",
                ),
                controller: nama,
              ),
              leading: IconButton(icon: Icon(Icons.person), onPressed: () {})),
          SizedBox(
            height: 32,
          ),
          RaisedButton(
            onPressed: () async {
              // ignore: missing_required_param
              Post newPost = new Post(
                id: 0,
                kodlokasi: kodlokasi.text,
                namalokasi: namalokasi.text,
                nama: nama.text,
              );
              Post p = await createPost(cREATE_POST_URL, body: newPost.toMap());
              print(p.kodlokasi);
              // insert();
              Navigator.push(
                  context, MaterialPageRoute(builder: (context) => MyHeader()));
              // setState(() {
              //   print(kodlokasi.text);
              //   print(namalokasi.text);
              //   print(nama.text);
              // });
            },
            child: Text("Submit"),
          )
        ])));
  }
}

Postjson.dart

class Post {
  Post({
    @required this.kodlokasi,
    @required this.namalokasi,
    @required this.nama,
    @required this.catatan,
    @required this.status,
    @required this.id,
  });

  final String kodlokasi;
  final String namalokasi;
  final String nama;
  final String catatan;
  final String status;
  final int id;

  factory Post.fromJson(Map<String, dynamic> json) => Post(
        kodlokasi: json["kodlokasi"],
        namalokasi: json["namalokasi"],
        nama: json["nama"],
        catatan: json["catatan"],
        status: json["status"],
        id: json["id"],
      );

  Map toMap() {
    var map = new Map();
    map['kodlokasi'] = kodlokasi;
    map['namalokasi'] = namalokasi;
    map['nama'] = nama;

    return map;
  }
}

【问题讨论】:

  • 您可能正在从 api 调用中获取数组。你能打印回复吗?
  • 我在打印响应 I/flutter (24900) 时得到这个:“响应”实例
  • print(response.body);
  • I/flutter (24900): [ I/flutter (24900): { I/flutter (24900): "kodlokasi": "001", I/flutter (24900): "namalokasi": "Pulau Pinang", I/flutter (24900): "nama":"Ali", I/flutter (24900): "catatan": "Maklumat", I/flutter (24900): "status": "", I /flutter (24900): "id":"1" I/flutter (24900): } I/flutter (24900): ]
  • 您的结果是列表,而不是地图。这就是你得到错误的原因。

标签: api flutter http dart


【解决方案1】:

您的结果是List,而不是Map。

试试这个。它将返回List&lt;Post&gt;。

Future createPost(String url, {Map body}) async {
    return http.post(url, body: body).then((http.Response response) {
      final int statusCode = response.statusCode;

      if (statusCode < 200 || statusCode > 400 || json == null) {
        throw new Exception("Error while fetching data");
      }
      return Post.fromJson(json.decode(response.body)[0]);
    });
  }

【讨论】:

  • 它得到这个错误未处理的异常:类型'List'不是类型'Post'的子类型
猜你喜欢
  • 2019-09-26
  • 2021-05-21
  • 1970-01-01
  • 2020-11-05
  • 1970-01-01
  • 1970-01-01
  • 2020-08-20
  • 2019-08-07
  • 2021-08-03
相关资源
最近更新 更多