DEV Community

Swee Sen
Swee Sen

Posted on

Flutter: Basic MVVM setup with provider

0. Update pubspec.yaml

    sdk: flutter
  provider: ^6.0.0
Enter fullscreen mode Exit fullscreen mode

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) {
Enter fullscreen mode Exit fullscreen mode

2. Create View (Widget), link to ViewModel

class HomePage extends StatelessWidget {
  const HomePage({super.key});

  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: => Text(e)).toList(),
Enter fullscreen mode Exit fullscreen mode
  • Use Consumer<HomePageModel> to access the view model, via the value param
  • 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.
  Widget build(BuildContext context) {
    return MaterialApp(
        title: 'Flutter Demo',
        theme: ThemeData(
        home: ChangeNotifierProvider(
          create: (context) => HomePageModel(),
          child: const HomePage(),
Enter fullscreen mode Exit fullscreen mode
  • Wrap HomePage widget with ChangeNotifierProvider.
  • Inject an instance of HomePageModel as the view model

Latest comments (0)