usage about flutter MultiProvider

Viewed 75
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

void main() {
  runApp(App());
}

class Model extends ChangeNotifier {
  String id;

  Model({this.id});
}

class App extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    var model1 = Model(id: '111');
    var model2 = Model(id: '222');
    var model3 = Model(id: '333');

    return MaterialApp(
        home: Scaffold(
      backgroundColor: Colors.white,
      body: MultiProvider(
        providers: [
          ChangeNotifierProvider.value(value: model1),
          ChangeNotifierProvider.value(value: model2),
          ChangeNotifierProvider.value(value: model3),
        ],
        child: Center(child: Foo()),
      ),
    ));
  }
}

class Foo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Consumer(
      builder: (ctx, Model model, child) {
        return Text(model.id);
      },
    );
  }
}

The result on the screen is 333, how do i get the second model if i want to display 222? are there any way to achieve this such as through index?


The real problem in my project is: I have a page which is composed by a list of components, such as banner, carousel, audio player, etc. The order and amount of them are arbitrary, configured by a json like:

{
  "settings": [
    {
      "type": "ComponentA",
      "data": "..."
    },
    {
      "type": "ComponentB",
      "data": "..."
    },
    {
      "type": "ComponentA",
      "data": "..."
    }
  ]
}

What i do is traverse the json and then create whole models. ComponentAModel, ComponentBModel, ComponentAModel. Then i put all of then into multi provider

now i have two ComponentA to render, but i can not distinguish the first ComponentAModel and the
second ComponentAModel.

1 Answers

You can't use Providers to provide multiple models of the same type.

Try riverpod instead.

Related