Flutter 处理Json错误为*type';列表<;动态>';不是类型为';字符串'*

Flutter 处理Json错误为*type';列表<;动态>';不是类型为';字符串'*,flutter,Flutter,这是我的回答 我正在显示api中的列表,我得到了响应。身体完美,但不知道发生了什么 我的PODO或模型是 class NewData { String id; String employeeName; String employeeSalary; String employeeAge; String profileImage; NewData( {this.id, this.employeeName, this.employ

这是我的回答

我正在显示api中的列表,我得到了响应。身体完美,但不知道发生了什么

我的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;
  }
}
class新数据{
字符串id;
字符串employeeName;
字符串员工工资;
字符串雇员;
字符串轮廓图像;
新数据(
{this.id,
这是我的名字,
这是雇员的工资,
这就是就业年龄,
这个.profileImage});
工厂NewData.fromJson(映射json)=>NewData(
id:json[“id”],
employeeName:json[“员工姓名”],
employeeSalary:json[“员工工资”],
employeeAge:json[“雇员年龄”],
profileImage:json[“profile_image”],
);
映射到JSON(){
最终地图数据=新地图();
数据['id']=this.id;
数据['employee_name']=this.employeeName;
数据['employee_salary']=this.employeeSalary;
数据['employee_age']=此.employeeAge;
数据['profile_image']=this.profileImage;
返回数据;
}
}
我的主要任务是

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');
    }
  }
主体:容器(
子:列(
儿童:[
未来建设者(
future:fetchPost(),
生成器:(上下文,快照){
if(snapshot.connectionState==connectionState.done){
if(snapshot.hasError){
返回文本(“ERROR:-”+snapshot.ERROR.toString());
}
列表数据=快照。数据作为列表;
返回新的ListView.builder(
itemCount:data.length,
itemBuilder:(上下文,索引){
返回新的ListTile(
标题:新文本(数据[索引].employeeName),
);
},
);
}否则{
//默认情况下,显示加载微调器。
返回中心(
子对象:CircularProgressIndicator(),
);
}
}),
],
),
),
);
}
Future fetchPost()异步{
var response=wait http.get(url);
如果(response.statusCode==200){
//如果服务器返回OK响应,则解析JSON。
var resp=json.decode(response.body);
打印(分别为toString());
返回NewData.fromJson(resp);
}否则{
//如果该响应不正常,则抛出一个错误。
抛出异常(“加载post失败”);
}
}
但我犯了这个错误

类型“List”不是类型“String”的子类型

帮我做这个
我如何摆脱它?

您请求的JSON将返回一个对象列表,在您的代码中,您将对单个对象进行反编码。因此,当您使用
NewData.fromJson(resp)
解析它时,您正在尝试解析对象列表,而不是单个对象

你最好做:

Iterable l = json.decode(rseponse.body);
List<NewData> dataList = l.map((Map model)=> NewData.fromJson(model)).toList();
Iterable l=json.decode(rsepose.body);
List dataList=l.map((map model)=>NewData.fromJson(model)).toList();
资料来源:


然后,您将能够将
fetchPost()
返回类型更新为
Future

您请求的JSON将返回一个对象列表,并且在您的代码中取消对单个对象的编码。因此,当您使用
NewData.fromJson(resp)
解析它时,您正在尝试解析对象列表,而不是单个对象

你最好做:

Iterable l = json.decode(rseponse.body);
List<NewData> dataList = l.map((Map model)=> NewData.fromJson(model)).toList();
Iterable l=json.decode(rsepose.body);
List dataList=l.map((map model)=>NewData.fromJson(model)).toList();
资料来源:


然后,您将能够将
fetchPost()
返回类型更新为
Future

,您需要进行一些更改以使其正常工作:

  • FutureBuilder(
    FutureBuilder(

  • List data=snapshot.data as List;
    to
    List data=snapshot.data;

  • 返回新的ListView.builder(
    返回新的扩展(子项:ListView.builder(

  • fetchPost()方法

  • 完整代码:

    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;
      }
    }
    
    import'package:http/http.dart'作为http;
    进口“包装:颤振/材料.省道”;
    导入“dart:async”;
    导入“dart:convert”;
    类Demo扩展StatefulWidget{
    @凌驾
    _DemoState createState();
    }
    类_DemoState扩展了状态{
    @凌驾
    小部件构建(构建上下文){
    返回脚手架(
    appBar:appBar(
    标题:文本(“演示”),
    ),
    主体:容器(
    子:列(
    儿童:[
    未来建设者(
    future:fetchPost(),
    生成器:(上下文,快照){
    if(snapshot.connectionState==connectionState.done){
    if(snapshot.hasError){
    返回文本(“ERROR:-”+snapshot.ERROR.toString());
    }
    列表数据=snapshot.data;
    返回新的扩展(
    子项:ListView.builder(
    itemCount:data.length,
    itemBuilder:(上下文,索引){
    返回新的ListTile(
    标题:新文本(数据[索引].employeeName),
    );
    },
    ));
    }否则{
    //默认情况下,显示加载微调器。
    返回中心(
    子对象:CircularProgressIndicator(),
    );
    }
    }),
    ],
    ),
    ),
    );
    }
    Future fetchPost()异步{
    var响应=
    等待http.get(“http://dummy.restapiexample.com/api/v1/employees");
    如果(response.statusCode==200){
    //如果服务器返回OK响应,则解析JSON。
    var resp=json.decode(response.body);
    打印(r)