Scoping Lifecycle of ChangeNotifier to just a specific number of screens - flutter

I have a ChangeNotifier Subclass that I am sharing between a number of screens like this:
final value = MyChangeNotifier();
MaterialApp(
routes: {
'/list': (_) => ChangeNotifierProvider.value(value: value, child: ListScreen()),
'/detials': (_) => ChangeNotifierProvider.value(value: value, child: DetailsScreen()),
'/other_screen': (_) => OtherScreen(),
}
)
I want to dispose my ChangeNotifier once the user has left the last screen in this flow, and I want to create a new Instance of the shared ChangeNotifier once user re-enters the given flow.
Is it possible to do with Provider?

Related

Flutter bloc Cubit Bad state: Cannot emit new states after calling close

I have an app that I build using Cubit
I have two pages A and B.every thing works fine on its own. I use a change status cubit on both pages but when I move to the second page and pop to return to the first page I see the error on the title.
I inject dependencies using get it
route A
routes: {
'/home': (context) => MultiBlocProvider(providers: [
BlocProvider<ChangeStatusCubit>(
create: (context) => locator<ChangeStatusCubit>(),
),
], child: const TodoHomePage()),
Route B
'/details': (context) => MultiBlocProvider(
providers: [
BlocProvider<ChangeStatusCubit>(
create: (context) => locator<ChangeStatusCubit>(),
),
],
child: TodoDetailsPage(),
dependency injection
locator.registerLazySingleton<ChangeStatusCubit>(() => ChangeStatusCubit(
locator(),
));
cubit
changeStatus(int id) async {
emit(ChangeStatusLoading());
try {
ResponseModel response = await _changeStatusUseCase(id);
if (response.status == 200) {
emit(ChangeStatusLoaded(response.data));
} else {
emit(ChangeStatusError(response.error?.todo?.first ?? ""));
}
} catch (e) {
emit(ChangeStatusError(e.toString()));
}
}
When you use create to initialize the BlocProvider's bloc, the bloc's stream will be closed when that BlocProvider is unmounted.
To solve this, you can either move your BlocProvider higher up in the widget tree, so that it will remain mounted between pages, or you can use the BlocProvider.value constructor.
The latter is probably best, since you aren't actually creating a bloc, but making use of a pre-existing singleton. Though it would also make sense to move the widget higher up, so that it's a parent of the Navigator - that way you can declare it just once and reduce code duplication.
However, keeping the structure in your example, your code might look something like this:
routes: {
'/home': (context) => MultiBlocProvider(
providers: [
BlocProvider.value<ChangeStatusCubit>(
value: locator<ChangeStatusCubit>(),
),
],
child: const TodoHomePage(),
),
'/details': (context) => MultiBlocProvider(
providers: [
BlocProvider<ChangeStatusCubit>.value(
value: locator<ChangeStatusCubit>(),
),
],
child: TodoDetailsPage(),
),
}

how do i use provider in this situation

I want to create a change app theme mode and I saw a way of creating it with Provider but I'm new to Provider. For Example, I want to add some codes like this
(the highlighted code)
in my main which consists of many routes
You want to change the theme of the app, then you need to move provider up so it can cover the widget (App in this case) state,
You could do something like this in your main method :
runApp(ChangeNotifierProvider(
create: (context) => ThemeProvider(),
child:MyApp()
);
now in the case of children you could simply call provider in the build method like this
Widget build(){
var themeProvider = Provider.of<ThemeProvider>(context);
}
or you could use the consumer widget
Consumer<ThemeProvider>(
builder: (context, provider, child) {
//return something
}
)
I suggest you to move your ChangeNotifierProvider to your runApp() method
runApp(
ChangeNotifierProvider<ThemeProvider>(
create: (_) => ThemeProvider(),
child: MyApp(),
),
),
Where your MyApp() is just all of your app extracted to its own widget.
Then you can actually easily access it as you wish with a Consumer widget on your build method.
return Consumer<ThemeProvider>(
builder: (BuildContext context, ThemeProvider provider, _) {
return MaterialApp(
theme: provider.myTheme,
...
);
}
)

Flutter Provider on Navigator inject multiple objects

New to Flutter, I have Provider on top of my app with the class Events. Is there any way to inject more than one object in Navigator builder like MapBox(events.itmaps, events.maps) for example?
class Events {
final String site, fb, itmaps, maps;
Events({this.site, this.fb, this.itmaps, this.maps});
}
void main() {
final events = Events();
runApp(
Provider<Events>.value(
value: events,
child: MyApp(),
),
);
}
onPressed: () {
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => MapBox(events.itmaps),
),
);
}
As I understood you have some conceptual misunderstandings!. I'll describe two scenarios, hopefully one of them will fit to your requirement.
Using MultiProvider to inject many Dependencies(Classes/Objects/Stores)
As https://pub.dev/packages/provider described it would be like this:
MultiProvider(
providers: [
Provider<Something>(create: (_) => Something()),
Provider<SomethingElse>(create: (_) => SomethingElse()),
Provider<AnotherThing>(create: (_) => AnotherThing()),
],
child: someWidget,
)
Passing arguments/props to Widgets
Despite the descriptions and keywords you used, by looking at your code I can guess you want to pass a second or more input/arguments/props to your screen widget. Every widget input is a class constructor argument. So you need just declare the desire parameters in the constructor of your MapBox class.
class MapBox extends StatelessWidget {
EventModel firstInput;
OtherEventModel secondInput;
MapBox(this.firstInput, this.secondInput);
.
.
.
}

How to consume Provider after navigating to another route?

My app have 2 type of user: admin and normal. I show admin screen to admin and normal screen to normal user. All user need access Provider model1. But only admin need access model2.
How I can initialise only model2 for admin user?
For example:
class MyApp extends StatelessWidget {
final model1 = Model1();
final model2 = Model2();
#override
Widget build(BuildContext context) {
return MultiProvider(
providers: [
ChangeNotifierProvider(builder: (_) => model1),
ChangeNotifierProvider(builder: (_) => model2),
],
child: MaterialApp(
I want to put model2 only in AdminScreen. But if I do this other admin pages cannot access model2 after Navigator.push because they are not descendant of AdminScreen.
Thanks for help!
You can pass the existing model forward creating a new ChangeNotifierProvider using the value of the existing one.
For that, you need to use ChangeNotifierProvider.value constructor passing the existing model2 as the value.
If you already have an instance of ChangeNotifier and want to expose it, you should use ChangeNotifierProvider.value instead of the default constructor.
MaterialPageRoute(
builder: (context) => ChangeNotifierProvider<Model2>.value(
value: model2,
child: SecondRoute(),
),
);

How to use a provider inside of another provider in Flutter

I want to create an app that has an authentication service with different permissions and functions (e.g. messages) depending on the user role.
So I created one Provider for the user and login management and another one for the messages the user can see.
Now, I want to fetch the messages (once) when the user logs in. In Widgets, I can access the Provider via Provider.of<T>(context) and I guess that's a kind of Singleton. But how can I access it from another class (in this case another Provider)?
From version >=4.0.0, we need to do this a little differently from what #updatestage has answered.
return MultiProvider(
providers: [
ChangeNotifierProvider(builder: (_) => Auth()),
ChangeNotifierProxyProvider<Auth, Messages>(
update: (context, auth, previousMessages) => Messages(auth),
create: (BuildContext context) => Messages(null),
),
],
child: MaterialApp(
...
),
);
Thanks for your answer. In the meanwhile, I solved it with another solution:
In the main.dart file I now use ChangeNotifierProxyProvider instead of ChangeNotifierProvider for the depending provider:
// main.dart
return MultiProvider(
providers: [
ChangeNotifierProvider(builder: (_) => Auth()),
ChangeNotifierProxyProvider<Auth, Messages>(
builder: (context, auth, previousMessages) => Messages(auth),
initialBuilder: (BuildContext context) => Messages(null),
),
],
child: MaterialApp(
...
),
);
Now the Messages provider will be rebuilt when the login state changes and gets passed the Auth Provider:
class Messages extends ChangeNotifier {
final Auth _authProvider;
List<Message> _messages = [];
List<Message> get messages => _messages;
Messages(this._authProvider) {
if (this._authProvider != null) {
if (_authProvider.loggedIn) fetchMessages();
}
}
...
}
Passing another provider in the constructor of the ChangeNotifierProxyProvider may cause you losing the state, in that case you should try the following.
ChangeNotifierProxyProvider<MyModel, MyChangeNotifier>(
create: (_) => MyChangeNotifier(),
update: (_, myModel, myNotifier) => myNotifier
..update(myModel),
);
class MyChangeNotifier with ChangeNotifier {
MyModel _myModel;
void update(MyModel myModel) {
_myModel = myModel;
}
}
It's simple: the first Provider provides an instance of a class, for example: LoginManager. The other Provides MessageFetcher. In MessageFetcher, whatever method you have, just add the Context parameter to it and call it by providing a fresh context.
Perhaps your code could look something like this:
MessageFetcher messageFetcher = Provider.of<ValueNotifier<MessageFetcher>>(context).value;
String message = await messageFetcher.fetchMessage(context);
And in MessageFetcher you can have:
class MessageFetcher {
Future<String> fetchMessage(BuildContext context) {
LoginManager loginManager = Provider.of<ValueNotifier<LoginManager>>(context).value;
loginManager.ensureLoggedIn();
///...
}
}
Seems like this would be a lot easier with Riverpod, especially the idea of passing a parameter into a .family builder to use the provider class as a cookie cutter for many different versions.