Develop a powerful Flutter app utilizing BLoC state management and REST APIs to enhance functionality and performance.
Flutter app using the BLoC state management pattern and REST APIs. Before we begin, make sure you have Flutter and Dart installed on your system.
First, let's set up the project and install the necessary packages:
Create a new Flutter project using the Flutter CLI:
flutter create bloc_rest_app Change your current directory to the project directory:
cd bloc_rest_appOpen the pubspec.yaml file and add the required packages under the dependencies section:
dependencies:
flutter:
sdk: flutter
http: ^0.13.4
bloc: ^7.3.0
flutter_bloc: ^7.3.0 Save the file and run the following command to install the packages:flutter pub getNow, let's create the necessary files for the BLoC and REST API implementation: Create a new directory called
blocinside thelibdirectory.Inside the
blocdirectory, create a new file calledpost_bloc.dartwith the following code:
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:bloc_rest_app/models/post.dart';
// Event
abstract class PostEvent {}
class FetchPostsEvent extends PostEvent {}
// State
abstract class PostState {}
class InitialPostState extends PostState {}
class LoadingPostState extends PostState {}
class LoadedPostState extends PostState {
final List<Post> posts;
LoadedPostState(this.posts);
}
class ErrorPostState extends PostState {}
// BLoC
class PostBloc extends Bloc<PostEvent, PostState> {
PostBloc() : super(InitialPostState());
@override
Stream<PostState> mapEventToState(PostEvent event) async* {
if (event is FetchPostsEvent) {
yield LoadingPostState();
try {
final response =
await http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts'));
final List<dynamic> jsonData = jsonDecode(response.body);
final posts = jsonData.map((post) => Post.fromJson(post)).toList();
yield LoadedPostState(posts);
} catch (e) {
yield ErrorPostState();
}
}
}
} Inside the
libdirectory, create another directory calledmodels.Inside the
modelsdirectory, create a new file calledpost.dartwith the following code:class Post { final int id; final String title; final String body; Post({required this.id, required this.title, required this.body}); factory Post.fromJson(Map<String, dynamic> json) { return Post( id: json['id'], title: json['title'], body: json['body'], ); } }Now, let's create the main app file and wire everything together:
- Replace the contents of
lib/main.dartwith the following code:
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'bloc/post_bloc.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'BLoC Rest App',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: BlocProvider(
create: (context) => PostBloc()..add(FetchPostsEvent()),
child: HomePage(),
),
);
}
}
class HomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('BLoC Rest App'),
),
body: BlocBuilder<PostBloc, PostState>(
builder: (context, state) {
if (state is LoadingPostState) {
return Center(
child: CircularProgressIndicator(),
);
} else if (state is LoadedPostState) {
return ListView.builder(
itemCount: state.posts.length,
itemBuilder: (context, index) {
final post = state.posts[index];
return ListTile(
title: Text(post.title),
subtitle: Text(post.body),
);
},
);
} else if (state is ErrorPostState) {
return Center(
child: Text('Error fetching posts!'),
);
} else {
return Container();
}
},
),
);
}
} That's it! You have now created a Flutter app using the BLoC state management pattern and REST APIs. The app fetches posts from the JSONPlaceholder API and displays them in a list view. You can customize and expand upon this code as per your requirements.
Remember to run the app using flutter run command.





