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 pubspec.yaml.
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
// event.dart
abstract class PostEvent {}
class FetchPost extends PostEvent {}
// state.dart
abstract class PostState {}
class PostInitial extends PostState {}
class PostLoading extends PostState {}
class PostLoaded extends PostState {
final String title;
PostLoaded(this.title);
}
class PostError extends PostState {}
// bloc.dart
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:http/http.dart' 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
http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts/1'));
Integrating GET API with Bloc in Flutter
if (response.statusCode == 200) {
final data = json.decode(response.body);
emit(PostLoaded(data['title']));
} else {
emit(PostError());
}
} catch (_) {
emit(PostError());
}
});
}
}
// main_widget.dart
import 'package:flutter/material.dart';
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(state.title, style: TextStyle(fontSize: 18)));
} else if (state is PostError) {
return Center(child: Text('Failed to fetch data'));
}
return Container();
},
),
),
);
}
}