Sure, here is a simple example of how you might structure a Flutter app using the Model-View-ViewModel (MVVM) architecture. MVVM separates your user interface code (View) from your business logic (ViewModel) and data (Model), making your app easier to test and maintain.
We will make a simple counter app for this example:
- Model:
class Counter {
int value = 0;
}
- ViewModel:
class CounterViewModel {
final Counter counter;
CounterViewModel(this.counter);
String get counterValue => 'Current count: ${counter.value}';
void incrementCounter() {
counter.value++;
}
}
- View:
class CounterView extends StatelessWidget {
final CounterViewModel viewModel;
CounterView({Key key, this.viewModel}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('MVVM Counter App'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(viewModel.counterValue),
RaisedButton(
child: Text('Increment'),
onPressed: viewModel.incrementCounter,
),
],
),
),
);
}
}
- Main:
void main() {
final counter = Counter();
final viewModel = CounterViewModel(counter);
runApp(MyApp(viewModel: viewModel));
}
class MyApp extends StatelessWidget {
final CounterViewModel viewModel;
MyApp({Key key, this.viewModel}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'MVVM Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: CounterView(viewModel: viewModel),
);
}
}
Remember that Flutter doesn't support MVVM natively, so for complex applications, you might want to consider using a state management library like Provider or Riverpod, which can handle the ViewModel part for you.