Flutter:快照未显示数据

Posted

技术标签:

【中文标题】Flutter:快照未显示数据【英文标题】:Flutter: Snapshot isn't showing data 【发布时间】:2021-04-02 16:27:43 【问题描述】:

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

API 响应正文

这是我的 API 调用代码

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');
    
  

这是我的 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");
                                
                              ),
       ),
    );
  

这里还有邮递员截图-

【问题讨论】:

var educationInfo = snapshot.data; 之前添加print(snapshot); - 您在日志中看到了什么? AsyncSnapshot>(ConnectionState.done, null, type 'int' 不是 type 'double' 的子类型) 所以你有一个错误:snapshot.error 设置为:“type 'int' is not a subtype of type 'double'” 【参考方案1】:

在您的 EducationInfo.fromJson 方法中

替换

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

【讨论】:

【参考方案2】:

由于它是一个未来并且异步运行,您必须检查快照是否有数据,并等待数据被获取。按照 sn-p 代码,您将如何在构建方法中检查它:

 (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(
                   .....)

【讨论】:

以上是关于Flutter:快照未显示数据的主要内容,如果未能解决你的问题,请参考以下文章

Flutter firebase 查询快照错误:“未处理的异常:错误状态:无元素”

Flutter:将firestore快照转换为streambuilder中的列表

来自一个 StreamBuilder 的 Flutter 快照显示在另一个 StreamBuilder 中

Flutter:StreamBuilder 快照——无数据

使用 Mockito 的 FutureBuilder 快照数据为空 - Flutter

Firestore 单文档快照流未更新