Integrating GET API with Bloc in Flutter
Explanation
In Flutter, integrating a GET API using the Bloc pattern allows for better separation of concerns and
scalability. Instead of managing state with setState, Bloc manages states and events.
Steps:
1. Add flutter_bloc and http to [Link].
2. Create Event, State, and Bloc classes.
3. Use BlocProvider to provide the Bloc to the widget tree.
4. Use BlocBuilder to respond to state changes.
Example Code
// [Link]
abstract class PostEvent {}
class FetchPost extends PostEvent {}
// [Link]
abstract class PostState {}
class PostInitial extends PostState {}
class PostLoading extends PostState {}
class PostLoaded extends PostState {
final String title;
PostLoaded([Link]);
}
class PostError extends PostState {}
// [Link]
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:http/[Link]' as http;
import 'dart:convert';
class PostBloc extends Bloc<PostEvent, PostState> {
PostBloc() : super(PostInitial()) {
on<FetchPost>((event, emit) async {
emit(PostLoading());
try {
final response = await
[Link]([Link]('[Link]
Integrating GET API with Bloc in Flutter
if ([Link] == 200) {
final data = [Link]([Link]);
emit(PostLoaded(data['title']));
} else {
emit(PostError());
}
} catch (_) {
emit(PostError());
}
});
}
}
// main_widget.dart
import 'package:flutter/[Link]';
import 'package:flutter_bloc/flutter_bloc.dart';
class PostPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return BlocProvider(
create: (_) => PostBloc()..add(FetchPost()),
child: Scaffold(
appBar: AppBar(title: Text('GET API with Bloc')),
body: BlocBuilder<PostBloc, PostState>(
builder: (context, state) {
if (state is PostLoading) {
return Center(child: CircularProgressIndicator());
} else if (state is PostLoaded) {
return Center(child: Text([Link], style: TextStyle(fontSize: 18)));
} else if (state is PostError) {
return Center(child: Text('Failed to fetch data'));
}
return Container();
},
),
),
);
}
}