2

How can I use consumer to access data of a ViewModel class from a nested models class?

I know we can use ChangeNotifierProvider and Consumer to access the view Model from a widget. But I'm trying to access the properties from a model class that doesn't have context or build method. Is the only option to pass the ViewModel to each nested class? What if I have multiple levels of nesting? how can I optimize this?

Simplified Model Structure

class TabItemsViewModel{
    bool grouped=false;
    List<ProductItemModel> products = [...];
class ProductItemModel{
    List<ProductItemAddonModel> addons=[...];
class ProductItemAddonModel{
    bool grouped=false;

    int get value{
        // I'm trying access grouped property from TabItemsViewModel;

Simplified Widget Structure

class MyApp extends State<SussaApp> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: ChangeNotifierProvider(
        create: (_) => TabItemsViewModel(),
        child: TabItemsView(),
class TabItemsView extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final vm = Provider.of<TabItemsViewModel>(context);

    return Column(
      children: [
        ListView.builder(
          itemCount: vm.products.length,
          itemBuilder: (BuildContext context, int index) {
            return ProductItem(model: vm.products[index]);

Thanks

Community
  • 1
  • 1
Marteiro
  • 165
  • 1
  • 7

0 Answers0