<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Yusuf ÖZ on Medium]]></title>
        <description><![CDATA[Stories by Yusuf ÖZ on Medium]]></description>
        <link>https://medium.com/@yusufoz?source=rss-f7719623b9b4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*fwM_Xk0-vbyovSpT</url>
            <title>Stories by Yusuf ÖZ on Medium</title>
            <link>https://medium.com/@yusufoz?source=rss-f7719623b9b4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 08:53:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@yusufoz/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[A Developer’s Guide to Flutter BLoC: From Internship Project to Clean Architecture]]></title>
            <link>https://medium.com/@yusufoz/a-developers-guide-to-flutter-bloc-from-internship-project-to-clean-architecture-37c94b1eba72?source=rss-f7719623b9b4------2</link>
            <guid isPermaLink="false">https://medium.com/p/37c94b1eba72</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[mobile-development]]></category>
            <category><![CDATA[bloc-pattern]]></category>
            <dc:creator><![CDATA[Yusuf ÖZ]]></dc:creator>
            <pubDate>Thu, 14 Aug 2025 07:13:12 GMT</pubDate>
            <atom:updated>2025-08-14T07:36:01.656Z</atom:updated>
            <content:encoded><![CDATA[<p>My journey into advanced Flutter development truly began during my internship. When I joined the team, I was excited to contribute to a large, real-world application. I was soon tasked with developing a new feature, and while I was comfortable with Flutter’s basics, I quickly realized that managing data flow and state in a complex, collaborative project was a completely different challenge. The methods I was used to, like setState(), were insufficient for the level of structure and scalability required.</p><p>It was then that I was introduced to the BLoC (Business Logic Component) pattern, the standard architectural choice within our team. BLoC was presented not just as a state management tool, but as a comprehensive approach to building predictable, testable, and maintainable features. This article is a culmination of what I learned during that experience, designed to be a practical guide for any developer looking to move beyond the basics and write production-quality Flutter code.</p><h3>Why We Need More Than setState()</h3><p>In any professional software project, key objectives are maintainability, scalability, and testability. While setState() is effective for local state within a single widget, its use in complex features can lead to several architectural problems:</p><ul><li><strong>Violation of Separation of Concerns:</strong> Business logic (e.g., API calls, data validation) becomes tightly coupled with UI code. This makes the codebase difficult to read and harder for new developers to understand.</li><li><strong>Poor Testability:</strong> When logic is embedded within widgets, writing clean, fast unit tests is nearly impossible. You are forced to write slower widget tests to cover business logic.</li><li><strong>Unpredictable State Changes:</strong> In a large widget tree, state can be altered from multiple places, making it difficult to trace data flow and debug issues. This creates a fragile system where one change can have unintended consequences.</li></ul><p>The BLoC pattern directly addresses these challenges by enforcing a clear separation between the presentation layer and the business logic.</p><h3>Understanding the BLoC Pattern: The Core Components</h3><p>At its heart, BLoC is a system that ensures data flows through an application in a predictable, unidirectional way. This interaction is defined by three main concepts:</p><ol><li><strong>Events:</strong> Immutable objects representing user interactions or system triggers. They are dispatched from the UI to the BLoC. Examples: FetchDataRequested, SubmitButtonPressed.</li><li><strong>States:</strong> Immutable objects representing a part of your application’s state. The BLoC emits states, and the UI rebuilds itself in response. Examples: PageInitial, LoadInProgress, LoadSuccess, LoadFailure.</li><li><strong>Bloc/Cubit:</strong> The component that listens for Events, processes them, and emits new States. A <strong>Cubit</strong> is a simplified version of a BLoC that uses functions instead of events, making it a great choice for less complex scenarios.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rAiLOJFZ8KKCbpi50G85Pg.png" /><figcaption>BLoC Architecture</figcaption></figure><h3>A Practical Example: Fetching User Data</h3><p>Let’s build a simple, yet common feature: fetching a random user profile from a public API and displaying it. This example is perfect for beginners as it clearly shows how BLoC handles asynchronous operations and their different states.</p><h3>Step 1: Define a Simple User Model</h3><p>First, let’s create a small data class to hold our user’s information. Using Equatable helps prevent unnecessary UI rebuilds.</p><pre>// user_model.dart<br>import &#39;package:equatable/equatable.dart&#39;;<br><br>class User extends Equatable {<br>  final String name;<br>  final String email;<br>  final String pictureUrl;<br><br>  const User({required this.name, required this.email, required this.pictureUrl});<br><br>  @override<br>  List&lt;Object?&gt; get props =&gt; [name, email, pictureUrl];<br>}</pre><h3>Step 2: Define the States and Events</h3><p>Next, we’ll define all possible states for our feature and the single event that can trigger a state change.</p><pre>// user_state.dart<br>import &#39;package:equatable/equatable.dart&#39;;<br>import &#39;user_model.dart&#39;;<br><br>abstract class UserState extends Equatable {<br>  const UserState();<br>  @override<br>  List&lt;Object&gt; get props =&gt; [];<br>}<br><br>class UserInitial extends UserState {}<br>class UserLoadInProgress extends UserState {}<br>class UserLoadSuccess extends UserState {<br>  final User user;<br>  const UserLoadSuccess(this.user);<br>  @override<br>  List&lt;Object&gt; get props =&gt; [user];<br>}<br>class UserLoadFailure extends UserState {<br>  final String error;<br>  const UserLoadFailure(this.error);<br>  @override<br>  List&lt;Object&gt; get props =&gt; [error];<br>}<br>```dart<br>// user_event.dart<br>import &#39;package:equatable/equatable.dart&#39;;<br><br>abstract class UserEvent extends Equatable {<br>  const UserEvent();<br>  @override<br>  List&lt;Object&gt; get props =&gt; [];<br>}<br><br>class FetchUser extends UserEvent {}</pre><h3>Step 3: Implement the UserBloc</h3><p>This is where the magic happens. Our BLoC will listen for the FetchUser event, call the API directly, and emit the appropriate states. For this example, we’ll use the http package for the API call.</p><pre>// user_bloc.dart<br>import &#39;package:flutter_bloc/flutter_bloc.dart&#39;;<br>import &#39;package:http/http.dart&#39; as http;<br>import &#39;dart:convert&#39;;<br>import &#39;user_event.dart&#39;;<br>import &#39;user_state.dart&#39;;<br>import &#39;user_model.dart&#39;;<br><br>class UserBloc extends Bloc&lt;UserEvent, UserState&gt; {<br>  UserBloc() : super(UserInitial()) {<br>    on&lt;FetchUser&gt;((event, emit) async {<br>      emit(UserLoadInProgress());<br>      try {<br>        final response = await http.get(Uri.parse(&#39;https://randomuser.me/api/&#39;));<br>        if (response.statusCode == 200) {<br>          final data = json.decode(response.body)[&#39;results&#39;][0];<br>          final user = User(<br>            name: &#39;${data[&#39;name&#39;][&#39;first&#39;]} ${data[&#39;name&#39;][&#39;last&#39;]}&#39;,<br>            email: data[&#39;email&#39;],<br>            pictureUrl: data[&#39;picture&#39;][&#39;large&#39;],<br>          );<br>          emit(UserLoadSuccess(user));<br>        } else {<br>          emit(const UserLoadFailure(&#39;Failed to fetch user data.&#39;));<br>        }<br>      } catch (e) {<br>        emit(UserLoadFailure(e.toString()));<br>      }<br>    });<br>  }<br>}</pre><h3>Step 4: Build the UI with BlocBuilder</h3><p>Finally, we create our UI. It will be “declarative,” meaning it will simply declare what to show for each possible state.</p><pre>// user_page.dart<br>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:flutter_bloc/flutter_bloc.dart&#39;;<br>import &#39;user_bloc.dart&#39;;<br>import &#39;user_event.dart&#39;;<br>import &#39;user_state.dart&#39;;<br>import &#39;user_model.dart&#39;;<br><br>class UserPage extends StatelessWidget {<br>  const UserPage({super.key});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return BlocProvider(<br>      create: (context) =&gt; UserBloc(),<br>      child: Scaffold(<br>        appBar: AppBar(title: const Text(&#39;User Fetcher with BLoC&#39;)),<br>        body: Center(<br>          child: BlocBuilder&lt;UserBloc, UserState&gt;(<br>            builder: (context, state) {<br>              if (state is UserLoadInProgress) {<br>                return const CircularProgressIndicator();<br>              }<br>              if (state is UserLoadFailure) {<br>                return Text(state.error, style: const TextStyle(color: Colors.red));<br>              }<br>              if (state is UserLoadSuccess) {<br>                // Display the user data in a nice card<br>                return UserProfileCard(user: state.user);<br>              }<br>              // Initial State<br>              return const Text(&#39;Press the button to fetch a user!&#39;);<br>            },<br>          ),<br>        ),<br>        floatingActionButton: Builder(<br>          builder: (context) =&gt; FloatingActionButton(<br>            onPressed: () =&gt; context.read&lt;UserBloc&gt;().add(FetchUser()),<br>            child: const Icon(Icons.refresh),<br>          ),<br>        ),<br>      ),<br>    );<br>  }<br>}<br><br>class UserProfileCard extends StatelessWidget {<br>  final User user;<br>  const UserProfileCard({super.key, required this.user});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Column(<br>      mainAxisAlignment: MainAxisAlignment.center,<br>      children: [<br>        CircleAvatar(<br>          radius: 50,<br>          backgroundImage: NetworkImage(user.pictureUrl),<br>        ),<br>        const SizedBox(height: 16),<br>        Text(user.name, style: Theme.of(context).textTheme.headlineSmall),<br>        const SizedBox(height: 8),<br>        Text(user.email, style: Theme.of(context).textTheme.bodyMedium),<br>      ],<br>    );<br>  }<br>}</pre><h3>Key Principles for Production-Ready Code</h3><p>This simple example still highlights several key principles for writing professional code:</p><ol><li><strong>Clear Separation:</strong> The UI code in UserPage is completely unaware of http or JSON parsing. Its only responsibility is to render states.</li><li><strong>Predictability:</strong> The user’s journey is clearly defined by the states: Initial -&gt; Loading -&gt; Success or Failure. There are no other paths, which makes debugging straightforward.</li><li><strong>Single Responsibility:</strong> UserBloc is responsible for one thing: managing the state of the user fetching feature.</li></ol><p>As a next step in a larger project, you might introduce a “Repository” layer to sit between the BLoC and the data source (http). This further decouples your business logic from the specific implementation of data fetching, making your code even more modular and testable.</p><p>In conclusion, BLoC is far more than just a state management library; it’s an architectural pattern that promotes structure, testability, and clarity. The initial learning curve is a worthwhile investment, providing a solid foundation for building professional, scalable Flutter applications that are easy to maintain and a pleasure to work on as a team.</p><h3>References</h3><ul><li><strong>[Official BLoC Library Documentation](</strong>https://bloclibrary.dev<strong>)</strong></li><li><strong>[Bloc Library: Basics &amp; Beyond — Felix Angelov | Flutter Europe](</strong>https://www.youtube.com/watch?v=knMvKPKBzGE<strong>)</strong></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=37c94b1eba72" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>