Third GET Dio API Calling with Cubit in Flutter

 import "package:api_with_cubit/3rd_Get_API_call_using_Cubit/Models/post_model.dart";

import "package:api_with_cubit/3rd_Get_API_call_using_Cubit/cubit/post_fetch_cubit.dart";
import "package:api_with_cubit/3rd_Get_API_call_using_Cubit/repository/api_repository.dart";
import "package:api_with_cubit/3rd_Get_API_call_using_Cubit/service/api_service.dart";
import "package:flutter/material.dart";
import "package:flutter_bloc/flutter_bloc.dart";

void main() {
runApp(MyApp(apiServiceThird: ApiServiceThird()));
}

class MyApp extends StatelessWidget {
const MyApp({super.key, required this.apiServiceThird});

final ApiServiceThird apiServiceThird;

@override
Widget build(BuildContext context) {
return MultiBlocProvider(
providers: [
BlocProvider<PostFetchCubit>(
create: (context) {
return PostFetchCubit(
apiRepositoryThird: ApiRepositoryThird(
apiServiceThird: apiServiceThird,
),
)..fetchPostApi();
},
),
],
child: MaterialApp(
title: "HomePage",
debugShowCheckedModeBanner: false,
theme: ThemeData(
appBarTheme: const AppBarTheme(
backgroundColor: Colors.grey,
centerTitle: true,
),
),
home: const HomePage(),
),
);
}
}

class HomePage extends StatelessWidget {
const HomePage({super.key});

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text(
"Api Fetch with Cubit",
style: TextStyle(fontWeight: FontWeight.bold),
),
centerTitle: true,
),
body: BlocBuilder<PostFetchCubit, PostFetchState>(
builder: (context, state) {
if (state is PostFetchLoading) {
return const Center(
child: CircularProgressIndicator(),
);
} else if (state is PostFetchError) {
return Center(
child: Text(state.failure.message),
);
} else if (state is PostFetchLoaded) {
final postList = state.postList;
return postList.isEmpty
? const Center(
child: Text(
"No any POST",
style: TextStyle(
fontWeight: FontWeight.bold, fontSize: 30.0),
),
)
: ListView.builder(
padding: const EdgeInsets.symmetric(
horizontal: 10.0, vertical: 10.0),
itemCount: postList.length,
itemBuilder: (context, index) {
final Post singlePost = postList[index];
return Card(
child: ListTile(
leading: CircleAvatar(
child: Text(
singlePost.id.toString(),
style: const TextStyle(
fontWeight: FontWeight.bold, fontSize: 20.0),
),
),
title: Text(
singlePost.title,
style: const TextStyle(fontWeight: FontWeight.bold),
),
subtitle: Text(singlePost.body),
),
);
},
);
}
return const SizedBox.shrink();
},
),
);
}
}
import "package:api_with_cubit/3rd_Get_API_call_using_Cubit/Models/failure_model.dart";
import "package:api_with_cubit/3rd_Get_API_call_using_Cubit/Models/post_model.dart";
import "package:api_with_cubit/3rd_Get_API_call_using_Cubit/repository/api_repository.dart";
import "package:flutter_bloc/flutter_bloc.dart";
import "package:equatable/equatable.dart";

part "post_fetch_state.dart";

class PostFetchCubit extends Cubit<PostFetchState> {
final ApiRepositoryThird apiRepositoryThird;

PostFetchCubit({required this.apiRepositoryThird})
: super(PostFetchInitial());

Future<void> fetchPostApi() async {
emit(PostFetchLoading());
try {
final List<Post>? postList = await apiRepositoryThird.getPostList();
emit(
PostFetchLoaded(postList: postList ?? []),
);
} on Failure catch (error) {
emit(
PostFetchError(failure: error),
);
} catch (error) {
print("Error: $error");
}
}
}

part of "post_fetch_cubit.dart";

abstract class PostFetchState extends Equatable {
const PostFetchState();

@override
List<Object> get props => [];
}

class PostFetchInitial extends PostFetchState {}

class PostFetchLoading extends PostFetchState {}

class PostFetchLoaded extends PostFetchState {
final List<Post> postList;

const PostFetchLoaded({required this.postList});

@override
List<Object> get props => [postList];
}

class PostFetchError extends PostFetchState {
final Failure failure;

const PostFetchError({required this.failure});

@override
List<Object> get props => [failure];
}

class Failure {
final String message;
final String code;

Failure({
this.message = "",
this.code = "",
});
}

class Post {
final int id;
final String title;
final String body;

Post({required this.id, required this.title, required this.body});

factory Post.fromMap(Map<String, dynamic> map) {
return Post(
id: map["id"] as int,
title: map["title"] as String,
body: map["body"] as String,
);
}
}

import 'package:api_with_cubit/3rd_Get_API_call_using_Cubit/Models/post_model.dart';
import 'package:api_with_cubit/3rd_Get_API_call_using_Cubit/service/api_service.dart';

class ApiRepositoryThird {
final ApiServiceThird apiServiceThird;

/// api repository is used to fetch data in cubit function
ApiRepositoryThird({required this.apiServiceThird});

Future<List<Post>?> getPostList() async {
final response = await apiServiceThird.getPostData();
if (response != null) {
final data = response.data as List<dynamic>;
return data.map(
(singlePost) {
return Post.fromMap(singlePost);
},
).toList();
}
}
}

import "package:dio/dio.dart";

class ApiServiceThird {
final Dio _dio = Dio();

Future<Response?> getPostData() async {
try {
final Response response =
await _dio.get("https://jsonplaceholder.typicode.com/posts");
return response;
} catch (error) {
print("Error: $error");
}
}
}

/// https://jsonplaceholder.typicode.com/posts
const String baseUrl = "https://jsonplaceholder.typicode.com";
const String posts = "posts";





Comments

Popular posts from this blog

Pagination with Bloc Pattern in Flutter

Pagination First Practical in Flutter

ExpansionPanel with ExpansionPanelList with Complete Collapse Operation in Flutter