Implement API using Bloc Pattern in Flutter
Step 1: Add Dependencies:
=> flutter_bloc: ^8.1.1=> equatable: ^2.0.5
Step 2: Create a Folder and File
=> Create a Folder API Bloc
=> Create a Folder API Bloc
=> In the API Bloc Folder, Create a Dart File,
- exampleAPIProvider.dart
- exampleRepository. dart
- exampleEvent. dart
- exampleState. dart
- exampleBloc. dart
1 => exampleAPIProvider.
import 'dart:convert';
import 'package:http/http.dart' as http;
class ExampleApiProvider {
Future<ExampleModel> fetchData({Id}) async {
var url = Apis.getExampleAPIURL;
var data = {"Id": 0};
var jsonData = json.encode(data); // Encode map data
http.Response res = await http.post(Uri.parse(url),
headers: {
'Content-Type': 'application/json',
},
body: jsonData);
try {
Map<String, dynamic> parsor = jsonDecode(res.body.toString());
return ExampleModel.fromJson(parsor);
} catch (error, stacktrace) {
Map<String, dynamic> parsor = jsonDecode(res.body.toString());
print(error);
return ExampleModel.fromJson(parsor);
}
}
}
2 => exampleRepository. dart
import 'package:.../exampleAPIProvider.dart';
import 'package:.../model.dart';
class ExampleApiRepository {
final _provider = ExampleApiProvider();
Future<ExampleModel> getData({Id}) {
return _provider.fetchData(Id:Id);
}
}
class NetworkError extends Error {}
3=> exampleEvent. dart
import 'package:flutter/material.dart';
@immutable
abstract class ExampleEvent {}
class GetExampleDataList extends ExampleEvent {
String Id;
GetExampleDataList({required this.Id});
}
class SearchDataList extends ExampleEvent{
String searchText;
SearchDataList({required this.searchText});
}
4=> exampleState. dart
import 'package:equatable/equatable.dart';5=> exampleBloc. dart
import 'package:.../model.dart';
abstract class ExampleState extends Equatable{
const ExampleState ();
@override
List<Object?> get props=>[];
}
class ExampleDataInitial extends ExampleState {}
class ExampleDataLoading extends ExampleState {}
class ExampleDataLoaded extends ExampleState{
List<ExampleData>? exampleListModel;
ExampleDataLoaded(this.exampleListModel);
}
class ExampleDataError extends ExampleState{
final String msg;
ExampleDataError(this.msg);
}
import 'package:flutter_bloc/flutter_bloc.dart';// Write Code On View Screen Page
import 'package:.../exampleEvent.dart';
import 'package:.../exampleRepository.dart';
import 'package:.../exampleState.dart';
import 'package:.../exampleModel.dart';
class ExampleBloc extends Bloc<ExampleEvent,ExampleState>{
ExampleBloc():super(ExampleDataInitial()){
final ExampleApiRepository exampleApiRepository= ExampleApiRepository();
List<ExampleModel>? exampleModel;
List<ExampleData>? exampleData;
on<GetExampleDataList>((event,state) async{
try{
emit(ExampleDataLoading());
final mList = await exampleApiRepository.getData(Id:event.Id);
exampleData?.clear();
exampleData=[];
exampleData= mList.exampleData;
emit(ExampleDataLoaded(exampleData));
if(mList.Status !=1){
emit(ExampleDataError("Some thing went wrong, please try again"));
}
}
on NetworkError{
emit(ExampleDataError("Some thing went wrong, please try again or please contact with IT team"));
}
});
on<SearchExampleDataList>((event,state) async{
try{
emit(ExampleDataLoading());
print("search CM:***");
final mList = await capacityData!.where((d) => d.ItemName.toString().toUpperCase().toString()==event.searchText.toUpperCase().toString() || d.CapacityName.toString().toUpperCase().toString()==event.searchText.toUpperCase().toString() || d.CreatedOn.toString().toUpperCase().toString()==event.searchText.toUpperCase().toString() || d.IsActive.toString().toUpperCase().toString()==event.searchText.toUpperCase().toString() ||d.Size.toString().replaceAll(".0", "").toUpperCase().toString()==event.searchText.toUpperCase().toString() || d.CreatedBy.toUpperCase().toString()==event.searchText.toUpperCase().toString()).toList();
print("search CM:$mList");
emit(ExampleDataLoaded(mList));
if(mList.isEmpty){
emit(ExampleDataError("Some thing went wrong, please try again"));
}
}
on NetworkError{
emit(ExampleDataError("Some thing went wrong, please try again or please contact with IT team"));
}
});
}
}
//bloc
ExampleBloc exampleBloc = ExampleBloc();
getDatafromServer() async{
exampleBloc.add(GetExampleDataList(Id:1));
}
@override
void initState() {
getDatafromServer();
super.initState();
}
// Build widgets.....
@override
Widget build(BuildContext context) {
fontSizes(context);
return WillPopScope(
onWillPop: () async=> await Navigator.pushAndRemoveUntil(context,
MaterialPageRoute(builder: (context)=>MainHomeScreen(menuIndex:2,)),
(route) => false),
// Wrape MultiBlocProvider Widget on Widgetc for use multiple bloc
child: MultiBlocProvider(
providers: [
BlocProvider(create: (_) => exampleBloc),
],
child: Scaffold(
appBar: AppBar(
leading: InkWell(
onTap: () {
Navigator.pushAndRemoveUntil(context,MaterialPageRoute(builder: (context)
=>MainHomeScreen(menuIndex:2,)), (route) => false);
},
child: Icon(
Icons.arrow_back_ios,
size: 3.h,
)),
elevation:0,
backgroundColor: kBackgroundColor,
centerTitle:true,
title: Column(
children: [
SizedBox(
width: MediaQuery.of(context).size.width*0.7,
child: Center(
child: MarqueeWidget(
direction: Axis.horizontal,
child: Text("${companyName}",style: GoogleFonts.raleway(
fontWeight: FontWeight.w800,
fontSize: fontSizes.subtitle,
height: 1.0,
letterSpacing: .5,
color: whiteColor,
)),
),
),
),
Text('$Title', style: GoogleFonts.raleway(
fontWeight: FontWeight.w600,
fontSize: fontSizes.title,
height: 1.2,
letterSpacing: .5,
color: whiteColor,
),),
],
),
actions: [],
),
body: // Wrape Bloc Builder Widget on Widget
BlocBuilder<ExampleBloc, ExampleState>(
builder: (context, state) {
if (state is ExampleDataLoading) {
return Container(
decoration: containerDecorationHome1,
height:3.h,
width:50.w,
child:Center(
child: Text("Available : 0",style: GoogleFonts.poppins(
fontWeight: FontWeight.w800,
fontSize: fontSizes.sub2title,
height: 1.2,
letterSpacing: .5,
color: blackColor,
)),
)
);
} else if (state is ExampleDataLoaded) {
exampleModel!=state.exampleListModel!;
if(state.exampleListModel!.isNotEmpty){
return
Container(
decoration: containerDecorationHome1,
height:3.h,
width:50.w,
child:Center(
child: Text("Available : ${state.exampleListModel!.length}",
style: GoogleFonts.poppins(
fontWeight: FontWeight.w800,
fontSize: fontSizes.sub2title,
height: 1.2,
letterSpacing: .5,
color: kBackgroundColor,
)),
)
);
}
else{
return Container(
decoration: containerDecorationHome1,
height:3.h,
width:50.w,
child:Center(
child: Text("Available : 0",style: GoogleFonts.poppins(
fontWeight: FontWeight.w800,
fontSize: fontSizes.sub2title,
height: 1.2,
letterSpacing: .5,
color: blackColor,
)),
)
);
}
} else if (state is ExampleDataError) {
return Container(
decoration: containerDecorationHome1,
height:3.h,
width:50.w,
child:Center(
child: Text("Available : 0",style: GoogleFonts.poppins(
fontWeight: FontWeight.w800,
fontSize: fontSizes.sub2title,
height: 1.2,
letterSpacing: .5,
color: blackColor,
)),
)
);
} else {
return Container();
}
},
),
),
),
);
}
// End.............
Thanks for reading the article ...
Comments
Post a Comment