Skip to main content

How to implement rest API using BLoC Pattern in Flutter

 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.

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.

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();
          }
        },
      ),
    );
  }
}


In this example, the UI widget uses BlocBuilder to rebuild itself based on the state emitted by the BLoC. When the "Fetch Data" button is pressed, the MyEvent. fetch data event is added to the BLoC, triggering the API call and updating the UI based on the result.

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:

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');
    }
  }
}

Remember to handle errors appropriately and consider using state management techniques like BLoC for more complex applications. Adjust the code based on the specific requirements of your API and application.


Thanks for reading the article ...
 



Comments

Popular posts from this blog

How to write a code of Encode and Decode json data in Dart language

 Encode and decode JSON data in dart language import 'dart:convert'; void main() {   // Original data as a Dart map   Map<String, dynamic> originalData = {     'field1': 'value1',     'field2': 42,     'field3': true,   };   // Encode the Dart map to JSON string   String jsonString = jsonEncode(originalData);   print('Original JSON String:');   print(jsonString);   // Encode the JSON string to base64   String base64EncodedString = base64.encode(utf8.encode(jsonString));   print('\nBase64 Encoded String:');   print(base64EncodedString);   // Decode the base64 string to JSON string   String decodedJsonString = utf8.decode(base64.decode(base64EncodedString));   print('\nDecoded JSON String:');   print(decodedJsonString);   // Decode the JSON string to a Dart map   Map<String, dynamic> decodedData = jsonDecode(decodedJsonString);   print('\nDecoded Dart Ma...

About of Free Learning Tech Point

  Welcome to Free Learning Tech Point , where knowledge meets accessibility. Our platform is dedicated to providing high-quality educational resources and e-learning opportunities to learners around the world, completely free of charge. Our Mission: At Free Learning Tech Point, we believe that education is a fundamental right, and everyone should have access to valuable learning materials. Our mission is to break down barriers to education by offering a diverse range of courses, tutorials, and resources across various subjects and disciplines. What Sets Us Apart: - Free Access: Our commitment is to make learning accessible to all. No subscription fees, no hidden costs – just free, open access to knowledge.    - Quality Content: We curate and create content that is both engaging and informative. Whether you're a student, professional, or lifelong learner, our resources are designed to cater to various learning styles and levels. - Diverse Subjects: From tech and science...

Privacy Policy Of Free Learning Tech Point

  Thank you for visiting Free Learning Tech Point . You can use our website, services, and products with the awareness that this Privacy Policy describes how we gather, use, disclose, and protect your personal information. 1- Information We Collect: We may collect personal information that you provide directly to us, such as your name, email address, and any other information you choose to provide when using our Services. We may also collect non-personal information, such as aggregated data and usage patterns. 2- How We Use Your Information: We may use the information we collect for various purposes, including but not limited to: Providing and improving our Services. Responding to your inquiries and requests. Analyzing usage patterns and trends. Sending you updates, newsletters, and other communications. Personalizing your experience on our platform. 3- Cookies and Similar Technologies: We may use cookies and similar technologies to collect information about your interactions with...