Search code examples
flutterflutter-animationflutter-provider

Clunky animation with Dismissible and Provider (NotifyListener)


I am trying to fix an issue that occurred when using the Dismissible widget and the Provider package.

When I dismissed a card this is called :

 Provider.of<NMyProvider>(context, listen: false).toggleIsDone(object.id);

The provider :

Future<void> deleteNotebook(int id) async {
    ...
    final notebookId = _items.indexWhere((notebook) => notebook.id == id);
    ...
    _items.removeAt(notebookId);
    notifyListeners();
  }

This makes the animation clunky with noticeable lag but does not occur when removing the NotifyListeners.


Solution

  • Most probably the entire screen is being rebuilt upon notification from the provider. There are some solutions for that:

    1. Move the Consumer<NMyProvider>/context.watch<NMyProvider>(context)/Provider.of<NMyProvider>(context, listen: true) closer to its usage. Flutter only rebuilds the widgets that use the same context;
    2. Use a unique key for every notebook. Not the index position, but a unique key like the notebookId. Flutter will re-use the already built notebook widget where the key is the same in between builds;
    3. Split the NMyProvider: Move everything that doesn't make sense to this provider into other providers. If a lot of unrelated states are together the chance of this provider being used by the root widget gets higher. NMyProvider should deal only with the list of notebooks state;