Thursday, June 8, 2023

Enhancing Flutter Apps with BLoC State Management and REST APIs for Optimal Performance

 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_app

Open 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 get
Now, let's create the necessary files for the BLoC and REST API implementation:  
  1. Create a new directory called bloc inside the lib directory.

  2. Inside the bloc directory, create a new file called post_bloc.dart with 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();
      }
    }
  }
}
 
 
  1. Inside the lib directory, create another directory called models.

  2. Inside the models directory, create a new file called post.dart with 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:

  3. Replace the contents of lib/main.dart with 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.

No comments:

Post a Comment

Enhancing Flutter Apps with BLoC State Management and REST APIs for Optimal Performance

 Develop a powerful Flutter app utilizing BLoC state management and REST APIs to enhance functionality and performance. Flutter app using th...