MVVM Design Pattern in Flutter

后端 未结 4 1014
时光说笑
时光说笑 2021-02-06 05:26

we try to develop a flutter app and we create a stateful widget as a page .
we want to separate build function from other state variable and state function in 2 different fi

4条回答
  •  天涯浪人
    2021-02-06 06:07

    I suggest moving your ViewModel code into a separate class that does not extend State. Keep the ViewModel platform independent. Your Widgets state can have an instance of the viewModel and interact with it.

    You can find a more detailed example here

    If child Widgets need to access your ViewModel you can use a Inherited Widget as suggested by @Rémi Rousselet. I quickly implemented this for you:

    class ViewModelProvider extends InheritedWidget {
      final ViewModel viewModel;
    
      ViewModelProvider({Key key, @required this.viewModel, Widget child}) 
      : super(key: key, child: child);
    
      @override
      bool updateShouldNotify(InheritedWidget oldWidget) => true;
    
      static ViewModel of(BuildContext context) =>
          (context.inheritFromWidgetOfExactType(ViewModelProvider) as 
      ViewModelProvider).viewModel;
    }
    

    Child widgets can grab the ViewModel by calling

    var viewModel = ViewModelProvider.of(context);
    

    Let me know if you have any questions :)

提交回复
热议问题