Second GET API Calling with Bloc simple Example in Flutter
import "package:api_with_bloc/Fourth_Get_API_call_using_Bloc/bloc/users_bloc.dart";
import "package:api_with_bloc/Fourth_Get_API_call_using_Bloc/bloc/users_bloc_states.dart";
import "package:flutter/material.dart";
import "package:flutter_bloc/flutter_bloc.dart";
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return BlocProvider<UsersBloc>(
create: (context) => UsersBloc(),
child: MaterialApp(
title: "HomePage",
debugShowCheckedModeBanner: false,
theme: ThemeData(
appBarTheme: const AppBarTheme(
backgroundColor: Colors.grey,
centerTitle: true,
),
),
home: const HomePageFourth(),
),
);
}
}
class HomePageFourth extends StatelessWidget {
const HomePageFourth({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text(
"Bloc Example",
style: TextStyle(fontWeight: FontWeight.bold),
),
centerTitle: true,
),
body: BlocBuilder<UsersBloc, BlocUserState>(
builder: (context, state) {
if (state is BlocUserLoadingState) {
return const Center(
child: CircularProgressIndicator(),
);
} else if (state is BlocUserLoadedState) {
return ListView.builder(
shrinkWrap: true,
itemCount: state.users.length,
itemBuilder: (context, index) {
return Card(
child: ListTile(
leading: CircleAvatar(
child: Text(
state.users[index].id.toString(),
style: const TextStyle(
fontWeight: FontWeight.bold, fontSize: 20.0),
),
),
title: Text(
state.users[index].name,
style: const TextStyle(
fontWeight: FontWeight.bold, fontSize: 20.0),
),
subtitle: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
state.users[index].username,
style: const TextStyle(fontWeight: FontWeight.bold),
),
Text(state.users[index].address.street),
Text(state.users[index].address.zipcode),
Text(state.users[index].email),
],
),
),
);
},
);
} else {
return const Center(
child: Text(
"Something went wrong",
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 20.0),
),
);
}
},
),
);
}
}
// To parse this JSON data, do
//
// final usersModel = usersModelFromJson(jsonString);
import 'dart:convert';
List<UsersModel> usersModelFromJson(String str) =>
List<UsersModel>.from(json.decode(str).map((x) => UsersModel.fromJson(x)));
String usersModelToJson(List<UsersModel> data) =>
json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class UsersModel {
int id;
String name;
String username;
String email;
Address address;
String phone;
String website;
Company company;
UsersModel({
required this.id,
required this.name,
required this.username,
required this.email,
required this.address,
required this.phone,
required this.website,
required this.company,
});
factory UsersModel.fromJson(Map<String, dynamic> json) => UsersModel(
id: json["id"],
name: json["name"],
username: json["username"],
email: json["email"],
address: Address.fromJson(json["address"]),
phone: json["phone"],
website: json["website"],
company: Company.fromJson(json["company"]),
);
Map<String, dynamic> toJson() => {
"id": id,
"name": name,
"username": username,
"email": email,
"address": address.toJson(),
"phone": phone,
"website": website,
"company": company.toJson(),
};
}
class Address {
String street;
String suite;
String city;
String zipcode;
Geo geo;
Address({
required this.street,
required this.suite,
required this.city,
required this.zipcode,
required this.geo,
});
factory Address.fromJson(Map<String, dynamic> json) => Address(
street: json["street"],
suite: json["suite"],
city: json["city"],
zipcode: json["zipcode"],
geo: Geo.fromJson(json["geo"]),
);
Map<String, dynamic> toJson() => {
"street": street,
"suite": suite,
"city": city,
"zipcode": zipcode,
"geo": geo.toJson(),
};
}
class Geo {
String lat;
String lng;
Geo({
required this.lat,
required this.lng,
});
factory Geo.fromJson(Map<String, dynamic> json) => Geo(
lat: json["lat"],
lng: json["lng"],
);
Map<String, dynamic> toJson() => {
"lat": lat,
"lng": lng,
};
}
class Company {
String name;
String catchPhrase;
String bs;
Company({
required this.name,
required this.catchPhrase,
required this.bs,
});
factory Company.fromJson(Map<String, dynamic> json) => Company(
name: json["name"],
catchPhrase: json["catchPhrase"],
bs: json["bs"],
);
Map<String, dynamic> toJson() => {
"name": name,
"catchPhrase": catchPhrase,
"bs": bs,
};
}
import 'package:api_with_bloc/Fourth_Get_API_call_using_Bloc/models/users_model.dart';
abstract class BlocUserState {}
class BlocUserLoadingState extends BlocUserState {}
class BlocUserLoadedState extends BlocUserState {
List<UsersModel> users;
BlocUserLoadedState({required this.users});
}
abstract class BlocUserEvent {}
class BlocUsersInitialEvent extends BlocUserEvent {}
class BlocUsersGetUsersEvent extends BlocUserEvent {}
import 'package:api_with_bloc/Fourth_Get_API_call_using_Bloc/bloc/users_bloc_events.dart';
import 'package:api_with_bloc/Fourth_Get_API_call_using_Bloc/bloc/users_bloc_states.dart';
import 'package:api_with_bloc/Fourth_Get_API_call_using_Bloc/models/users_model.dart';
import 'package:api_with_bloc/Fourth_Get_API_call_using_Bloc/repositories/users_repo.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
class UsersBloc extends Bloc<BlocUserEvent, BlocUserState> {
final UsersRepoFourth usersRepo = UsersRepoFourth();
UsersBloc() : super(BlocUserLoadingState()) {
on<BlocUsersInitialEvent>((event, emit) async {
List<UsersModel> users = await usersRepo.getUsers();
emit(
BlocUserLoadedState(users: users),
);
});
add(BlocUsersInitialEvent());
}
}
import 'package:api_with_bloc/Fourth_Get_API_call_using_Bloc/models/users_model.dart';
import "package:http/http.dart" as http;
import "package:http/http.dart";
class UsersRepoFourth {
static const usersUrl = "https://jsonplaceholder.typicode.com/users";
Future<List<UsersModel>> getUsers() async {
Response response = await http.get(
Uri.parse(usersUrl),
);
return usersModelFromJson(response.body);
}
}
Comments
Post a Comment