I'm seeking some help to overcome some difficulties to understand how to properly use provider
as state management. I have three custom classes StationModel
, SlideModel
and ProductModel
nested inside each other, like a Russian doll. All of them extends ChangeNotifier
and have some getters and setters that helps me to access the class' properties.
class StationModel with ChangeNotifier {
final String? _id;
SlideModel? _slide1;
SlideModel? _slide2;
}
class SlideModel extends ChangeNotifier {
String? _id;
double? _portion;
String? _batch;
String? _type;
ProductModel? _product;
bool? _isOutOfStock;
String? _subSlideId;
double? _subQuantity;
ProductModel? _subProduct;
}
class ProductModel extends ChangeNotifier {
String? _id;
String? _uom;
String? _category;
String? _family;
String? _description;
String? _descriptionShort;
int? _batchManagement;
}
At the beginning of MyApp
tree I instantiated a MultiProvider
with three ChangeNotifierProvider
and one ChangeNotifierProxyProvider2
. From my understanding this should combine the previous notifier inside one.
class MyApp extends StatelessWidget {
const MyApp({super.key});
// Application root
@override
Widget build(BuildContext context) {
return MultiProvider(
providers: [
ChangeNotifierProvider(create: (context) => ProductModel.empty()), // HERE
ChangeNotifierProvider(create: (context) => SlideModel.empty()), // HERE
ChangeNotifierProvider(create: (context) => StationModel.empty()), // HERE
ChangeNotifierProxyProvider2<SlideModel, SlideModel, StationModel>( // HERE
create: (context) => StationModel.empty(),
update: (context, slideA, slideB, station) => StationModel(
id: station?.getId,
slide1: slideA,
slide2: slideB,
),
),
],
child: MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Wenda Warehouse',
theme: CustomTheme.lightTheme,
initialRoute: '/',
routes: {
'/': (context) => PortioningApp(),
'/newSchedule': (context) => SchedulePage(),
},
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
),
);
}
}
Through the app I used Consumer
widgets to access the needed properties and everything seems to work fine. The issue pop-out when I am trying apply some changes to the object instantiated; for example if I am trying to change one of the slide properties _isOutOfStock
the consumer will not reflect the change and the UI doesn't rebuild itself. I hope someone can explain me better hoe to use this feature. Thank you in advance.
I expect to have just one stationModel
reference and being able to retrieve or modify a properties at all three levels (StationModel
-> SlideModel
-> ProductModel
) and to see the UI change accordingly.