Okay, let's create a basic Flutter screen with the Bloc pattern and AutoRoute for navigation. This will be a foundational setup you can expand upon.
Prerequisites:
- Flutter SDK Installed: Make sure you have Flutter installed and configured.
- Packages: Add the following packages to your
pubspec.yaml file:
dependencies:
flutter:
sdk: flutter
flutter_bloc: ^8.1.3 # Or the latest version
auto_route: ^7.8.4 # Or the latest version
get_it: ^7.6.4 #Or the latest version - for DI
dev_dependencies:
flutter_test:
sdk: flutter
auto_route_generator: ^7.3.2 # Or the latest version
build_runner: ^2.4.7 # Or the latest version
Run flutter pub get after adding these. Make sure the versions are compatible with your flutter version.
Project Structure:
I recommend structuring your project like this:
my_app/
├── lib/
│ ├── core/ (optional - for things used across the app)
│ │ └── services/
│ │ └── di.dart (Dependency Injection setup)
│ ├── features/
│ │ └── my_screen/
│ │ ├── bloc/
│ │ │ ├── my_screen_bloc.dart
│ │ │ ├── my_screen_event.dart
│ │ │ └── my_screen_state.dart
│ │ ├── pages/
│ │ │ └── my_screen_page.dart
│ │ └── models/ (Optional - models specific to this feature)
│ ├── app_router.dart (AutoRoute configuration)
│ └── main.dart
Code:
1. core/services/di.dart (Dependency Injection - Using GetIt):
import 'package:get_it/get_it.dart';
import 'package:my_app/features/my_screen/bloc/my_screen_bloc.dart';
final getIt = GetIt.instance;
Future<void> configureDependencies() async {
// Register Blocs
getIt.registerFactory(() => MyScreenBloc());
// Register other services, repositories, data sources here...
}
2. features/my_screen/bloc/my_screen_event.dart:
part of 'my_screen_bloc.dart';
sealed class MyScreenEvent {}
class MyScreenLoadData extends MyScreenEvent {} // Example event
3. features/my_screen/bloc/my_screen_state.dart:
part of 'my_screen_bloc.dart';
sealed class MyScreenState {
const MyScreenState();
}
final class MyScreenInitial extends MyScreenState {
const MyScreenInitial();
}
final class MyScreenLoading extends MyScreenState {
const MyScreenLoading();
}
final class MyScreenLoaded extends MyScreenState {
const MyScreenLoaded({required this.data});
final String data; // Example data
}
final class MyScreenError extends MyScreenState {
const MyScreenError({required this.message});
final String message;
}
4. features/my_screen/bloc/my_screen_bloc.dart:
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:equatable/equatable.dart'; // Useful for state comparisons
import 'package:my_app/core/services/di.dart';
part 'my_screen_event.dart';
part 'my_screen_state.dart';
class MyScreenBloc extends Bloc<MyScreenEvent, MyScreenState> {
MyScreenBloc() : super(const MyScreenInitial()) {
on<MyScreenLoadData>(_onLoadData);
}
Future<void> _onLoadData(
MyScreenLoadData event, Emitter<MyScreenState> emit) async {
emit(const MyScreenLoading());
try {
// Simulate loading data (replace with your actual data fetching)
await Future.delayed(const Duration(seconds: 2));
const data = "Hello from the Bloc!";
emit(MyScreenLoaded(data: data));
} catch (e) {
emit(MyScreenError(message: e.toString()));
}
}
}
5. features/my_screen/pages/my_screen_page.dart:
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:my_app/features/my_screen/bloc/my_screen_bloc.dart';
import 'package:auto_route/auto_route.dart';
import 'package:my_app/core/services/di.dart';
@RoutePage()
class MyScreenPage extends StatelessWidget {
const MyScreenPage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return BlocProvider(
create: (context) => getIt<MyScreenBloc>()..add(MyScreenLoadData()), // Inject the Bloc
child: Scaffold(
appBar: AppBar(title: const Text('My Screen')),
body: Center(
child: BlocBuilder<MyScreenBloc, MyScreenState>(
builder: (context, state) {
if (state is MyScreenInitial || state is MyScreenLoading) {
return const CircularProgressIndicator();
} else if (state is MyScreenLoaded) {
return Text(state.data);
} else if (state is MyScreenError) {
return Text('Error: ${state.message}');
} else {
return const Text('Unknown state');
}
},
),
),
),
);
}
}
6. app_router.dart:
import 'package:auto_route/auto_route.dart';
import 'package:flutter/material.dart';
import 'package:my_app/features/my_screen/pages/my_screen_page.dart';
part 'app_router.gr.dart'; // This will be generated
@AutoRouterConfig()
class AppRouter extends _$AppRouter {
@override
List<AutoRoute> get routes => [
AutoRoute(page: MyScreenPageRoute.page, initial: true),
];
}
7. main.dart:
import 'package:flutter/material.dart';
import 'package:my_app/app_router.dart';
import 'package:my_app/core/services/di.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized(); // Ensure Flutter is initialized
await configureDependencies(); // Configure DI
runApp(MyApp());
}
class MyApp extends StatelessWidget {
MyApp({Key? key}) : super(key: key);
final _appRouter = AppRouter();
@override
Widget build(BuildContext context) {
return MaterialApp.router(
routerConfig: _appRouter.config(),
debugShowCheckedModeBanner: false,
title: 'My App',
theme: ThemeData(
primarySwatch: Colors.blue,
),
);
}
}
Important Steps:
-
Run the Generator: After creating these files, run the AutoRoute generator:
flutter pub run build_runner build --delete-conflicting-outputs
This will generate the app_router.gr.dart file, which contains the AutoRoute code.
-
Dependency Injection: I've used get_it for Dependency Injection. This is a simple way to make your Bloc available to the MyScreenPage without having to pass it around manually. Remember to configureDependencies() in your main.dart before running the app. Also use getIt<MyScreenBloc>() to resolve the bloc instance in MyScreenPage.
-
AutoRoute: @RoutePage() makes the route accessible to auto route and @AutoRouterConfig() makes sure you routes are setup.
Explanation:
- Bloc Pattern: We've implemented a basic Bloc. The
MyScreenBloc handles the MyScreenLoadData event, simulates loading data, and emits different states (MyScreenLoading, MyScreenLoaded, MyScreenError) to the UI.
- AutoRoute: AutoRoute simplifies navigation. The
AppRouter defines the routes for your application. The @RoutePage() annotation tells AutoRoute to generate a route for MyScreenPage.
- Dependency Injection:
get_it is used to manage dependencies. This helps keep your code decoupled and testable.
- UI Updates: The
BlocBuilder widget in MyScreenPage rebuilds the UI based on the current state emitted by the MyScreenBloc.
How to Run:
- Make sure you have Flutter installed and configured.
- Copy the code into the appropriate files in your Flutter project.
- Run
flutter pub get to install the dependencies.
- Run
flutter pub run build_runner build --delete-conflicting-outputs to generate the AutoRoute code.
- Run
flutter run to start the application.
This is a basic example, but it provides a solid foundation for building more complex Flutter applications with the Bloc pattern and AutoRoute. Remember to adapt the code to your specific needs, add more events and states to your Bloc, and implement your data fetching logic. Also add more routes to your app_router.dart file.