Here you will learn how to use http bloc example
The code for main.dart
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
home: RepositoryProvider(
create: (context) => UserRepository(),
child: const Home(),
)
);
}
}
class Home extends StatelessWidget {
const Home({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return BlocProvider(
create: (context) => UserBloc(
RepositoryProvider.of<UserRepository>(context),
)..add(LoadUserEvent()),
child: Scaffold(
appBar: AppBar(
title: const Text('The BLoC App'),
),
body: BlocBuilder<UserBloc, UserState>(
builder: (context, state) {
if (state is UserLoadingState) {
return const Center(
child: CircularProgressIndicator(),
);
}
if(state is UserLoadedState){
List<UserModel> userList = state.users;
return ListView.builder(
itemCount: userList.length,
itemBuilder: (_,index){
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 10),
child: InkWell(
onTap: (){
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => DetailScreen(
e: userList[index],
),
),
);
},
child: Card(
color: Colors.blue,
elevation: 4,
margin: const EdgeInsets.symmetric(vertical: 10),
child: ListTile(
title: Text(userList[index].firstname, style: const TextStyle(
color: Colors.white
),),
subtitle: Text(userList[index].lastname, style: const TextStyle(
color: Colors.white
)),
trailing: CircleAvatar(
backgroundImage: NetworkImage(userList[index].avatar),
),
),
),
),
);
});
}
if(state is UserErrorState){
return Center(child:Text("Error"));
}
return Container();
},
),
),
);
}
}
The code for data_screen.dart
class DetailScreen extends StatelessWidget {
const DetailScreen({Key? key, required this.e}) : super(key: key);
final UserModel e;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body:Center(
child: Padding(
padding: const EdgeInsets.all(20.0),
child: Column(
children: [
Center(
child: CircleAvatar(
maxRadius: 60,
backgroundImage: NetworkImage(e.avatar),
),
),
Text(
e.firstname + " " + e.lastname,
),
Text(e.email),
],
),
),
)
);
}
}
The code for repository.dart
class UserRepository {
String endpoint = 'https://reqres.in/api/users?page=2';
Future<List<UserModel>> getUsers() async {
Response response = await get(Uri.parse(endpoint));
if (response.statusCode == 200){
final List result = jsonDecode(response.body)['data'];
return result.map(((e) => UserModel.fromJson(e))).toList();
}else {
throw Exception(response.reasonPhrase);
}
}
}
The code for app_states.dart
@immutable
abstract class UserState extends Equatable {}
//data loading state
class UserLoadingState extends UserState {
@override
List<Object?> get props => [];
}
class UserLoadedState extends UserState {
UserLoadedState(this.users);
final List<UserModel> users;
@override
List<Object?> get props => [users];
}
class UserErrorState extends UserState {
UserErrorState(this.error);
final String error;
@override
List<Object?> get props => [error];
}
The code for app_events.dart
@immutable
abstract class UserEvent extends Equatable {
const UserEvent();
}
class LoadUserEvent extends UserEvent {
@override
List<Object> get props => [];
}
The code for app_blocs.dart
class UserBloc extends Bloc<UserEvent, UserState> {
final UserRepository _userRepository;
UserBloc(this._userRepository) : super(UserLoadingState()) {
on<LoadUserEvent>((event, emit) async {
emit(UserLoadingState());
try {
final users = await _userRepository.getUsers();
emit(UserLoadedState(users));
} catch (e) {
emit(UserErrorState(e.toString()));
}
});
}
}
The code for user_model.dart
class UserModel {
final int id;
final String email;
final String firstname;
final String lastname;
final String avatar;
UserModel(
{required this.id,
required this.email,
required this.firstname,
required this.lastname,
required this.avatar});
factory UserModel.fromJson(Map<String, dynamic> json) {
return UserModel(
id: json['id'],
email: json['email'],
firstname: json['first_name'] ?? 'First Name',
lastname: json['last_name'] ?? 'Last Name',
avatar: json['avatar'] ??
'https://img.freepik.com/free-vector/illustration-user-avatar-icon_53876-5907.jpg?w=740');
}
}
Hello, I’ve followed your tutorial -> https://www.youtube.com/watch?v=CjCTNPKhgXc
Could you help me fix my code here, please? https://github.com/dimaspsetyo/accurate
When I ‘flutter run’ it only goes to Error State.
You could access the API on the repositories.dart files
Your error report is not clear. Your github link is not working