give me example of MVVM in flutter
- User
give me example of MVVM in flutter
- Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
give me example of MVVM in flutter
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Sure, Model-View-ViewModel (MVVM) is a software architectural pattern that separates the development of graphical user interfaces into three interconnected components: the Model, which represents the data or the business logic; the View, which is the UI; and the ViewModel, which acts as an intermediary between the Model and the View.
Here's a simple example to illustrate MVVM in Flutter:
class User {
String name;
int age;
User(this.name, this.age);
}
import 'package:flutter/foundation.dart';
import 'user.dart';
class UserViewModel with ChangeNotifier {
User _user;
UserViewModel(this._user);
String get userName => _user.name;
int get userAge => _user.age;
void updateUser(String name, int age) {
_user.name = name;
_user.age = age;
notifyListeners();
}
}
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'user.dart';
import 'user_view_model.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
User user = User('John Doe', 30); // Example user data
return MaterialApp(
title: 'MVVM Example',
home: ChangeNotifierProvider(
create: (context) => UserViewModel(user),
child: UserView(),
),
);
}
}
class UserView extends StatelessWidget {
@override
Widget build(BuildContext context) {
UserViewModel viewModel = Provider.of<UserViewModel>(context);
return Scaffold(
appBar: AppBar(
title: Text('MVVM Example'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text('Name: ${viewModel.userName}'),
Text('Age: ${viewModel.userAge}'),
ElevatedButton(
onPressed: () {
viewModel.updateUser('Jane Doe', 25);
},
child: Text('Update User'),
),
],
),
),
);
}
}
In this example, User is the Model containing data, UserViewModel is the ViewModel that provides data to the UI and handles logic for updating the user, and UserView is the View that displays the user's information and contains a button for updating it. Notice how ChangeNotifierProvider from the provider package is used to provide an instance of UserViewModel to the UserView. When the user presses the button, the ViewModel updates the user's information, which causes the UI to rebuild with the new data.
Remember that this is a simplified example, and MVVM can be implemented in many different ways in Flutter, especially when it comes to state management. You might choose different packages or approaches depending on the complexity of your application and your team's preferences.