How to provide data with provider using nested data models [List > Item > Sublist > SubItem]

Issue

i started using Provider package for state management, and using it in a basic way.
As the app gets more complex i want to extend the usage.

Now i have this model structure in mind: List<Client> having a List<Product> (and deeper having a List<Component>).

I have a MultiProvider using a ChangeNotifierProvider for the Clients, means the List<Client> is managed by the provider, so far so good.

Now i want to directly use the List<Product> in a provider, or later the List<Component> inside the List<Product>. I do not want to go the way through the List<Client>…down to the Component.

Here i have an image map of the structure to visualize.

Here is some simplified code:

    // Just an example idea of..

Class Product with ChangeNotifier {
  final String title;  
}

Class Client with ChangeNotifier {
  final String name;
  final String List<Product>;
}


Class Clients with ChangeNotifier {
  final List<Client> _items;

}


void main()  { 
    // start the app
  runApp(MyApp());
}
class MyApp extends StatelessWidget {

@override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider(create: (ctx) => Clients()),  

        // How to provide a List<Product> that actually in the model 
        // belongs to a Client in the List<Client>

      ],
      child: MaterialApp(
        body: ...
      )
      );   
  }
}

So the main question is how to provide a List<Product> that actually in the model
belongs to a Client in the List<Client>?

Solution

Thanks for your help in the comments.

There seem to be two possible solutions to it.

  1. Do not use nested structure. This is possible by keeping the id of the parent inside the before nested list and throw it out the of the parent list. Then give it an own ChangeNotifierProvider and filter the items by the parent id when needed.

So in my example List and List are on the same level and both have an
ChangeNotifierProvider. The product model holds the id of it's client and the list has an method getbyClientId(clientId) that results in a filtered productslist to the specified client. That’s it.

  1. Use ChangeNotifierProxyProvider to delegate the request into the nested list.

I have chosen the first way as in my case it seemed the right way. And after working some time now with it i can not say it was a wrong decision, so i have my freedom with it.

Probably for other cases the second approach might be better. I haven’t invested too much time in ChangeNotifierProxyProvider, so please check other sources for more details on that.

Answered By – Antonio Cambule

Answer Checked By – Clifford M. (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *