How to implement Change Notifier along with moor?

Issue

I am trying to make an app having a database it has a table Students

class Students extends Table{

  IntColumn get RollNumber=>integer().autoIncrement()();
  TextColumn get Name => text().withLength(min: 3,max:32)();

  Students( String name){
    Name==name;
  }

@UseMoor(tables: [Students])
class myDatabase extends _$myDatabase {

  myDatabase() : super(_openConnection());
  @override
  int get schemaVersion => 1;

  // loads all student entries

  Future<List<Student>> getAllStudents() => select(students).get();

  //Watches all entries in Students and automatically
  //emits new data when data changes
  Stream<List<Student>>  watchAllStudents()=> select(students).watch();

  Future insertStudent(Student student )=>into(students).insert(student);
  //Future UpdateStudent(Student student )=>update(students).replace(student);
  //Future DeleteStudent(Student student )=>into(students).insert(student);
}

Now I tried to use change notifier with myDatabase but here I cannot extend it so I tried to do this

class myDatabase extends _$myDatabase with ChangeNotifier{
..
}

but the student class showed an error. Now I don’t know how to proceed.

Solution

The better way will be to create a service for the database operations eg

class DatabaseService with ChangeNotifier {
      Future<List<Students>> getListOfStudents() async {
        // fetch list of students here and return it to the function that calls the DB service
      }
   }

Then you create a ViewModel that implements ChangeNotifier for the Screen/Widget or View you intend to use to students in. The ViewModel will call the DatabaseService and return the values from the database. Eg

class StudentViewModel with ChangeNotifier {

setState() {
  notifyListeners();
 }

Future<void> getStudents() async {
  // get students list from db service and call setState() to notifyListeners
 }
}

NB: Database instances are sort of expensive, so you should create a Singleton instance of the db and the dbservice as well. If you try to open multiple instances of the db, moor will throw an exception to alert you to that.

Answered By – Dean

Answer Checked By – David Goodson (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.