Loader in Flutter using Bloc pattern

 Loader in Flutter using Bloc pattern

Hello reader, I hope you enjoyed last post. In this post we are going to learn to implement a loading indicator in Flutter using the Bloc pattern. Enhance state management and user experience in your Flutter development with this guide.

Step 1: Folder and file structure

 
-loader
    -bloc
        -loader_cubit.dart
    -loading_circle.dart
    -loading_screen.dart


Step 2: loader_cubit.dart


import 'package:flutter_bloc/flutter_bloc.dart';


class LoadingCubit extends Cubit<bool> {

  LoadingCubit() : super(false);


  void show() => emit(true);


  void hide() => emit(false);

}


Step3: loading_circle.dart


import 'package:flutter/material.dart';

import '../../../constants/assets.dart';


class LoadingCircle extends StatelessWidget {

  final double size;


  const LoadingCircle({super.key, required this.size});


  @override

  Widget build(BuildContext context) {

    return SizedBox(

      height: 100,

      width: 500,

      child: Image.asset(Assets.loaderGif,

          gaplessPlayback: true, fit: BoxFit.fitHeight),

    );

  }

}


Step 4: loading_screen.dart


import 'package:flutter/material.dart';

import 'package:flutter_bloc/flutter_bloc.dart';

import '../../../constants/size_constants.dart';

import '../../theme/colors.dart';

import 'bloc/LoadingCubit.dart';

import 'loading_circle.dart';


class LoadingScreen extends StatelessWidget {

  final Widget screen;


  const LoadingScreen({super.key, required this.screen});


  @override

  Widget build(BuildContext context) {

    return BlocBuilder<LoadingCubit, bool>(

      buildWhen: (previousState, currentState) => previousState != currentState,

      builder: (context, shouldShow) {

        return WillPopScope(

          onWillPop: shouldShow ? () async => false : null,

          child: Stack(

            fit: StackFit.expand,

            children: [

              screen,

              if (shouldShow)

                Container(

                  decoration: BoxDecoration(

                      color: KColors.chineseBlack.withOpacity(0.7)),

                  child: const Center(

                    child: LoadingCircle(

                      size: Sizes.dimen_200,

                    ),

                  ),

                ),

            ],

          ),

        );

      },

    );

  }

}




Thanks for reading....

Post a Comment

0 Comments