Okay, let's create a base screen structure in Flutter using flutter_bloc for state management and auto_route for navigation.
This example will include:
Dependencies: Necessary packages in pubspec.yaml.
Folder Structure: A suggested organization.
BLoC Components: Event, State, and BLoC classes.
Screen Widget: The UI that uses the BLoC and is Auto Route aware.
Auto Route Setup (Basic): How to integrate the screen into your router.
1. Dependencies
Make sure you have these dependencies in your pubspec.yaml:
yaml
dependencies:
flutter:
sdk: flutter
flutter_bloc: ^8.1.3 # Use the latest version
equatable: ^2.0.5 # For value equality in BLoC states/events
auto_route: ^7.8.4 # Use the latest version
dev_dependencies:
flutter_test:
sdk: flutter
build_runner: ^2.4.6 # Use the latest version
auto_route_generator: ^7.3.2 # Use the latest version
flutter_lints: ^2.0.0
part of 'base_bloc.dart'; // Connects to the BLoC file
// Use Equatable for easy value comparison
abstract class BaseEvent extends Equatable {
const BaseEvent();
@override
List<Object> get props => [];
}
// Example Event: Trigger data loading
class LoadBaseData extends BaseEvent {
const LoadBaseData();
}
// Example Event: Trigger some other action
class PerformBaseAction extends BaseEvent {
final String parameter;
const PerformBaseAction(this.parameter);
@override
List<Object> get props => [parameter];
}
part of 'base_bloc.dart'; // Connects to the BLoC file
// Use Equatable for easy value comparison and prevent unnecessary rebuilds
abstract class BaseState extends Equatable {
const BaseState();
@override
List<Object> get props => [];
}
// Initial state
class BaseInitial extends BaseState {
const BaseInitial();
}
// State while loading data
class BaseLoading extends BaseState {
const BaseLoading();
}
// State when data is loaded successfully
class BaseLoaded extends BaseState {
final String data; // Example data field
const BaseLoaded(this.data);
@override
List<Object> get props => [data];
}
// State when an error occurs
class BaseError extends BaseState {
final String message;
const BaseError(this.message);
@override
List<Object> get props => [message];
}
(c) lib/features/base_feature/bloc/base_bloc.dart
dart
import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:meta/meta.dart';
part 'base_event.dart'; // Import event definitions
part 'base_state.dart'; // Import state definitions
class BaseBloc extends Bloc<BaseEvent, BaseState> {
BaseBloc() : super(const BaseInitial()) {
// Register event handlers
on<LoadBaseData>(_onLoadBaseData);
on<PerformBaseAction>(_onPerformBaseAction);
}
// Handler for LoadBaseData event
Future<void> _onLoadBaseData(
LoadBaseData event,
Emitter<BaseState> emit,
) async {
emit(const BaseLoading());
try {
// Simulate network call or data fetching
await Future.delayed(const Duration(seconds: 2));
const fetchedData = 'This is loaded data!';
// You might fetch data from a repository here
// final data = await _yourRepository.fetchData();
emit(const BaseLoaded(fetchedData));
} catch (e) {
emit(BaseError('Failed to load data: ${e.toString()}'));
}
}
// Handler for PerformBaseAction event
Future<void> _onPerformBaseAction(
PerformBaseAction event,
Emitter<BaseState> emit,
) async {
// You can emit different states based on the action
print("Performing action with parameter: ${event.parameter}");
// Maybe navigate or show a snackbar, often done in BlocListener
}
}
import 'package:auto_route/auto_route.dart';
// Adjust the import path for your base screen
import '../../features/base_feature/presentation/screens/base_screen.dart';
part 'app_router.gr.dart'; // This file will be generated
@AutoRouterConfig(replaceInRouteName: 'Screen,Route') // Standard naming convention
class AppRouter extends _$AppRouter { // Extends the generated class
@override
List<AutoRoute> get routes => [
// Define your routes here
AutoRoute(
page: BaseRoute.page, // Use the generated route name (`BaseScreen` -> `BaseRoute`)
path: '/base', // URL path for web/deep linking
initial: true, // Make this the initial route if desired
),
// Add other routes here
// AutoRoute(page: AnotherRoute.page, path: '/another'),
];
}
(b) Run the Build Runner
Open your terminal in the project root and run:
bash
flutter pub run build_runner build --delete-conflicting-outputs
This command generates the app_router.gr.dart file based on your annotations (@RoutePage, @AutoRouterConfig).
(c) Use the Router in main.dart
dart
import 'package:flutter/material.dart';
// Adjust import path
import 'core/navigation/app_router.dart';
void main() {
runApp(MyApp());
}
// Create an instance of your router
final _appRouter = AppRouter();
class MyApp extends StatelessWidget {
MyApp({super.key});
@override
Widget build(BuildContext context) {
// Use MaterialApp.router
return MaterialApp.router(
title: 'Flutter Base Screen Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
// Provide the router configuration
routerConfig: _appRouter.config(),
);
}
}
Now, when you run your app, it should start with BaseScreen (if initial: true was set). The screen will use BaseBloc for its state, and you can interact with the buttons to trigger events and see the UI update according to the BLoC states. Navigation from this screen can be done using context.router.push(...) or other auto_route methods.
import 'package:auto_route/auto_route.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
// Adjust the import path based on your project structure
import '../../bloc/base_bloc.dart';
// AutoRoute Annotation - This makes it discoverable by the generator
@RoutePage()
class BaseScreen extends StatelessWidget {
const BaseScreen({super.key});
@override
Widget build(BuildContext context) {
// Provide the BLoC to the widget subtree
return BlocProvider(
// Create instance of the BLoC.
// Optionally add an initial event: create: (context) => BaseBloc()..add(const LoadBaseData()),
create: (context) => BaseBloc(),
child: Scaffold(
appBar: AppBar(
title: const Text('Base Screen'),
// Example: Accessing router for back navigation if needed
// leading: AutoLeadingButton(), // AutoRoute provides this convenience
),
body: BlocConsumer<BaseBloc, BaseState>(
// listener is optional, used for side effects like navigation, showing snackbars etc.
listener: (context, state) {
if (state is BaseError) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(state.message),
backgroundColor: Colors.red,
),
);
}
// You could listen for a specific state to trigger navigation
// if (state is SomeSpecificStateForNavigation) {
// context.router.push(const AnotherRoute());
// }
},
// builder builds the UI based on the current state
builder: (context, state) {
// Handle different states
if (state is BaseInitial) {
return _buildInitial(context);
} else if (state is BaseLoading) {
return _buildLoading();
} else if (state is BaseLoaded) {
return _buildLoaded(context, state.data);
} else if (state is BaseError) {
// Error state can optionally show a retry button
return _buildError(context, state.message);
}
// Fallback for any unhandled state (though ideally all states are handled)
return const Center(child: Text('Unknown State'));
},
),
),
);
}
// Widget for the Initial state
Widget _buildInitial(BuildContext context) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text('Press the button to load data.'),
const SizedBox(height: 16),
ElevatedButton(
onPressed: () {
// Dispatch the LoadBaseData event to the BLoC
context.read<BaseBloc>().add(const LoadBaseData());
},
child: const Text('Load Data'),
),
const SizedBox(height: 16),
ElevatedButton(
onPressed: () {
// Dispatch another event
context.read<BaseBloc>().add(const PerformBaseAction("Hello from UI!"));
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Action Performed (Check Console)'))
);
},
child: const Text('Perform Action'),
),
],
),
);
}
// Widget for the Loading state
Widget _buildLoading() {
return const Center(
child: CircularProgressIndicator(),
);
}
// Widget for the Loaded state
Widget _buildLoaded(BuildContext context, String data) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('Data Loaded Successfully:', style: Theme.of(context).textTheme.headlineSmall),
const SizedBox(height: 16),
Text(data),
const SizedBox(height: 16),
ElevatedButton(
onPressed: () {
// Option to reload data
context.read<BaseBloc>().add(const LoadBaseData());
},
child: const Text('Reload Data'),
),
const SizedBox(height: 16),
ElevatedButton(
onPressed: () {
// Example: Navigate away using AutoRoute
// Replace `YourNextRoute()` with an actual generated route class
// context.router.push(const YourNextRoute());
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Navigation placeholder'))
);
},
child: const Text('Go to Next Screen'),
),
],
),
);
}
// Widget for the Error state
Widget _buildError(BuildContext context, String message) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Icon(Icons.error_outline, color: Colors.red, size: 50),
const SizedBox(height: 16),
Text('An Error Occurred:', style: Theme.of(context).textTheme.titleMedium),
Padding(
padding: const EdgeInsets.all(16.0),
child: Text(message, textAlign: TextAlign.center, style: const TextStyle(color: Colors.red)),
),
ElevatedButton(
onPressed: () {
// Allow retrying the operation
context.read<BaseBloc>().add(const LoadBaseData());
},
child: const Text('Retry'),
),
],
),
);
}
}