Flutter bloc 6.0.1
- MultiRepositoryProvider
- Merges multiple RepositoryProvider widgets into one widget tree.
- RepositoryProvider
- It is used as a dependency injection (DI) widget so that a single instance of a repository can be provided to multiple widgets within a subtree.
- Lazily creates the provided repository unless `lazy` is set to `false`.
Note : flutter bloc 6.0.1 create 2 classes. 1) state 2) cubit
here is a programming of flutter bloc 6.0.1

lib Package
Inside Lib Package Create
- cubite package
- data package
- model package
- res package
- ui package
- main.dart
cubite package
post_cubit.dart
import 'package:bloc/bloc.dart'; import 'package:bloc_new/data/network_service.dart'; import 'post_state.dart'; class PostCubit extends Cubit<PostState> { final NetworkService networkService; PostCubit({this.networkService}) : super(PostInitial()); Future<void> clear() async { emit(PostInitial()); } Future<void> getPost() async { emit(PostLoading()); await networkService.fetchPosts().then((posts) { emit(PostLoaded(posts)); }).catchError(() { emit(PostError(message: "Some error")); }); } }
post_state.dart
import 'package:equatable/equatable.dart'; import 'package:bloc_new/model/post.dart'; abstract class PostState { const PostState(); } class PostInitial extends PostState { const PostInitial(); } class PostLoading extends PostState { const PostLoading(); } class PostLoaded extends PostState with EquatableMixin { final List<Post> posts; PostLoaded(this.posts); @override List<Object> get props => [posts]; } class PostError extends PostState with EquatableMixin { final String message; PostError({this.message}); @override List<Object> get props => [message]; }
Data Package
network_service.dart
import 'dart:convert'; import 'package:bloc_new/model/post.dart'; import 'package:http/http.dart'; const String BASE_URL = "https://jsonplaceholder.typicode.com/"; const String POSTS = "posts"; class NetworkService { Future<List<Post>> fetchPosts() async { Response response = await get(BASE_URL + POSTS); List decodeResponse = json.decode(response.body); return decodeResponse.map((value) => Post.fromJson(value)).toList(); } }
Model Package
post.dart
import 'package:equatable/equatable.dart'; class Post extends Equatable { final int userId; final int id; final String title; final String body; Post({this.userId, this.id, this.title, this.body}); factory Post.fromJson(Map<String, dynamic> json) { return Post( userId: json['userId'], id: json['id'], title: json['title'], body: json['body']); } @override List<Object> get props => [userId, id, title, body]; @override bool get stringify => true; }
res package
string.dart
class Strings { // App static const appName = "Flutter Bloc"; // Home Screen static const homeScreen_title = "Home Screen"; static const homeScreen_openPostScreen = "Open PostScreen"; // News Screen static const newsScreen_title = "News Screen"; }
ui package
home.dart
import 'package:flutter/material.dart'; import 'package:bloc_new/res/strings.dart'; import 'file:///C:/Users/kamlesh/AndroidStudioProjects/bloc_new/lib/ui/home/post_screen.dart'; class HomeScreen extends StatefulWidget { @override HomeScreenState createState() => HomeScreenState(); } class HomeScreenState extends State { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text(Strings.homeScreen_title)), body: SafeArea( child: Center( child: Container( padding: EdgeInsets.only(top: 20.0), child: Column(children: <Widget>[ RaisedButton( child: Text(Strings.homeScreen_openPostScreen), onPressed: () { Navigator.push( context, MaterialPageRoute( builder: (context) => PostScreen())); }) ]))))); } }
post_screen.dart
import 'package:bloc_new/cubit/post/post_cubit.dart'; import 'package:bloc_new/cubit/post/post_state.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:bloc_new/model/post.dart'; import 'package:bloc_new/res/strings.dart'; class PostScreen extends StatefulWidget { @override PostScreenState createState() => PostScreenState(); } class PostScreenState extends State { @override void initState() { BlocProvider.of<PostCubit>(context).getPost(); super.initState(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text(Strings.newsScreen_title)), body: BlocBuilder<PostCubit, PostState>(builder: (context, postState) { if (postState is PostInitial) { return buildInitialWidget(); } else if (postState is PostLoading) { return buildLoadingWidget(); } else if (postState is PostLoaded) { return buildLoadedWidget(postState.posts); } else if (postState is PostError) { return buildErrorWidget(postState.message); } else { return null; } })); } Widget buildInitialWidget() { return Center(child: RaisedButton(child: Text("Load data"))); } Widget buildLoadingWidget() { return Center(child: CircularProgressIndicator()); } Widget buildLoadedWidget(List<Post> posts) { return buildPostListWidget(posts); } var dividerWidget = Padding( padding: const EdgeInsets.only(left: 8.0, right: 8.0), child: Divider(height: 1, thickness: 1, color: Colors.black38)); Widget buildPostListWidget(List<Post> posts) { return ListView.separated( physics: BouncingScrollPhysics(), separatorBuilder: (context, index) => dividerWidget, itemBuilder: (context, index) => _postItemWidget(context, posts[index]), itemCount: posts.length); } Widget _postItemWidget(BuildContext context, Post post) { return Container( margin: EdgeInsets.only(left: 8.0, right: 8.0), child: Card( shape: RoundedRectangleBorder( borderRadius: BorderRadius.all(Radius.circular(20.0))), elevation: 4.0, child: InkWell( customBorder: RoundedRectangleBorder( borderRadius: BorderRadius.all(Radius.circular(20.0))), child: Container( margin: EdgeInsets.all(20.0), child: Text(post.body)), onTap: () { Scaffold.of(context) .showSnackBar(SnackBar(content: Text("${post.title}"))); }))); } Widget buildErrorWidget(String message) { return Center(child: Text(message)); } }
outside all package
main.dart
import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:bloc_new/data/network_service.dart'; import 'package:bloc_new/res/strings.dart'; import 'package:bloc_new/ui/home/home.dart'; import 'cubit/post/post_cubit.dart'; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MultiRepositoryProvider( providers: [RepositoryProvider(create: (context) => NetworkService())], child: MultiBlocProvider( providers: [ BlocProvider<PostCubit>( create: (context) => PostCubit( networkService: context.repository<NetworkService>())) ], child: MaterialApp( title: Strings.appName, theme: ThemeData( primarySwatch: Colors.blue, visualDensity: VisualDensity.adaptivePlatformDensity), home: HomeScreen()))); } }
pubspec.yaml
name: bloc_new description: A new Flutter application. publish_to: 'none' version: 1.0.0+1 environment: sdk: ">=2.7.0 <3.0.0" dependencies: flutter: sdk: flutter cupertino_icons: http: flutter_bloc: equatable: dev_dependencies: flutter_test: sdk: flutter flutter: uses-material-design: true
The flutter tutorial is a website that bring you the latest and amazing resources of code. All the languages codes are included in this website. The languages like flutter, android, java,kotlin etc.with the help of this languages any user can develop the beautiful application
For more information about Flutter. visit www.fluttertutorial.in