Skip to content

ViewModel: Function fields vs function literals? #214

Description

@hacker1024

In many examples (including the TODO architecture sample), ViewModels are created like so:

class ViewModel {
  final void Function() myFunction;
  final String myProperty;

  ViewModel({
    required this.myFunction,
    required this.myProperty,
  });

  factory ViewModel.fromStore(Store<AppState> store) {
    return ViewModel(
      myFunction: () => store.dispatch(const MyFunctionAction()),
      myProperty: store.state.myProperty,
    );
  }
}

This (IMO) has the following problems

  • myFunction may be accidentally used in a == or hashCode implementation, which would be incorrect as the closure would be non-identical with every new ViewModel
  • More RAM usage (maybe?)

Why is that the recommended approach, compared to something like this?

class ViewModel {
  final Store<AppState> _store;

  ViewModel(this._store) : myProperty = _store.state.myProperty;

  final String myProperty;

  void myFunction() => _store.dispatch(const MyFunctionAction());
}

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions