Binding object and widget together in Flutter using Provider package

Viewed 743

Imagine in the TodoScreen of the application, I have a TodoObjectList (list of todos obtained from some API) and I want to show them inside a list. So I created a list of TodoWidgets (StatelessWidget), each one having its own TodoObject as its property. Now I want TodoWidgets to be bound with its TodoObject, so I used the Provider package. The code is something like below (inside TodoScreen):

SliverList(
  delegate: SliverChildBuilderDelegate(
    (BuildContext context, int index) {
      return ChangeNotifierProvider<TodoObject>(
              builder: (_) => TodoObjectList[index],
              child: Consumer<TodoObject>(
                builder: (context, TodoObject, child) => TodoWidget(todo: TodoObject)
              ),
            );
    },
    childCount: TodoObjectList.length,
  ),
)

This code works fine for the first time. But when I go back and navigate to TodoScreen for the second time (I won’t call the API again, TodoObjectList is already cached), Provider throws an error:

 “A TodoObject was used after being disposed.”

I Know why this error is being thrown, but my question is how should I bind TodoWidget with TodoObject using provider, without facing this error when I have the API data stored somewhere.

1 Answers

You should use ChangeNotifierProvider.value instead. This link would probably help you if you had any follow up questions.

Related