使用Json错误是*类型'List <dynamic>'不是类型'String'的子类型*

时间:2019-12-20 08:15:06

标签: flutter

这是我的回应 http://dummy.restapiexample.com/api/v1/employees

我正在显示来自api的列表,我在response.body完美时得到了响应,但随后不知道会发生什么情况

我的PODO或模型是

class NewData {
  String id;
  String employeeName;
  String employeeSalary;
  String employeeAge;
  String profileImage;

  NewData(
      {this.id,
        this.employeeName,
        this.employeeSalary,
        this.employeeAge,
        this.profileImage});

  factory NewData.fromJson(Map<String, dynamic> json) => NewData(
    id: json["id"],
    employeeName: json["employee_name"],
    employeeSalary: json["employee_salary"],
    employeeAge: json["employee_age"],
    profileImage: json["profile_image"],
  );


  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['id'] = this.id;
    data['employee_name'] = this.employeeName;
    data['employee_salary'] = this.employeeSalary;
    data['employee_age'] = this.employeeAge;
    data['profile_image'] = this.profileImage;
    return data;
  }
}

我的Main.dart是

body: Container(
        child: Column(
          children: <Widget>[
            FutureBuilder<NewData>(
                future: fetchPost(),
                builder: (context, snapshot) {
                  if (snapshot.connectionState == ConnectionState.done) {
                    if (snapshot.hasError) {
                      return Text("ERROR : - " + snapshot.error.toString());
                    }
                    List<NewData> data = snapshot.data as List<NewData>;
                    return new ListView.builder(
                      itemCount: data.length,
                      itemBuilder: (context, index) {
                        return new ListTile(
                          title: new Text(data[index].employeeName),
                        );
                      },
                    );
                  } else {
                    // By default, show a loading spinner.
                    return Center(
                      child: CircularProgressIndicator(),
                    );
                  }
                }),
          ],
        ),
      ),
    );
  }

  Future<NewData> fetchPost() async {
    var response = await http.get(url);
    if (response.statusCode == 200) {
      // If server returns an OK response, parse the JSON.
      var resp = json.decode(response.body);
      print(resp.toString());
      return NewData.fromJson(resp);
    } else {
      // If that response was not OK, throw an error.
      throw Exception('Failed to load post');
    }
  }

但是我遇到了这个错误

  

“列表”类型不是“字符串”类型的子类型

帮我解决这个问题 我该如何摆脱呢?

2 个答案:

答案 0 :(得分:0)

您请求的JSON返回一个对象列表,并且在您的代码中您对一个对象进行了解构。因此,当您使用<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;">进行解析时,您尝试解析的是对象列表,而不是单个对象。

您最好这样做:

NewData.fromJson(resp)

来源:How to Deserialize a list of objects from json in flutter

然后,您将可以将Iterable l = json.decode(rseponse.body); List<NewData> dataList = l.map((Map model)=> NewData.fromJson(model)).toList(); 的返回类型更新为fetchPost()

答案 1 :(得分:0)

您需要进行一些更改以使其起作用:

  1. FutureBuilder<NewData>(FutureBuilder<List<NewData>>(

  2. List<NewData> data = snapshot.data as List<NewData>;List<NewData> data = snapshot.data;

  3. return new ListView.builder(return new Expanded(child: ListView.builder(

  4. fetchPost() method

完整代码:

import 'package:http/http.dart' as http;
import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:convert';

class Demo extends StatefulWidget {
  @override
  _DemoState createState() => _DemoState();
}

class _DemoState extends State<Demo> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("DEMO"),
      ),
      body: Container(
        child: Column(
          children: <Widget>[
            FutureBuilder<List<NewData>>(
                future: fetchPost(),
                builder: (context, snapshot) {
                  if (snapshot.connectionState == ConnectionState.done) {
                    if (snapshot.hasError) {
                      return Text("ERROR : - " + snapshot.error.toString());
                    }

                    List<NewData> data = snapshot.data;

                    return new Expanded(
                        child: ListView.builder(
                      itemCount: data.length,
                      itemBuilder: (context, index) {
                        return new ListTile(
                          title: new Text(data[index].employeeName),
                        );
                      },
                    ));
                  } else {
                    // By default, show a loading spinner.
                    return Center(
                      child: CircularProgressIndicator(),
                    );
                  }
                }),
          ],
        ),
      ),
    );
  }

  Future<List<NewData>> fetchPost() async {
    var response =
        await http.get("http://dummy.restapiexample.com/api/v1/employees");
    if (response.statusCode == 200) {
      // If server returns an OK response, parse the JSON.
      var resp = json.decode(response.body);
      print(resp.toString());

      final parsed = resp.cast<Map<String, dynamic>>(); // added this
      return parsed
          .map<NewData>((json) => NewData.fromJson(json))
          .toList(); // add this too
    } else {
      // If that response was not OK, throw an error.
      throw Exception('Failed to load post');
    }
  }
}

class NewData {
  String id;
  String employeeName;
  String employeeSalary;
  String employeeAge;
  String profileImage;

  NewData(
      {this.id,
      this.employeeName,
      this.employeeSalary,
      this.employeeAge,
      this.profileImage});

  factory NewData.fromJson(Map<String, dynamic> json) => NewData(
        id: json["id"],
        employeeName: json["employee_name"],
        employeeSalary: json["employee_salary"],
        employeeAge: json["employee_age"],
        profileImage: json["profile_image"],
      );

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['id'] = this.id;
    data['employee_name'] = this.employeeName;
    data['employee_salary'] = this.employeeSalary;
    data['employee_age'] = this.employeeAge;
    data['profile_image'] = this.profileImage;
    return data;
  }
}