0. Update pubspec.yaml
dependencies:
  flutter:
    sdk: flutter
  provider: ^6.0.0
1.Create ViewModel
Create a new class that extends ChangeNotifier
class HomePageModel extends ChangeNotifier {
  // we make _items private, modification should only be done through
  // `addItem` function
  final List<String> _items = [];
  // get method to for public to access _items;
  List<String> get items => _items;
  void addItem(String item) {
    _items.add(item);
    notifyListeners();
  }
}
2. Create View (Widget), link to ViewModel
class HomePage extends StatelessWidget {
  const HomePage({super.key});
  @override
  Widget build(BuildContext context) {
    return Consumer<HomePageModel>(
      builder: (context, value, child) => Scaffold(
        floatingActionButton: FloatingActionButton(
          onPressed: (() {
            value.addItem("new item");
          }),
          child: const Text("+"),
        ),
        body: ListView(
          children: value.items.map((e) => Text(e)).toList(),
        ),
      ),
    );
  }
}
- Use Consumer<HomePageModel>to access the view model, via thevalueparam
- Access list of items through value.items
- Add item to list through value.addItem
  
  
  3. Wrap the widget with ChangeNotifierProvider
class MyApp extends StatelessWidget {
  const MyApp({super.key});
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        title: 'Flutter Demo',
        theme: ThemeData(
          primarySwatch: Colors.blue,
        ),
        home: ChangeNotifierProvider(
          create: (context) => HomePageModel(),
          child: const HomePage(),
        ));
  }
}
- Wrap HomePagewidget withChangeNotifierProvider.
- Inject an instance of HomePageModelas the view model
 

 
    
Top comments (0)