Loader in Flutter using Bloc pattern
Step 1: Folder and file structure
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,
),
),
),
],
),
);
},
);
}
}
0 Comments