How to integrate Moor Database in Flutter?

Why is a Moor Database needed?

When we start building the applications, there comes a point where we have to save the data inside the programme itself for user-generated data or offline support.

At that time, we start adding a database to the application’s development.

Moor is one of the available flutter possibilities.

Moor

This is a SQLite-based reactive persistence library for Flutter and Dart.

An SQLite database is made more user-friendly by this layer that sits on top of it.

Let’s get started with the implementation.

Include packages in your pubspec.yaml file.

dependencies:
  flutter:
    sdk: flutter
  moor: ^4.4.1
 
dev_dependencies:
  flutter_test:
    sdk: flutter
  moor_generator: # use the latest version

Table

Make a table based on your requirements.

class Person extends Table {
  IntColumn get id => integer().nullable().autoIncrement()();
 
  TextColumn get name => text()();
 
  TextColumn get email => text()();
 
  TextColumn get country => text()();
 
  TextColumn get language => text()();
}

Database Class

You must register all of your data tables and define the methods for your database in this class.

part 'AppDatabase.g.dart';
 
@PersonMoor(tables: [Person]).
class AppDatabase extends _$AppDatabase {
  AppDatabase(QueryExecutor e) : super(e);
 
  @override
  int get schemaVersion => 1;
 
  Future<List<Person>> getAllPerson() => select(person).get(); 
 
  Stream<List<Person>> streamAllUsers() => select(person).watch();
 
  Future<int> insertPerson(Person person) => into(person).insert(person);
 
  Future<int> deletePerson(Person person) => delete(person).delete(person);
 
  updatePerson(int id, String name) =>
      (update(persons)..where((t) => t.id.equals(id)))
          .write(PersonCompanion(name: Value(name)));
}

The code for the Moore database will then be created by using the command flutter pub run build runner build.

Executor for Query

Executing statements on a database and returning the results in raw form are the duties of a query executor.

class AppDatabaseUtils {
  AppDatabaseUtils._();
 
  static LazyDatabase openConnection() {
    return LazyDatabase(() async {
      final dbFolder = await getApplicationDocumentsDirectory();
      final file = File(p.join(dbFolder.path, 'db.sqlite'));
      return VmDatabase(file);
    });
  }
}

Now that everything has been set up, we can go to the main view.

Step 1: Make a singleton instance of the database class you created.

GetIt locator = GetIt.I;
 
Future setupLocator() async {
  locator.registerSingleton(AppDatabase(AppDatabaseUtils.openConnection()));
}
 
Future<void> main() async {
  await setupLocator();
  runApp(MyApp());
}

Step 2: Let’s start by creating the database’s functionalities.

void insertPerson() async {
  await locator<AppDatabase>().insertPerson(Person(
      id: null,
      name: "Test",
      email: 'test@gmail.com',
      country: 'India',
      language: 'Hindi'));
}
 
void deletePerson() async {
  await locator<AppDatabase>().deletePerson(Person(
      id: 6,
      name: "Test",
      email: 'test@gmail.com',
      country: 'India',
      language: 'Hindi'));
}
 
void updatePerson() {
  locator<AppDatabase>().updatePerson(5, "Update");
}
 
void getPerson() {
  locator<AppDatabase>()
      .getAllPerson()
      .then((value){});
}

Step 3: Let’s use the stream builder to display the data on the UI.

StreamBuilder<List<User>>(
  stream: locator<AppDatabase>().streamAllPerson(),
  builder: (_, AsyncSnapshot<List<Person>> snapshot) {
    print(snapshot.connectionState);
    if (snapshot.connectionState == ConnectionState.active) {
      if (snapshot.hasError) {
        return Text('Error whie fetching data');
      }
      return Expanded(
        child: ListView.builder(
          itemBuilder: (_, int index) {
            return Text(snapshot.data![index].name);
          },
          itemCount: snapshot.data!.length,
        ),
      );
    } else {
      return Text('No data found');
    }
  },
),

Please visit the Moor Database for further information.

I hope this Article has given you some useful knowledge.

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories