Flutter 将 API 值返回给 FutureBuilder Null

时间:2021-05-07 04:14:14

标签: api flutter listview dart mobile

我想从 API 获取数据并将其转换为 List 以显示到 Mobile,但 FutureBuilder 总是说我的数据为空。我已经打印了我的数据,它有数据。但是当我将它返回给 FutureBuilder 时,它只是 null。

API 示例

{
  "success": true,
  "data": {
    "current_page": 1,
    "data": [
      {
        "absence_date": "2021-02-09",
        "time_in": "07:51:34",
        "time_out": "17:14:28"
      },
      {
        "absence_date": "2021-02-08",
        "time_in": "07:53:56",
        "time_out": "17:09:15"
      },
      {
        "absence_date": "2021-02-05",
        "time_in": "07:53:32",
        "time_out": "17:17:31"
      }
    ],
    "last_page": 4
  }
}

出勤.dart -> 模型

@JsonSerializable()
class Attendance {
  @JsonKey()
  List<dynamic> data;
  @JsonKey()
  int last_page;

  Attendance();

  factory Attendance.fromJson(Map<String, dynamic> json) => _$AttendanceFromJson(json);

  Map<String, dynamic> toJson() => _$AttendanceToJson(this);
}

ListView.dart -> _fecthJobs

Widget build(BuildContext context) {
  return FutureBuilder<List<Job>>(
    future: _fetchJobs(),
    builder: (context, snapshot) {
      print(snapshot.data);
      if (snapshot.hasData) {
        List<Job> data = snapshot.data;
        return _jobsListView(data);
      } else if (snapshot.hasError) {
        return Text("${snapshot.error}");
      }
      return CircularProgressIndicator();
    },
  );
}

Future<List<Job>> _fetchJobs() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
    var email = prefs.getString('email');
    await api.attendances(email).then((items) async {
      if (items.success == true) {
        Attendance att = Attendance.fromJson(items.data);
        print(att.data);
        return att.data.map((job) => new Job.fromJson(job)).toList();
      }
    }).catchError((e) {
      print('Exception $e');
  });
}

我打印att.data,它有数据API,但是当它在snapshot.data中时,它说它为空

0 个答案:

没有答案