zero.one
zero.one

Reputation: 1553

How can I dispose ChangeNotifierProvider<T>.value( ) in Flutter

how can I dispose ChangeNotifierProvider.value( ) in Flutter

so there will be no memory leaks

I made the object that is as a value to the ChangeNotifierProvider.value( ) as a singleton cause I need more than page to share their state in one object

Upvotes: 1

Views: 3961

Answers (3)

osaxma
osaxma

Reputation: 2994

The other answers are only correct for ChangeNotifierProvider default constructor but not for ChangeNotifierProvider.value named constructor which is the one in the question.

According to the package author, you are responsible for disposing the object:

ChangeNotifierProvider.value will not dispose the ChangeNotifier

It is your job to do so (with a typical StatefulWidget?), as using the .value constructor, it is impossible for provider to know if the object is no longer used.

From: the following Github Issue Comment: How to dispose a ChangeNotifier which is also provided with a ChangeNotifierProvider.value?

Upvotes: 0

ChangeNotifierProvider automatically calls the dispose() method of the state when it is needed. You need not do anything about that. They talk about this in this video:Pragmatic State Management in Flutter (Google I/O'19)

Upvotes: 3

kaboc
kaboc

Reputation: 844

You need to use the dispose() method of State or the default constructor of ChangeNotifierProvider. The latter automatically disposes of the object created in the create function.

I wonder why you are using ChangeNotifierProvider.value() instead of ChangeNotifierProvider(), but assuming you want to pass the value to a different page, you can combine both as follows.

ChangeNotifierProvider<Foo>(
  create: (context) => Foo(),  // this Foo object is disposed of automatically
)

Somewhere down the tree:

Navigator.of(context).push(
  MaterialPageRoute<void>(
    builder: (context2) => Provider<Foo>.value(
      value: Provider.of<Foo>(context, listen: false),
      child: NextPage(),
    ),
  ),
)

Note: You won't have to do this if you provide the value from above MaterialApp.

Upvotes: 0

Related Questions