My Blog

My WordPress Blog

My Blog

My WordPress Blog

Step 1: Add Dependencies

First, add the required dependencies to your pubspec.yaml:

dependencies:
  drift: ^2.4.0
  drift_flutter: ^2.4.0
  sqlite3_flutter_libs: ^0.5.0 # For SQLite support

dev_dependencies:
  build_runner: ^2.3.0
  drift_dev: ^2.4.0

Step 2: Create a Database Model

Create a new Dart file for your database model, e.g., database.dart.

import 'package:drift/drift.dart';
import 'package:drift/native.dart';

part 'database.g.dart'; // The part directive for code generation

@DataClassName('Task') // The class that will represent a row
class Tasks extends Table {
  IntColumn get id => integer().autoIncrement()(); // Auto-incrementing ID
  TextColumn get name => text().withLength(min: 1, max: 50)(); // Task name
  BoolColumn get isComplete => boolean().withDefault(Constant(false))(); // Completion status
}

@DriftDatabase(tables: [Tasks])
class AppDatabase extends _$AppDatabase {
  AppDatabase() : super(NativeDatabase.memory()); // Use in-memory database for testing

  @override
  int get schemaVersion => 1;

  // Define methods for database operations
  Future<List<Task>> getAllTasks() => select(tasks).get();
  Future insertTask(Insertable<Task> task) => into(tasks).insert(task);
  Future updateTask(Insertable<Task> task) => update(tasks).replace(task);
  Future deleteTask(Insertable<Task> task) => delete(tasks).delete(task);
}

Step 3: Generate the Code

Run the following command to generate the necessary code:

flutter pub run build_runner build

This will create a file named database.g.dart with the generated code.

Step 4: Use the Database

Now you can use the database in your Flutter app. Here’s a simple example of how to use it:

import 'package:flutter/material.dart';
import 'database.dart'; // Import your database model

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
return MaterialApp(
  home: TaskList(),
);
} } class TaskList extends StatefulWidget { @override _TaskListState createState() => _TaskListState(); } class _TaskListState extends State<TaskList> { late AppDatabase _database; @override void initState() {
super.initState();
_database = AppDatabase(); // Initialize the database
} Future<void> _addTask(String name) async {
final task = TasksCompanion(
  name: Value(name),
  isComplete: Value(false),
);
await _database.insertTask(task);
setState(() {}); // Refresh the UI
} Future<List<Task>> _fetchTasks() async {
return await _database.getAllTasks();
} @override Widget build(BuildContext context) {
return Scaffold(
  appBar: AppBar(title: Text('Tasks')),
  body: FutureBuilder&lt;List&lt;Task>>(
    future: _fetchTasks(),
    builder: (context, snapshot) {
      if (snapshot.connectionState == ConnectionState.waiting) {
        return Center(child: CircularProgressIndicator());
      }
      final tasks = snapshot.data ?? &#91;];
      return ListView.builder(
        itemCount: tasks.length,
        itemBuilder: (context, index) {
          final task = tasks&#91;index];
          return ListTile(
            title: Text(task.name),
            trailing: Checkbox(
              value: task.isComplete,
              onChanged: (value) {
                // Update task completion status
                final updatedTask = task.copyWith(isComplete: value);
                _database.updateTask(updatedTask);
                setState(() {}); // Refresh the UI
              },
            ),
          );
        },
      );
    },
  ),
  floatingActionButton: FloatingActionButton(
    onPressed: () {
      // Add a new task (for example)
      _addTask('New Task');
    },
    child: Icon(Icons.add),
  ),
);
} }

Step 5: Run the App

Run your Flutter app, and you should see a simple task list that allows you to add and check off tasks!

Moor

Leave a Reply

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

Scroll to top