StreamBuilder 抛出脏状态

StreamBuilder throws dirty state

我正在尝试从互联网上获取一些数据,将其存储到我的 sqlite 数据库中并使用 ListView.

在屏幕上显示

当我第一次获取数据时,一切正常,我能够在屏幕上看到数据,数据也被插入到 sqlite 数据库中,但是当我重新打开应用程序时,我收到一条错误消息

flutter: The following NoSuchMethodError was thrown building StreamBuilder<StudentModel>(dirty, state:
flutter: _StreamBuilderBaseState<StudentModel, AsyncSnapshot<StudentModel>>#3f888):
flutter: The getter 'studentData' was called on null.
flutter: Receiver: null
flutter: Tried calling: studentData

这是我的模型class

class StudentModel {
  int status;
  String msg;
  StudentModelData studentModelData;

  StudentModel({this.status, this.msg, this.studentModelData});

  StudentModel.fromJson(Map<String, dynamic> json) {
    status = json['status'];
    msg = json['msg'];
    studentModelData = json['data'] != null ? new StudentModelData.fromJson(json['data']) : null;
  }

  StudentModel.fromDb(Map<String, dynamic> parsedJson) {
    status = parsedJson['status'];
    msg = parsedJson['msg'];
    studentModelData = parsedJson['data'] != null ? new StudentModelData.fromJson(parsedJson['data']) : null;
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['status'] = this.status;
    data['msg'] = this.msg;
    if (this.studentModelData != null) {
      data['data'] = this.studentModelData.toJson();
    }
    return data;
  }
}

class StudentModelData {
  int lastIndex;
  List<StudentData> studentData;

  StudentModelData({this.lastIndex, this.studentData});

  StudentModelData.fromJson(Map<String, dynamic> json) {
    lastIndex = json['lastIndex'];
    if (json['studentData'] != null) {
      studentData = new List<StudentData>();
      json['studentData'].forEach((v) {
        studentData.add(new StudentData.fromJson(v));
      });
    }
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['lastIndex'] = this.lastIndex;
    if (this.studentData != null) {
      data['studentData'] = this.studentData.map((v) => v.toJson()).toList();
    }
    return data;
  }
}

class StudentData {
  String studentId;
  String studName;
  String studProfilepic;
  String studentEmail;
  String studentMobile;
  String courseName;
  String classCode;
  int minAvg;
  int avg;

  StudentData(
      {this.studentId,
        this.studName,
        this.studProfilepic,
        this.studentEmail,
        this.studentMobile,
        this.courseName,
        this.classCode,
        this.minAvg,
        this.avg});

  StudentData.fromJson(Map<String, dynamic> json) {
    studentId = json['student_id'];
    studName = json['stud_name'];
    studProfilepic = json['stud_profilepic'];
    studentEmail = json['student_email'];
    studentMobile = json['student_mobile'];
    courseName = json['course_name'];
    classCode = json['class_code'];
    minAvg = json['minAvg'];
    avg = json['avg'];
  }

  StudentData.fromDb(Map<String, dynamic> parsedJson){
    studentId = parsedJson['student_id'];
    studName = parsedJson['stud_name'];
    studProfilepic = parsedJson['stud_profilepic'];
    studentEmail = parsedJson['student_email'];
    studentMobile = parsedJson['student_mobile'];
    courseName = parsedJson['course_name'];
    classCode = parsedJson['class_code'];
    minAvg = parsedJson['minAvg'];
    avg = parsedJson['avg'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['student_id'] = this.studentId;
    data['stud_name'] = this.studName;
    data['stud_profilepic'] = this.studProfilepic;
    data['student_email'] = this.studentEmail;
    data['student_mobile'] = this.studentMobile;
    data['course_name'] = this.courseName;
    data['class_code'] = this.classCode;
    data['minAvg'] = this.minAvg;
    data['avg'] = this.avg;
    return data;
  }
}

以下是我的存储库class

class StudentDbProvider implements Source, Cache {

  Database db;

  void init() async {
    print("database initialized");
    Directory documentsDirectory = await getApplicationDocumentsDirectory();
    final path = join(documentsDirectory.path, "students.db");
     db =  await openDatabase(path, version: 1,
        onCreate: (Database newDb, int version) {
      newDb.execute("""
        CREATE TABLE STUDENTS(
          id INTEGER PRIMARY KEY,
          student_id TEXT,
          stud_name TEXT,
          stud_profilepic TEXT,
          student_email TEXT,
          student_mobile TEXT,
          course_name TEXT,
          class_code TEXT,
          minAvg TEXT,
          avg TEXT
        )
       """);
    });


  }

  @override
  Future<int> clear() {
    return db.delete("STUDENTS");
  }

  @override
  Future<StudentModel> fetchStudents(String disciplineId, String schoolId,
      String year_id, String lastIndex) async {

    print("PritishSawant${db==null}");

    final maps =
        await db.query("STUDENTS");

    if (maps.length > 0) {
      return StudentModel.fromDb(maps.first);
    }

    return null;
  }


  @override
  Future<int> addStudent(StudentData studentData) {
    return db.insert("STUDENTS", studentData.toJson(),
        conflictAlgorithm: ConflictAlgorithm.ignore);
  }
}

final studentDbProvider = StudentDbProvider();

以下是我的圈子class

class StudentsBloc {

  final _repository = Repository();
  final _students = PublishSubject<StudentModel>();

  Observable<StudentModel> get students => _students.stream;

  fetchStudents(String disciplineId,String schoolId,String year_id,String lastIndex) async {


    await studentDbProvider.init();

    final student = await _repository.fetchStudents(disciplineId, schoolId, year_id, lastIndex);
    _students.sink.add(student);
  }

  clearCache(){
    return _repository.clearCache();
  }

  dispose(){
    _students.close();
  }


}

据我所知,错误一定是由于数据库初始化不当造成的,但是当我执行第一个网络请求时,一切正常,控制台中没有出现任何错误,数据库也已初始化。我无法理解为什么此错误第二次出现?

我想你在代码的某些部分调用了 snapshot.data.studentData

在流构建器上,我倾向于先进行空检查

if (snapshot.data != null) {
   // your code here
}

然后继续验证数据,否则您可以在 StreamBuilder

提供的 null data 上使用 getter

您应该检查 snapshot!=null && snapshot.hasError 以确保您的数据确实返回

if (snapshot!=null && !snapshot.hasError) { // your code here }