session-9
session-9
• Components of MVVM:
o Model: Represents the data layer (business logic, local database interaction, etc.).
o ViewModel: Acts as a mediator between the Model and the View, contains UI-
related logic, and provides data to the View.
o Represents your data layer. You could use plain Dart classes to simulate the model
without APIs.
import 'package:get/get.dart';
class User {
final RxString name, age;
}
View:
• The UI layer, where widgets are built based on data provided by the ViewModel.
ViewModel:
• It retrieves/manipulates data from the Model and provides that data to the View for
rendering.
• In Flutter, we usually use GetxController to make ViewModels reactive and notify the UI of
any data changes.
• Step-by-Step Implementation:
▪ Create a model class representing the data. For simplicity, we’ll use a local
User model.
import 'package:get/get.dart';
class User {
final RxString name, age;
}
Set up the ViewModel:
• Use GetXController or Provider to manage state changes and notify the View of any
updates.
• The View listens to the ViewModel using ChangeNotifierProvider and displays the data.
import 'package:demo_app/view%20models/user_viewmodel.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '';
@override
Widget build(BuildContext context) {
import 'package:demo_app/screens/getx_example.dart';
import 'package:demo_app/screens/home.dart';
import 'package:demo_app/view/user_info.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
void main() {
runApp(const MyApp());
}
@override
Widget build(BuildContext context) {
return const GetMaterialApp(
debugShowCheckedModeBanner: false,
home: UserInfo());
}
}
• Challenges:
5. Practical Exercise
• Exercise: Create a simple Flutter app that allows users to enter their name and age, and
then display that information in the View using MVVM architecture. Students should: