Flutter provider listeners not updating themselves when sqflite database data changes

Viewed 185

I created a local database using flutter sqflite. And I want to listen to a length of a list of tasks on that database and update the total count of the tasks, when I add something or remove from that list. But when I call provider.of(context) thing, it doesn't update themselves, means it doesn't listen. I used a stream to grab the database data and show in the UI.

GIF

Here is the database class I created:

class TaskDatabase with ChangeNotifier {
  final String dbName = 'db.sqlite';
  Database? _db;

  List<Task> _tasksList = [];
  int _totalTaskCount = 0;
  final _streamController = StreamController<List<Task>>.broadcast();

Stream<List<Task>> all() =>
      _streamController.stream.map((tasks) => tasks..sort());

  int get totalTasksCount {
    return _totalTaskCount;
  }

  Future<bool> close() async {
    final db = _db;
    if (db == null) {
      return false;
    }

    await db.close();
    return true;
  }
    


Future<bool> open() async {
        if (_db != null) {
          return true;
        }
    
    final directory = await getApplicationDocumentsDirectory();
    final path = '${directory.path}/$dbName';

    try {
      final db = await openDatabase(path);
      _db = db;

      //creating the database table using sqflite
      const createTable = '''CREATE TABLE IF NOT EXISTS "TABLEOFTASKS" (
            "id"    INTEGER NOT NULL,
            "taskTitle" TEXT,
            "isDone"    INTEGER NOT NULL DEFAULT 0,
            PRIMARY KEY("id" AUTOINCREMENT));''';

      await db.execute(createTable);

      // read all existing task objects from the db

      _tasksList = await _fetchTasks();
      _streamController.add(_tasksList);
      return true;
    } catch (e) {
      // print('error = $e');
      return false;
    }
  }
 // Creating a new task and save to the database:
 // other CRUD functions are not added here:)

  Future<bool> create(String taskTitle) async {
    final db = _db;
    if (db == null) {
      return false;
    }
    try {
      final id = await db.insert(
        'TABLEOFTASKS',
        {
          'taskTitle': taskTitle,
          'isDone': 0,
        },
      );
      final task = Task(
        id: id,
        taskTitle: taskTitle,
        isDone: false,
      );
      _tasksList.add(task);
      _streamController.add(_tasksList);
      _totalTaskCount = _tasksList.length;
      notifyListeners();
      return true;
    } catch (e) {
      print('error in creating task = $e');
      return false;
    }
  }
}

Here is the widget that I want to listen and update:

final int taskCount = Provider.of<TaskDatabase>(context, listen: true).totalTasksCount;
.
.
.
Text(taskCount.toString()),

I added the provider at the top of the widget tree and there are no errors. Only thing happening is not updating the text widget

1 Answers

I created a streamBuilder and grabbed the list I want as a snapshot. Updating the list length using the provider package did not work. You can find in the DB class in the question to find how I created a stream of Tasks. Firest initialize the Database in init method.

late final TaskDatabase _crudStorage;

  @override
  void initState() {
    _crudStorage = TaskDatabase();
    _crudStorage.open();
    super.initState();
  }

  @override
  void dispose() {
    _crudStorage.close();
    super.dispose();
  }

....

return Scaffold(
      resizeToAvoidBottomInset: false,
      drawer: const CustomDrawer(),
      body: StreamBuilder(
        stream: _crudStorage.all(),
        builder: (context, snapshot) {
          switch (snapshot.connectionState) {
            case ConnectionState.active:
            case ConnectionState.waiting:
              if (snapshot.data == null) {
                return const Center(child: Shimmer());
              }
              final tasksList = snapshot.data as List<Task>; /// The List I want
            .
            .
            .
            .
            .
            .
  SomeTextWidget('The length of tasks = ${tasksList.length}'),
Related