Flutter:快照不显示数据

Flutter: Snapshot isn't showing data

我使用 get 方法(API 调用)创建了一个 Listview 构建器。 API 通话正常,因为我收到了回复。但在小部件 snapshot.data 中显示为空。我无法解决这个问题,也不知道为什么会这样。请有人帮助我。

API 响应体

Here is my code for API call

class APIService {

Future<List<EducationInfo>> getEducationInfo() async {
    String url = "$baseAPIUrl/educations";
    String _token = await SavedData().loadToken();
    String authorization = "Bearer $_token";
    var response = await http.get(url, headers: {
      'Content-Type': 'application/json',
      'Accept': 'application/json',
      "Authorization": authorization
    });
    print('API ${response.statusCode}\n API${json.decode(response.body)}');
    if (response.statusCode == 200) {
      var jsonResponse = response.body;
      var decoded = json.decode(jsonResponse);
      return decoded['success']
          .map<EducationInfo>((b) => EducationInfo.fromJson(b))
          .toList();
    } else {
      throw Exception('Failed to load Education Information');
    }
  }
}

Here is my Model.dart

//Model

class EducationInfo {
  int id;
  String degreeName;
  int rollNumber;
  int regNumber;
  int passingYear;
  String gradeType;
  double cgpa;
  double outOfCgpa;
  String divisionName;
  String groupName;
  String subjectName;
  String boardName;
  String instituteName;

  EducationInfo({
    this.id,
    this.degreeName,
    this.rollNumber,
    this.regNumber,
    this.passingYear,
    this.gradeType,
    this.cgpa,
    this.outOfCgpa,
    this.divisionName,
    this.groupName,
    this.subjectName,
    this.boardName,
    this.instituteName,
  });

  factory EducationInfo.fromJson(Map<String, dynamic> json) {
    return EducationInfo(
      id: json['user_id'],
      degreeName: json['degree_name'],
      rollNumber: json['roll_number'],
      regNumber: json['registration_number'],
      passingYear: json['passing_year'],
      gradeType: json['grade_type'],
      cgpa: json['cgpa'],
      outOfCgpa: json['out_of_cgpa'],
      divisionName: json['division'],
      groupName: json['group_name'],
      subjectName: json['subject_name'],
      boardName: json['board'],
      instituteName: json['institute_name'],
    );
  }
}

这是我的主要代码-

class Resume extends StatefulWidget {
  @override
  _ResumeState createState() => _ResumeState();
}

class _ResumeState extends State<Resume> {
  Future<List<EducationInfo>> furuteEducationInfo;

  @override
  void initState() {
    super.initState();
    furuteEducationInfo = APIService().getEducationInfo();
  }
  @override
  Widget build(BuildContext context) {
  return Scaffold(
      resizeToAvoidBottomPadding: false,
      appBar: AppBar(
        automaticallyImplyLeading: false,
        leading: IconButton(
          icon: Icon(
            Icons.arrow_back_ios,
          ),
          onPressed: () {
            Navigator.pop(context);
          },
        ),
        title: Text("Resume"),
      ),
      body: Align(
      child: FutureBuilder(
                            future: furuteEducationInfo,
                              builder: (context, snapshot) {
                                var educationInfo = snapshot.data;
                                if (snapshot.data == null) {
                                  return Text("No Data Available ");
                                } else if (snapshot.hasData) {
                                  return ListView.builder(
                                      scrollDirection: Axis.vertical,
                                      itemCount: educationInfo.length,
                                      itemBuilder: (context, index) {
                                        var eduInfo = educationInfo[index];
                                        print(
                                            "\nEducation Info ${educationInfo[index]}");
                                        return designedContainer(
                                            _width - 30,
                                            Padding(
                                              padding: EdgeInsets.all(5.0),
                                              child: Stack(
                                                children: [
                                                  Container(
                                                    child: Column(
                                                      children: [
                                                        detailsField(
                                                            "Degree Name",
                                                            "${_checkNull(eduInfo.degreeName)}"),
                                                      ],
                                                    ),
                                                  ),
                                                  Align(
                                                    alignment:
                                                        Alignment.topRight,
                                                    child: editButton(
                                                        Icons.add, "Delete",
                                                        () {
                                                      print("Delete");
                                                    }),
                                                  )
                                                ],
                                              ),
                                            ));
                                      });
                                } else {
                                  Text("Something Went to Wrong");
                                }
                              }),
       ),
    );
  }

这里还有postman截图-

在你的EducationInfo.fromJson方法中

替换

  cgpa: json['cgpa'] ?? 0.0,
  outOfCgpa: json['out_of_cgpa'] ?? 0.0,

因为是future并且是异步运行的,所以你必须检查快照是否有数据,然后等待数据被获取。按照片段代码,您将如何在构建方法中检查它:

 (snapshot.hasData && snapshot.data.length == 0)
                ? Container(
                    child: Center(
                      child: Column(
                        mainAxisSize: MainAxisSize.max,
                        crossAxisAlignment: CrossAxisAlignment.center,
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: <Widget>[
                          Text("Congrats, No jobs asssigned!!!")
                        ],
                      ),
                    ),
                  )
                : (snapshot.hasData)
                    ? Container(
                        child: ListView.builder(
                   .....)