### Install common_github_search Dependencies Source: https://github.com/felangel/bloc/blob/master/examples/github_search/README.md Use this command to install dependencies for the common_github_search module. Ensure you are in the correct directory. ```bash cd common_github_search dart pub get cd ../ ``` -------------------------------- ### Install flutter_github_search Dependencies Source: https://github.com/felangel/bloc/blob/master/examples/github_search/README.md Use this command to install dependencies for the flutter_github_search module. Ensure you are in the correct directory. ```bash cd flutter_github_search flutter pub get cd ../ ``` -------------------------------- ### Run Flutter Project Source: https://github.com/felangel/bloc/blob/master/examples/github_search/README.md Navigate to the flutter_github_search directory and run this command to start the Flutter application. ```bash cd flutter_github_search flutter run ``` -------------------------------- ### Show Bloc Linter Help (Dart) Source: https://github.com/felangel/bloc/blob/master/docs/src/content/docs/lint/installation.mdx Displays the help output for the `bloc lint` command after `bloc_tools` has been installed. This command shows available options and usage instructions for the bloc linter. ```dart bloc lint --help ``` -------------------------------- ### Install angular_github_search Dependencies Source: https://github.com/felangel/bloc/blob/master/examples/github_search/README.md Use this command to install dependencies for the angular_github_search module. Ensure you are in the correct directory. ```bash cd angular_github_search dart pub get cd ../ ``` -------------------------------- ### Install Bloc Command-Line Tools Source: https://github.com/felangel/bloc/blob/master/docs/src/content/docs/lint/index.mdx Installs the bloc command-line tools, which are necessary for running the bloc linter and other bloc-related utilities. This is a prerequisite for using the bloc linter. ```bash dart pub global activate bloc_tools ``` -------------------------------- ### Install Dependencies Source: https://github.com/felangel/bloc/blob/master/docs/src/content/docs/tutorials/flutter-infinite-list.mdx Command to install all the dependencies listed in the pubspec.yaml file. This command should be run after updating the pubspec.yaml. ```bash flutter pub get ``` -------------------------------- ### Initialize Flutter Project Source: https://github.com/felangel/bloc/blob/master/docs/src/content/docs/tutorials/github-search.mdx Commands to create a new Flutter project and install dependencies for the GitHub search application. ```shell flutter create flutter_github_search flutter pub get ``` -------------------------------- ### Simplify MockBloc and MockCubit testing with mocktail Source: https://github.com/felangel/bloc/blob/master/docs/src/content/docs/migration.mdx Demonstrates the transition from requiring manual registerFallbackValue calls in v8.x.x to the simplified setup in v9.0.0 for MockBloc and MockCubit. ```dart // v8.x.x class FakeMyEvent extends Fake implements MyEvent {} class FakeMyState extends Fake implements MyState {} class MyMockBloc extends MockBloc implements MyBloc {} void main() { setUpAll(() { registerFallbackValue(FakeMyEvent()); registerFallbackValue(FakeMyState()); }); // Tests... } ``` ```dart // v9.0.0 class MyMockBloc extends MockBloc implements MyBloc {} void main() { // Tests... } ``` -------------------------------- ### Counter Bloc Test Setup Source: https://github.com/felangel/bloc/blob/master/docs/src/content/docs/testing.mdx This snippet demonstrates how to create an instance of the CounterBloc within a setUp function. This ensures a fresh instance of the bloc is available for each test. ```dart late CounterBloc counterBloc; void setUp() { counterBloc = CounterBloc(); } void tearDown() { counterBloc.close(); } ``` -------------------------------- ### Activate Bloc CLI Tools Source: https://github.com/felangel/bloc/blob/master/packages/bloc_tools/example/README.md Installs the bloc_tools package globally using the Dart package manager. ```sh dart pub global activate bloc_tools ``` -------------------------------- ### App Widget Setup (app.dart) Source: https://github.com/felangel/bloc/blob/master/docs/src/content/docs/ru/tutorials/flutter-todos.mdx The App widget wraps the application with a RepositoryProvider to make the TodosRepository available to all descendant widgets. AppView then configures the MaterialApp, including theme and localizations. ```dart class App extends StatelessWidget { const App({super.key, required TodosRepository todosRepository}) : _todosRepository = todosRepository; final TodosRepository _todosRepository; @override Widget build(BuildContext context) { return RepositoryProvider.value( value: _todosRepository, child: const AppView(), ); } } class AppView extends StatelessWidget { const AppView({super.key}); @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Todos', theme: FlutterTodosTheme.light, darkTheme: FlutterTodosTheme.dark, home: const HomePage(), ); } } ``` -------------------------------- ### Bloc Observer Setup (v5.0.0) Source: https://github.com/felangel/bloc/blob/master/docs/src/content/docs/es/migration.mdx In version 5.0.0, `BlocObserver` is set directly via `Bloc.observer`. This change decouples storage from `BlocDelegate` and maintains consistency. ```dart Bloc.observer = MyBlocObserver(); ``` -------------------------------- ### Bootstrap Function (bootstrap.dart) Source: https://github.com/felangel/bloc/blob/master/docs/src/content/docs/ru/tutorials/flutter-todos.mdx The bootstrap function initializes the BlocObserver and creates the instance of TodosRepository. It serves as the starting point for setting up the application's core dependencies. ```dart void bootstrap({required TodosApiClient todosApiClient}) { Bloc.observer = const AppBlocObserver(); runApp( App( todosRepository: TodosRepository( todosApiClient: todosApiClient, ), ), ); } ``` -------------------------------- ### Install very_good_cli Source: https://github.com/felangel/bloc/blob/master/docs/src/content/docs/tutorials/flutter-todos.mdx Installs the very_good_cli tool, which is used for creating and managing Flutter projects with best practices. Ensure you have Flutter installed and configured. ```bash dart pub global activate very_good_cli ``` -------------------------------- ### Bloc Counter Example Source: https://github.com/felangel/bloc/blob/master/docs/src/content/docs/testing.mdx This snippet shows the implementation of a basic CounterBloc, which is used as an example throughout the testing documentation. ```dart class CounterBloc extends Bloc { CounterBloc() : super(0) { on((event, emit) => emit(state + 1)); } } ``` -------------------------------- ### Implement a Global BlocObserver in Dart Source: https://github.com/felangel/bloc/blob/master/packages/bloc/README.md Provides an example of creating a `BlocObserver` to globally observe all Cubit and Bloc lifecycle events such as creation, state changes, errors, and closure. ```dart class MyBlocObserver extends BlocObserver { @override void onCreate(BlocBase bloc) { super.onCreate(bloc); print('onCreate -- ${bloc.runtimeType}'); } @override void onChange(BlocBase bloc, Change change) { super.onChange(bloc, change); print('onChange -- ${bloc.runtimeType}, $change'); } @override void onError(BlocBase bloc, Object error, StackTrace stackTrace) { print('onError -- ${bloc.runtimeType}, $error'); super.onError(bloc, error, stackTrace); } @override void onClose(BlocBase bloc) { super.onClose(bloc); print('onClose -- ${bloc.runtimeType}'); } } ``` -------------------------------- ### Create and Use ReplayCubit Source: https://github.com/felangel/bloc/blob/master/packages/replay_bloc/README.md Demonstrates how to extend ReplayCubit to manage state with built-in undo/redo capabilities. The example shows state transitions and the invocation of undo and redo methods. ```dart class CounterCubit extends ReplayCubit { CounterCubit() : super(0); void increment() => emit(state + 1); } void main() { final cubit = CounterCubit(); cubit.increment(); print(cubit.state); // 1 cubit.undo(); print(cubit.state); // 0 cubit.redo(); print(cubit.state); // 1 } ``` -------------------------------- ### Install Dependencies for Common GitHub Search Source: https://github.com/felangel/bloc/blob/master/docs/src/content/docs/tutorials/github-search.mdx Installs the project dependencies defined in the `pubspec.yaml` file for the common GitHub Search library. This command fetches and links all required packages, making them available for use in the project. ```bash dart pub get ``` -------------------------------- ### Bloc Linter Warning Output Example Source: https://github.com/felangel/bloc/blob/master/docs/src/content/docs/lint/index.mdx Shows an example of the warning output produced by the bloc linter when a Flutter dependency is incorrectly imported into a cubit. This output helps developers identify and fix the issue. ```text warning: Avoid importing 'package:flutter/material.dart' into a cubit. lib/my_cubit.dart:1:8 | 1 | import 'package:flutter/material.dart'; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | 'Avoid importing 'package:flutter/material.dart' into a cubit.' ``` -------------------------------- ### Stream Manipulation Examples Source: https://github.com/felangel/bloc/blob/master/docs/src/content/docs/bloc-concepts.mdx Demonstrates how to work with streams for state management. Includes examples for counting stream events and summing stream values. These snippets are useful for understanding reactive programming within the bloc package. ```dart Stream count = Stream.periodic(const Duration(seconds: 1), (i) => i).take(5); count.listen(print); // Output: // 0 // 1 // 2 // 3 // 4 ``` ```dart Stream sum = Stream.fromIterable([1, 2, 3, 4, 5]); sum.listen(print); // Output: // 1 // 2 // 3 // 4 // 5 ``` -------------------------------- ### Bootstrap Application Environment Source: https://github.com/felangel/bloc/blob/master/docs/src/content/docs/tutorials/flutter-todos.mdx Handles the initialization of the BlocObserver and the creation of the TodosRepository. This ensures global dependencies are ready before the app starts. ```Dart Future bootstrap(FutureOr Function() builder) async { Bloc.observer = const AppBlocObserver(); runApp(await builder()); } ``` -------------------------------- ### Select specific state properties with context.select Source: https://github.com/felangel/bloc/blob/master/docs/src/content/docs/migration.mdx Shows how to listen to a specific part of a bloc state, ensuring the widget only rebuilds when that specific property changes. ```dart final name = context.select((UserBloc bloc) => bloc.state.user.name); ``` -------------------------------- ### Simplified HydratedBloc Initialization (Dart) Source: https://github.com/felangel/bloc/blob/master/docs/src/content/docs/migration.mdx Demonstrates the simplified initialization process for `HydratedBloc` in v5.0.0, aligning it with standard `Bloc` initialization and removing the need for manual `super.initialState` calls. ```dart class CounterBloc extends HydratedBloc { @override int get initialState => super.initialState ?? 0; } ``` ```dart class CounterBloc extends HydratedBloc { CounterBloc() : super(0); ... } ``` -------------------------------- ### Listen to Bloc and Cubit streams Source: https://github.com/felangel/bloc/blob/master/docs/src/content/docs/migration.mdx Demonstrates the updated syntax for listening to state changes in Bloc and Cubit by accessing the stream property directly in version 7.0.0. ```dart final bloc = MyBloc(); bloc.stream.listen((state) {...}); final cubit = MyCubit(); cubit.stream.listen((state) {...}); ``` -------------------------------- ### Implement HydratedBlocOverrides for scoped storage Source: https://github.com/felangel/bloc/blob/master/docs/src/content/docs/migration.mdx Shows the migration from global HydratedBloc.storage singletons to the zone-based HydratedBlocOverrides API introduced in v8.0.0 to support scoped storage implementations. ```dart // v7.x.x void main() async { HydratedBloc.storage = await HydratedStorage.build( storageDirectory: await getApplicationSupportDirectory(), ); // ... } ``` ```dart // v8.0.0 void main() { final storage = await HydratedStorage.build( storageDirectory: await getApplicationSupportDirectory(), ); HydratedBlocOverrides.runZoned( () { // ... }, storage: storage, ); } ``` -------------------------------- ### Counter Cubit Implementation and Usage Source: https://github.com/felangel/bloc/blob/master/docs/src/content/docs/bloc-concepts.mdx Illustrates the creation and usage of a CounterCubit, a simple state management class. It covers initializing the state, incrementing the counter, and observing state changes. This is a basic example for getting started with Cubits. ```dart class CounterCubit extends Cubit { CounterCubit() : super(0); void increment() => emit(state + 1); } ``` ```dart final counterCubit = CounterCubit(); print(counterCubit.state); // Output: 0 counterCubit.increment(); print(counterCubit.state); // Output: 1 ``` ```dart counterCubit.stream.listen(print); // Output: // 0 // 1 ``` ```dart counterCubit.onChange.listen(print); // Output: // Change(initialState: 0, nextState: 1) ``` -------------------------------- ### Setup AngularDart Counter App Dependencies Source: https://github.com/felangel/bloc/blob/master/docs/src/content/docs/tutorials/ngdart-counter.mdx Installs necessary dependencies for the AngularDart counter application by replacing the pubspec.yaml content and running the dependency installation command. ```yaml name: angular_counter version: 0.0.1 homepage: https://dart.dev/tools/dart-pub environment: sdk: '>=2.12.0 <3.0.0' dependencies: angular: ^6.0.0 bloc: ^8.0.0 flutter_bloc: ^8.0.0 equatable: ^2.0.0 dev_dependencies: build_runner: ^2.1.0 build_test: ^2.0.0 build_web_compilers: ^3.0.0 lints: ^1.0.0 test: ^1.16.0 angular_test: ^3.0.0 ``` ```bash dart pub get ``` -------------------------------- ### Application Entrypoint and Configuration Source: https://github.com/felangel/bloc/blob/master/docs/src/content/docs/tutorials/flutter-weather.mdx Sets up the main application entry point, including BlocObserver for debugging and HydratedStorage for state persistence. ```dart https://raw.githubusercontent.com/felangel/bloc/master/examples/flutter_weather/lib/main.dart ``` ```dart https://raw.githubusercontent.com/felangel/bloc/master/examples/flutter_weather/lib/app.dart ``` -------------------------------- ### Initialize Flutter Project Source: https://github.com/felangel/bloc/blob/master/docs/src/content/docs/tutorials/flutter-weather.mdx The command to scaffold a new Flutter project. This is the foundational step for setting up the application environment. ```bash flutter create flutter_weather ``` -------------------------------- ### View Bloc CLI Help Source: https://github.com/felangel/bloc/blob/master/packages/bloc_tools/example/README.md Displays the list of available commands and usage information for the Bloc CLI. ```sh bloc --help ``` -------------------------------- ### blocTest build method synchronous change (v5 vs v6) Source: https://github.com/felangel/bloc/blob/master/docs/src/content/docs/migration.mdx The `build` function in `blocTest` is now synchronous in v6.0.0, whereas it was asynchronous in v5.x.x. This change simplifies setup by allowing direct state emission instead of async preparation. ```dart blocTest( 'emits [2] when increment is added', build: () async { final bloc = CounterBloc(); bloc.add(CounterEvent.increment); await bloc.take(2); return bloc; }, act: (bloc) => bloc.add(CounterEvent.increment), expect: const [2], ); ``` ```dart blocTest( 'emits [2] when increment is added', build: () => CounterBloc()..emit(1), act: (bloc) => bloc.add(CounterEvent.increment), expect: const [2], ); // Note: emit is only visible for testing. ``` -------------------------------- ### Run the linter Source: https://github.com/felangel/bloc/blob/master/packages/bloc_lint/README.md Execute the bloc lint command to analyze your project files. ```sh bloc lint . ``` -------------------------------- ### Flutter App Entrypoints (main_development.dart, main_staging.dart, main_production.dart) Source: https://github.com/felangel/bloc/blob/master/docs/src/content/docs/ru/tutorials/flutter-todos.mdx These files serve as the entry points for the Flutter application, with variations for development, staging, and production environments. They are responsible for initializing the app and instantiating the local storage todos API. ```dart Future main() async { WidgetsFlutterBinding.ensureInitialized(); final todosApiClient = LocalStorageTodosApiClient( plugin: await SharedPreferences.getInstance(), ); bootstrap( todosApiClient: todosApiClient, ); } ``` ```dart Future main() async { WidgetsFlutterBinding.ensureInitialized(); final todosApiClient = LocalStorageTodosApiClient( plugin: await SharedPreferences.getInstance(), ); bootstrap( todosApiClient: todosApiClient, ); } ``` ```dart Future main() async { WidgetsFlutterBinding.ensureInitialized(); final todosApiClient = LocalStorageTodosApiClient( plugin: await SharedPreferences.getInstance(), ); bootstrap( todosApiClient: todosApiClient, ); } ``` -------------------------------- ### Install Bloc Lint Package Source: https://github.com/felangel/bloc/blob/master/docs/src/content/docs/lint/index.mdx Installs the bloc_lint package as a dev dependency in your project. This package provides the linting rules used by the bloc linter. ```bash dart pub add --dev bloc_lint ``` -------------------------------- ### Initialize Flutter Project and Dependencies Source: https://github.com/felangel/bloc/blob/master/docs/src/content/docs/tutorials/flutter-login.mdx Commands to create a new Flutter project and fetch necessary package dependencies for the application. ```shell flutter create login_app flutter pub get ``` -------------------------------- ### Create Flutter Repository Package Source: https://github.com/felangel/bloc/blob/master/docs/src/content/docs/tutorials/flutter-weather.mdx Command to initialize a new Dart package for the repository layer within a Flutter project structure. ```bash flutter create --template=package weather_repository ``` -------------------------------- ### View CLI Help Source: https://github.com/felangel/bloc/blob/master/packages/bloc_tools/README.md Displays the usage information and available commands for the Bloc Tools CLI. ```shell Command Line Tools for the Bloc Library. Usage: bloc [arguments] Global options: -h, --help Print this usage information. --version Print the current version. Available commands: lint bloc lint [arguments] Lint Dart source code. new bloc new [arguments] Generate new bloc components. Run "bloc help " for more information about a command. ``` -------------------------------- ### State Naming Conventions (Bad Examples) Source: https://github.com/felangel/bloc/blob/master/docs/src/content/docs/naming-conventions.mdx Illustrates discouraged naming conventions for Bloc states, showing how unclear names can hinder understanding. This includes examples of both subclass and single-class state representations. ```dart abstract class CounterState extends Equatable { const CounterState(); @override List get props => []; } class A extends CounterState {} class B extends CounterState { const B(this.value); final int value; @override List get props => [value]; } class C extends CounterState { const C(this.message); final String message; @override List get props => [message]; } class D extends CounterState {} ``` -------------------------------- ### Dart Counter Cubit Implementation Source: https://github.com/felangel/bloc/blob/master/docs/src/components/lint/ImportFlutterInfoSnippet.mdx This snippet shows the implementation of a basic CounterCubit class in Dart using the bloc package. It extends the Cubit class and initializes the state to 0. This is a foundational example for managing state in Flutter applications. ```dart import 'package:bloc/bloc.dart'; import 'package:flutter/material.dart'; class CounterCubit extends Cubit { CounterCubit() : super(0); } ``` -------------------------------- ### Initialize AngularDart Project Source: https://github.com/felangel/bloc/blob/master/docs/src/content/docs/tutorials/github-search.mdx Commands to install stagehand and create a new AngularDart project structure. ```shell pub global activate stagehand stagehand web-angular ``` -------------------------------- ### CounterApp Setup with BlocProvider - Dart Source: https://github.com/felangel/bloc/blob/master/packages/flutter_bloc/README.md Sets up the main application widget, CounterApp, using MaterialApp. It demonstrates how to use BlocProvider to make a CounterCubit instance available to the widget subtree. The CounterPage widget will have access to this provided cubit. ```dart void main() => runApp(CounterApp()); class CounterApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: BlocProvider( create: (_) => CounterCubit(), child: CounterPage(), ), ); } } ``` -------------------------------- ### Update global Bloc observer configuration Source: https://github.com/felangel/bloc/blob/master/docs/src/content/docs/migration.mdx Replaces the deprecated BlocSupervisor.delegate assignment with the static Bloc.observer property. ```dart Bloc.observer = MyBlocObserver(); ``` -------------------------------- ### Watch multiple blocs with context.watch Source: https://github.com/felangel/bloc/blob/master/docs/src/content/docs/migration.mdx Demonstrates how to observe multiple bloc states within a single Builder widget using context.watch, enabling UI updates based on multiple data sources. ```dart Builder( builder: (context) { final stateA = context.watch().state; final stateB = context.watch().state; final stateC = context.watch().state; // return a Widget which depends on the state of BlocA, BlocB, and BlocC } ); ``` -------------------------------- ### Rename condition to buildWhen in BlocBuilder Source: https://github.com/felangel/bloc/blob/master/docs/src/content/docs/migration.mdx Updates the condition property to buildWhen in BlocBuilder to provide a more descriptive and consistent API. ```dart BlocBuilder( buildWhen: (previous, current) { return true; }, builder: (context, state) {...} ); ``` -------------------------------- ### Unit Test WeatherCubit Logic Source: https://github.com/felangel/bloc/blob/master/docs/src/content/docs/tutorials/flutter-weather.mdx Demonstrates how to write unit tests for the WeatherCubit using the bloc_test library to verify state transitions and business logic. ```dart https://raw.githubusercontent.com/felangel/bloc/master/examples/flutter_weather/test/weather/cubit/weather_cubit_test.dart ``` -------------------------------- ### Run AngularDart Project Source: https://github.com/felangel/bloc/blob/master/examples/github_search/README.md Navigate to the angular_github_search directory and run this command to serve the AngularDart web application. ```bash cd angular_github_search webdev serve ``` -------------------------------- ### Install bloc_lint dependency Source: https://github.com/felangel/bloc/blob/master/docs/src/content/docs/lint/customizing-rules.mdx Add the bloc_lint package to your project as a development dependency using the dart pub command. ```shell dart pub add bloc_lint --dev ``` -------------------------------- ### Unit Test WeatherRepository with Mocktail Source: https://github.com/felangel/bloc/blob/master/docs/src/content/docs/tutorials/flutter-weather.mdx Demonstrates how to unit test the WeatherRepository by mocking the API client using the mocktail library. This ensures domain logic is verified in an isolated environment. ```dart import 'package:mocktail/mocktail.dart'; import 'package:test/test.dart'; import 'package:weather_repository/weather_repository.dart'; class MockWeatherApiClient extends Mock implements WeatherApiClient {} void main() { group('WeatherRepository', () { late WeatherApiClient apiClient; late WeatherRepository repository; setUp(() { apiClient = MockWeatherApiClient(); repository = WeatherRepository(weatherApiClient: apiClient); }); test('getWeather returns weather on success', () async { // Test implementation details... }); }); } ``` -------------------------------- ### Initialize Flutter Project Source: https://github.com/felangel/bloc/blob/master/docs/src/content/docs/tutorials/flutter-timer.mdx The initial command to scaffold a new Flutter project structure for the timer application. ```bash flutter create flutter_timer ``` -------------------------------- ### Rename BlocDelegate to BlocObserver Source: https://github.com/felangel/bloc/blob/master/docs/src/content/docs/migration.mdx Updates the observer class name from BlocDelegate to BlocObserver to better reflect its passive role in the application. ```dart class MyBlocObserver extends BlocObserver { ... } ``` -------------------------------- ### Configure Dependencies for Testing Source: https://github.com/felangel/bloc/blob/master/docs/src/content/docs/tutorials/flutter-weather.mdx Lists the necessary dev_dependencies in pubspec.yaml to support unit testing, specifically bloc_test, mocktail, and test packages. ```yaml https://raw.githubusercontent.com/felangel/bloc/master/examples/flutter_weather/pubspec.yaml ``` -------------------------------- ### Use a Bloc in Dart Source: https://github.com/felangel/bloc/blob/master/packages/bloc/README.md Illustrates how to instantiate a Bloc, add events to it to trigger state changes, wait for the event processing to complete, access the new state, and finally close the Bloc. ```dart Future main() async { /// Create a `CounterBloc` instance. final bloc = CounterBloc(); /// Access the state of the `bloc` via `state`. print(bloc.state); // 0 /// Interact with the `bloc` to trigger `state` changes. bloc.add(CounterIncrementPressed()); /// Wait for next iteration of the event-loop /// to ensure event has been processed. await Future.delayed(Duration.zero); /// Access the new `state`. print(bloc.state); // 1 /// Close the `bloc` when it is no longer needed. await bloc.close(); } ``` -------------------------------- ### Migrate initialState to super constructor Source: https://github.com/felangel/bloc/blob/master/docs/src/content/docs/migration.mdx Removes the initialState override in favor of passing the initial state to the super constructor in the Bloc class. ```dart class CounterBloc extends Bloc { CounterBloc() : super(0); } ``` -------------------------------- ### Create New Flutter Project Source: https://github.com/felangel/bloc/blob/master/docs/src/content/docs/tutorials/flutter-infinite-list.mdx Command to create a new Flutter project. This is the initial step for setting up the infinite list application. ```bash flutter create flutter_infinite_list ``` -------------------------------- ### Fetch Posts from JSONPlaceholder API Source: https://github.com/felangel/bloc/blob/master/docs/src/content/docs/tutorials/flutter-infinite-list.mdx Example of the JSON response from the JSONPlaceholder API for posts. This demonstrates the structure of the data that will be fetched and displayed in the list. ```json [ { "userId": 1, "id": 1, "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit", "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto" }, { "userId": 1, "id": 2, "title": "qui est esse", "body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque " } ] ``` -------------------------------- ### Create Presentation Layer Pages Source: https://github.com/felangel/bloc/blob/master/docs/src/content/docs/tutorials/flutter-weather.mdx Implements the main UI components including WeatherPage, SettingsPage, and SearchPage to handle user interaction and state injection. ```dart https://raw.githubusercontent.com/felangel/bloc/master/examples/flutter_weather/lib/weather/view/weather_page.dart ``` ```dart https://raw.githubusercontent.com/felangel/bloc/master/examples/flutter_weather/lib/settings/view/settings_page.dart ``` ```dart https://raw.githubusercontent.com/felangel/bloc/master/examples/flutter_weather/lib/search/view/search_page.dart ``` -------------------------------- ### Create Counter Cubit (Dart) Source: https://github.com/felangel/bloc/blob/master/docs/src/components/lint-rules/prefer_void_public_cubit_methods/BadSnippet.mdx Demonstrates how to create a simple CounterCubit using the bloc library. This Cubit manages an integer state and provides an increment method to update the state. It initializes the state to 0 and emits new states using the emit method. ```dart import 'package:bloc/bloc.dart'; class CounterCubit extends Cubit { CounterCubit() : super(0); int increment() { emit(state + 1); return state; } } ``` -------------------------------- ### Implement Timer Event Handlers Source: https://github.com/felangel/bloc/blob/master/docs/src/content/docs/tutorials/flutter-timer.mdx Handles timer lifecycle events including starting, ticking, pausing, resuming, and resetting the timer state. ```dart void _onStarted(TimerStarted event, Emitter emit) { emit(TimerRunInProgress(event.duration)); _tickerSubscription?.cancel(); _tickerSubscription = _ticker .tick(ticks: event.duration) .listen((duration) => add(_TimerTicked(duration: duration))); } void _onTicked(_TimerTicked event, Emitter emit) { emit(event.duration > 0 ? TimerRunInProgress(event.duration) : const TimerRunComplete()); } void _onPaused(TimerPaused event, Emitter emit) { if (state is TimerRunInProgress) { _tickerSubscription?.pause(); emit(TimerRunPause(state.duration)); } } void _onResumed(TimerResumed event, Emitter emit) { if (state is TimerRunPause) { _tickerSubscription?.resume(); emit(TimerRunInProgress(state.duration)); } } ``` -------------------------------- ### Test Flutter UI with MockCubits Source: https://github.com/felangel/bloc/blob/master/docs/src/content/docs/tutorials/flutter-weather.mdx Demonstrates how to use MockWeatherCubit and the mocktail library to stub cubit states during widget testing. This ensures the UI correctly reacts to various state transitions in a controlled environment. ```dart import 'package:bloc_test/bloc_test.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; import 'package:weather_repository/weather_repository.dart'; class MockWeatherCubit extends MockCubit implements WeatherCubit {} void main() { group('WeatherPage', () { late WeatherCubit weatherCubit; setUp(() { weatherCubit = MockWeatherCubit(); }); testWidgets('renders correctly', (tester) async { when(() => weatherCubit.state).thenReturn(const WeatherState.initial()); await tester.pumpWidget(BlocProvider.value(value: weatherCubit, child: const WeatherPage())); expect(find.byType(WeatherView), findsOneWidget); }); }); } ``` -------------------------------- ### Run Build Runner for Serialization Source: https://github.com/felangel/bloc/blob/master/docs/src/content/docs/tutorials/flutter-weather.mdx Command to trigger the build_runner tool to generate serialization and deserialization code for data models. ```bash dart run build_runner build --delete-conflicting-outputs ``` -------------------------------- ### Configure dynamic expectations in blocTest Source: https://github.com/felangel/bloc/blob/master/docs/src/content/docs/migration.mdx Updates the expect parameter in blocTest to accept a function, supporting dynamic values and Matcher objects for more flexible testing. ```dart blocTest( '...', expect: () => [MyStateA(), MyStateB()], ... ); // It can also be a `Matcher` blocTest( '...', expect: () => contains(MyStateA()), ... ); ``` -------------------------------- ### Create New Flutter Project with very_good_cli Source: https://github.com/felangel/bloc/blob/master/docs/src/content/docs/tutorials/flutter-todos.mdx Initializes a new Flutter project using the very_good_cli. This command sets up a new Flutter application with a predefined structure and best practices. ```bash flutter create --template=package "com.example.flutter_todos" ``` -------------------------------- ### Configure dynamic seed in blocTest Source: https://github.com/felangel/bloc/blob/master/docs/src/content/docs/migration.mdx Updates the blocTest configuration to use a function for the seed parameter, allowing for dynamic state initialization in version 8.0.0. ```dart blocTest( '...', seed: () => MyState(), ... ); ``` -------------------------------- ### Implement BlocObserver with BlocBase Source: https://github.com/felangel/bloc/blob/master/docs/src/content/docs/migration.mdx Updates the BlocObserver implementation to use the new BlocBase class, ensuring compatibility with both Bloc and Cubit instances in version 7.0.0. ```dart class SimpleBlocObserver extends BlocObserver { @override void onCreate(BlocBase bloc) {...} @override void onEvent(Bloc bloc, Object event) {...} @override void onChange(BlocBase bloc, Object? event) {...} @override void onTransition(Bloc bloc, Transition transition) {...} @override void onError(BlocBase bloc, Object error, StackTrace stackTrace) {...} @override void onClose(BlocBase bloc) {...} } ``` -------------------------------- ### BlocProvider: Correctly Accessing Bloc Context (Good Example) Source: https://github.com/felangel/bloc/blob/master/docs/src/content/docs/faqs.mdx Demonstrates the correct way to access a Bloc using `BlocProvider.of(context)` by ensuring the call is made within a child BuildContext, not the same context where the BlocProvider was defined. This prevents the common 'BlocProvider.of() fails to find Bloc' error. ```dart BlocProvider( create: (_) => MyBloc(), child: ChildWidget(), ) class ChildWidget extends StatelessWidget { @override Widget build(BuildContext context) { // Correct: Accessing bloc from a child context final myBloc = BlocProvider.of(context); return Container(); } ) ```