This guide introduces the BLoC pattern in Flutter and walks through an example of loading product data from an API and displaying it in a list. It covers package setup, project organization, events, states, and UI integration. Check the package documentation for the version you use before applying these examples.
What the BLoC pattern does
BLoC stands for Business Logic Component. It separates application logic from the user interface and provides a way to represent changes in application state. Keeping these responsibilities separate can make code easier to organize, test, and reuse.
Install the package
Add the dependency to pubspec.yaml and fetch packages:
dependencies:
flutter_bloc: ^8.0.0
flutter pub get
Organize the example
The example begins with a model such as Product, which holds product information such as a name, price, and image. Keep the model and BLoC code in suitable project folders. The source also proposes base event and state classes named MyEvent and MyState.
Create states for the stages of loading data—for example, initial, loading, success, and error—and an event such as GetProductEvent to request the product list. A ProductBloc handles the application logic and emits the state that the interface should display.
Load and parse API data
The example uses an HTTP request to fetch data. Check the response status code, parse the response body from JSON into product objects, and represent the results as a list. Emit a loading state while the request is in progress, a success state with the products when it completes, or an error state when it fails.
Provide the BLoC and display its states
Use BlocProvider to make ProductBloc available to a screen such as ProductListScreen. The source uses BlocConsumer to listen for state changes and build the UI. Dispatch GetProductEvent when the screen is initialized, then display each product with widgets such as ListTile, using its title, subtitle, and leading area for product details.
Version notes and other topics in the source
The article uses the phrase “Event to Stage” for an 8.0 change and says some older code may no longer work. The intended API term is unclear, so verify migration details in the documentation for the package version you use. Other topics include streams, command-based logic, IDE extensions, constants, shortcuts, comments, naming conventions, imports, file organization, beta preparation, and a product-list example. These topics receive only a brief overview.
Key points
- Keep application logic separate from widgets.
- Represent loading, success, and error as explicit states.
- Check API responses and parse JSON before displaying data.
- Use a provider to expose a BLoC and a state-aware widget to render its output.
- Test the implementation and verify version-specific behavior against the official package documentation.
For a free financial consultation with an expert, contact us on LINE.