Implement Rest API using BLoC Pattern in Flutter
Implementing a REST API in Flutter using the BLoC (Business Logic Component) pattern typically involves the following steps:Step 1:- Create the BLoC:
Define a class for your BLoC, which will contain the business logic for managing the state of your data.
Use the flutter_bloc package to create a BLoC. You can add this package to your pubspec.yaml file:
dependencies:
flutter_bloc: ^7.0.0
- Run flutter pub get to fetch the package.
- Create a BLoC class.
- Here's a simple example:
import 'package:bloc/bloc.dart';
// Define events
enum MyEvent { fetchData }
// Define states
abstract class MyState {}
class InitialState extends MyState {}
class LoadedState extends MyState {
final List<String> data;
LoadedState(this.data);
}
class ErrorState extends MyState {
final String error;
ErrorState(this.error);
}
// Define the BLoC
class MyBloc extends Bloc<MyEvent, MyState> {
MyBloc() : super(InitialState());
@override
Stream<MyState> mapEventToState(MyEvent event) async* {
try {
if (event == MyEvent.fetchData) {
// Fetch data from the API here
List<String> data = await fetchDataFromApi();
yield LoadedState(data);
}
} catch (e) {
yield ErrorState('Error fetching data: $e');
}
}
Future<List<String>> fetchDataFromApi() async {
// Implement your API call logic here
// Use packages like http or dio to make HTTP requests
// Return the data obtained from the API
return ['Data1', 'Data2', 'Data3'];
}
}
Step 2: Create a Repository:
Create a separate class to handle the communication with your REST API. This class is commonly referred to as a repository.
Create a separate class to handle the communication with your REST API. This class is commonly referred to as a repository.
class MyRepository {
Future<List<String>> fetchData() async {
// Implement your API call logic here
// Use packages like http or dio to make HTTP requests
// Return the data obtained from the API
return ['Data1', 'Data2', 'Data3'];
}
}
Step 3: Create a UI Component:
Create a widget that will interact with your BLoC and display the data.
Create a widget that will interact with your BLoC and display the data.
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: BlocProvider(
create: (context) => MyBloc(),
child: MyWidget(),
),
);
}
}
class MyWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Flutter BLoC API Example'),
),
body: BlocBuilder<MyBloc, MyState>(
builder: (context, state) {
if (state is InitialState) {
return Center(
child: ElevatedButton(
onPressed: () {
context.read<MyBloc>().add(MyEvent.fetchData);
},
child: Text('Fetch Data'),
),
);
} else if (state is LoadedState) {
return ListView.builder(
itemCount: state.data.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(state.data[index]),
);
},
);
} else if (state is ErrorState) {
return Center(
child: Text('Error: ${state.error}'),
);
} else {
return Container();
}
},
),
);
}
}
Step 4: Make API Requests:
Use a package like http or dio to make HTTP requests in the fetchDataFromApi method of your BLoC or in the repository.
For example, using the http package:
For example, using the http package:
import 'package:http/http.dart' as http;
class MyRepository {
Future<List<String>> fetchData() async {
final response = await http.get('https://api.example.com/data');
if (response.statusCode == 200) {
// Parse the response and return data
// For simplicity, assuming the API returns a JSON array of strings
final List<dynamic> jsonData = json.decode(response.body);
return jsonData.cast<String>().toList();
} else {
throw Exception('Failed to fetch data');
}
}
}
Thanks for reading the article ...
Comments
Post a Comment