September 13, 2024
Integrating Bloc with MVVM in Flutter
class User {
final String name;
final int age;
User({required this.name, required this.age});
}
import 'package:bloc/bloc.dart';
// Events
abstract class UserEvent {}
class LoadUser extends UserEvent {}
// States
abstract class UserState {}
class UserInitial extends UserState {}
class UserLoaded extends UserState {
final User user;
UserLoaded(this.user);
}
// Bloc
class UserBloc extends Bloc<UserEvent, UserState> {
UserBloc() : super(UserInitial()) {
on<LoadUser>((event, emit) {
// Simulate to fetch the user data (from a repository)
final user = User(name: "Teddy Nguyen", age: 44);
//Emit the new event
emit(UserLoaded(user));
});
}
}
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
class UserScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('User')),
body: BlocBuilder<UserBloc, UserState>(
builder: (context, state) {
if (state is UserInitial) {
return Center(child: CircularProgressIndicator());
} else if (state is UserLoaded) {
return Center(child: Text('Name: ${state.user.name}, Age: ${state.user.age}'));
} else {
return Center(child: Text('Something went wrong!'));
}
},
),
);
}
}