<?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 Tech Ramakant on Medium]]></title>
        <description><![CDATA[Stories by Tech Ramakant on Medium]]></description>
        <link>https://medium.com/@tech.ramakant?source=rss-b01a13ae7644------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*mYoMfjcUej7NxmrD</url>
            <title>Stories by Tech Ramakant on Medium</title>
            <link>https://medium.com/@tech.ramakant?source=rss-b01a13ae7644------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 07:14:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tech.ramakant/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[GetX: Flutter’s All-in-One Hero!]]></title>
            <link>https://medium.com/@tech.ramakant/getx-flutters-all-in-one-hero-94e77cd1fb5c?source=rss-b01a13ae7644------2</link>
            <guid isPermaLink="false">https://medium.com/p/94e77cd1fb5c</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[apple]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[apps]]></category>
            <dc:creator><![CDATA[Tech Ramakant]]></dc:creator>
            <pubDate>Wed, 29 Jan 2025 09:03:09 GMT</pubDate>
            <atom:updated>2025-11-11T09:58:13.642Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Tired of juggling multiple packages and boilerplate code? Its time to Meet GetX — your one-stop solution for Flutter apps.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*d19s1RijXuP8mlvT" /><figcaption>Photo by <a href="https://unsplash.com/@exxteban?utm_source=medium&amp;utm_medium=referral">Esteban López</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this guide, we will not only dive into <strong>state management with GetX</strong>, but also explore its <strong>power-packed features</strong> like routing and dependency injection, and why it’s often called a Flutter developer’s <strong>Swiss Army knife</strong>!</p><h3>Why Choose GetX?</h3><p>Here is why GetX shines:</p><p>✅ <strong>State Management</strong>: Reactive and super lightweight.<br>✅ <strong>Dependency Injection</strong>: No need for InheritedWidget or Provider.<br>✅ <strong>Routing</strong>: Easy navigation without Navigator.push() boilerplate.<br>✅ <strong>Performance</strong>: Optimized for speed and memory efficiency.<br>✅ <strong>Minimal Boilerplate</strong>: Write less, achieve more!<br>✅ <strong>Community Support</strong>: Actively maintained with lots of examples.</p><h3>Step 1: Adding GetX to Your Project</h3><p>First, add GetX to your pubspec.yaml:</p><pre>dependencies:<br>  get: ^4.6.5</pre><p>Run:</p><pre>flutter pub get</pre><h3>Step 2: State Management Made Easy</h3><p><strong>Reactive State Example:</strong></p><pre>import &#39;package:get/get.dart&#39;;<br><br>class CounterController extends GetxController {<br>  var count = 0.obs; // Reactive variable<br><br>  void increment() =&gt; count++;<br>}</pre><p>Using it in the UI:</p><pre>final CounterController controller = Get.put(CounterController());<br><br>Obx(() =&gt; Text(&#39;Count: ${controller.count}&#39;));</pre><p><strong>Why it’s better:</strong></p><ul><li>No setState().</li><li>Automatically rebuilds UI on state change.</li></ul><h3>Step 3: Dependency Injection Simplified</h3><p>With GetX, forget about passing context or manually initializing controllers.</p><p><strong>Example:</strong></p><pre>class UserController extends GetxController {<br>  var userName = &#39;Guest&#39;.obs;<br><br>  void login(String name) =&gt; userName.value = name;<br>}<br><br>// Injecting it<br>Get.put(UserController());</pre><p><strong>Using it anywhere:</strong></p><pre>final userController = Get.find&lt;UserController&gt;();<br>Text(&#39;Hello, ${userController.userName}&#39;);</pre><p><strong>Benefits:</strong></p><ul><li>No need for InheritedWidget.</li><li>Controllers are globally accessible.</li></ul><h3>Step 4: Navigation Done Right</h3><p>Say goodbye to Navigator.push() boilerplate!</p><p><strong>Routing Example</strong></p><ol><li>Define routes:</li></ol><pre>final routes = [<br>  GetPage(name: &#39;/home&#39;, page: () =&gt; HomeScreen()),<br>  GetPage(name: &#39;/details&#39;, page: () =&gt; DetailsScreen()),<br>];</pre><p>2. Navigate:</p><pre>Get.toNamed(&#39;/details&#39;);</pre><p>3. Add routes in GetMaterialApp:</p><pre>GetMaterialApp(<br>  initialRoute: &#39;/home&#39;,<br>  getPages: routes,<br>);</pre><p><strong>What makes it awesome:</strong></p><ul><li>Supports dynamic arguments: Get.toNamed(&#39;/details&#39;, arguments: &#39;Hello!&#39;).</li><li>No need for context.</li></ul><h3>Step 5: Middleware and SnackBars</h3><h4>Middleware</h4><p>Add custom logic before navigation (like authentication):</p><pre>class AuthMiddleware extends GetMiddleware {<br>  @override<br>  RouteSettings? redirect(String? route) {<br>    return isLoggedIn ? null : RouteSettings(name: &#39;/login&#39;);<br>  }<br>}</pre><h4>SnackBars</h4><p>Simple, customizable SnackBars:</p><pre>Get.snackbar(<br>  &#39;Hello!&#39;,<br>  &#39;Welcome to GetX!&#39;,<br>  snackPosition: SnackPosition.BOTTOM,<br>);</pre><h3>Packed Features of GetX</h3><ol><li><strong>Dialogues</strong>:</li></ol><pre>Get.defaultDialog(<br>  title: &#39;Warning&#39;,<br>  content: Text(&#39;This action is irreversible.&#39;),<br>);</pre><p>2. <strong>Theme Management</strong>:</p><pre>Get.changeTheme(ThemeData.dark());</pre><p><strong>3. Workers</strong> (React to changes):</p><pre>ever(controller.count, (_) =&gt; print(&#39;Count changed!&#39;));</pre><h3>Advantages Over Alternatives</h3><ul><li><strong>Provider</strong>: Less boilerplate, no context passing.</li><li><strong>Bloc</strong>: Simpler API, no streams.</li><li><strong>Redux</strong>: Faster and lightweight.</li><li><strong>Built-in Extras</strong>: Routing, SnackBars, Dialogues — all in one package.</li></ul><h3><strong>Disadvantages Over Alternatives</strong></h3><p>While <strong>GetX</strong> is powerful, it is not always the best choice. Here’s why</p><ul><li><strong>Not Officially Recommended by Flutter</strong> — Unlike <strong>Provider</strong> and <strong>Riverpod</strong>, which are backed by the Flutter team, GetX is a third-party package.</li><li><strong>Magic-Like Behavior</strong> — The simplicity of GetX can sometimes <strong>hide important Flutter concepts</strong>, making debugging harder for beginners.</li><li><strong>Overuse of </strong><strong>.obs Can Lead to Bad Practices</strong> – If used incorrectly, reactive variables can cause unnecessary rebuilds.</li><li><strong>Riverpod is Safer and More Scalable</strong> — Riverpod’s approach avoids <strong>unintended memory leaks</strong> and offers <strong>compile-time safety</strong>, unlike GetX’s Get.put().</li><li><strong>Bloc is More Structured for Large Apps</strong> — If your app requires <strong>complex business logic</strong>, <strong>Bloc or Cubit</strong> might be a better choice than GetX.</li></ul><p><strong>When to Use GetX?</strong><br>✅ Great for <strong>small to medium</strong> apps<br>✅ Best for <strong>fast MVP development</strong><br>✅ Ideal when you need <strong>state management + navigation + dependency injection in one package</strong></p><p><strong>When to Avoid GetX?</strong><br>❌ If working on a <strong>large enterprise app</strong><br>❌ When you need <strong>strict state management rules</strong><br>❌ If you prefer <strong>Flutter team-recommended solutions like Provider or Riverpod</strong></p><h3>Conclusion</h3><p>GetX is an <strong>incredible tool</strong> that simplifies <strong>state management, navigation, and dependency injection</strong> in one package. However, like every tool, it has its <strong>pros and cons</strong>. If you’re looking for <strong>rapid development</strong> and <strong>minimal boilerplate</strong>, GetX is a fantastic choice. But for larger projects, <strong>Provider, Riverpod, or Bloc</strong> might offer <strong>better scalability and maintainability</strong>.</p><p>Ready to dive deeper? Clap on this article and share it with fellow developers. Let’s make Flutter development <strong>fun and efficient</strong> with GetX!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=94e77cd1fb5c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[REST in Peace: Star Wars Meets GraphQL + Flutter!]]></title>
            <link>https://medium.com/@tech.ramakant/rest-in-peace-star-wars-meets-graphql-flutter-54c1e11e8f7f?source=rss-b01a13ae7644------2</link>
            <guid isPermaLink="false">https://medium.com/p/54c1e11e8f7f</guid>
            <category><![CDATA[apps]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[apple]]></category>
            <dc:creator><![CDATA[Tech Ramakant]]></dc:creator>
            <pubDate>Tue, 19 Nov 2024 06:05:14 GMT</pubDate>
            <atom:updated>2025-08-26T09:16:33.077Z</atom:updated>
            <content:encoded><![CDATA[<p>Tired of REST APIs showering you with unnecessary data or leaving out that one field you desperately need? Enter <strong>GraphQL</strong> — the superhero of APIs. It is precise, efficient, and makes API consumption a breeze. In this tutorial, we will build a <strong>Star Wars character app</strong> using Flutter and GraphQL. Yes, you will feel like a Jedi by the end.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YiQ7oiPb0qHy4vDA" /><figcaption>Photo by <a href="https://unsplash.com/@diane_soko?utm_source=medium&amp;utm_medium=referral">Diane Picchiottino</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Why GraphQL?</h3><p>GraphQL is not just a shiny buzzword — it is a better way to talk to APIs:</p><ul><li><strong>Ask and Receive</strong>: Need just names and ages? Done. No extra baggage.</li><li><strong>One Endpoint</strong>: It is a buffet; grab what you need. No running to different counters.</li><li><strong>API Upgrades? No Problem!</strong>: Your older apps will still work.</li></ul><p>Sounds cool? Let’s make it even cooler by creating an app!</p><h3>Project: Star Wars Character Fetcher</h3><p>A simple app to fetch and display Star Wars characters. Follow these steps, and may the code be with you.</p><h3>1. Setting Up Your Flutter Project</h3><p>Start by creating your Flutter project:</p><pre>flutter create graphql_demo_app  <br>cd graphql_demo_app</pre><p>Then, add the graphql_flutter dependency:</p><pre>flutter pub add graphql_flutter</pre><p>This package is our lightsaber — it’ll help us connect to a GraphQL API.</p><h3>2. Initialize the GraphQL Client</h3><p>To communicate with GraphQL, we need a client. Here’s how you set it up:</p><p>In main.dart, initialize the GraphQL client:</p><pre>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:graphql_demo_app/star_wars_characters.dart&#39;;<br>import &#39;package:graphql_flutter/graphql_flutter.dart&#39;;<br><br>void main() async {<br>  await initHiveForFlutter(); // Needed for caching data.<br>  runApp(const MyApp());<br>}<br><br>class MyApp extends StatelessWidget {<br>  const MyApp({super.key});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    final client = ValueNotifier(<br>      GraphQLClient(<br>        link: HttpLink(<br>            &#39;https://swapi-graphql.netlify.app/.netlify/functions/index&#39;),<br>        // API URL<br>        cache: GraphQLCache(store: HiveStore()),<br>      ),<br>    );<br><br>    return GraphQLProvider(<br>      client: client,<br>      child: MaterialApp(<br>        title: &#39;Star Wars GraphQL Demo&#39;,<br>        theme: ThemeData(primarySwatch: Colors.blue),<br>        home: const StarWarsCharacters(), // Our app screen.<br>      ),<br>    );<br>  }<br>}</pre><h4>What’s Happening Here?</h4><ul><li><strong>HttpLink</strong>: Points to our Star Wars GraphQL API.</li><li><strong>GraphQLCache</strong>: Caches API responses for better performance.</li><li><strong>GraphQLProvider</strong>: Provides the client to all child widgets.</li></ul><h3>3. Fetch Data with a GraphQL Query</h3><p>Here comes the magic — fetching data with a query.</p><p>Create a new file, star_wars_characters.dart, and add this:</p><pre>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:graphql_flutter/graphql_flutter.dart&#39;;<br><br>class StarWarsCharacters extends StatelessWidget {<br>  // Our GraphQL query to fetch character data.<br>  final String query = &quot;&quot;&quot;  <br>    query {  <br>      allPeople {  <br>        people {  <br>          name  <br>          gender  <br>        }  <br>      }  <br>    }  <br>  &quot;&quot;&quot;;<br><br>  const StarWarsCharacters({super.key});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(title: const Text(&#39;Star Wars Characters&#39;)),<br>      body: Query(<br>        options: QueryOptions(document: gql(query)),  // Pass the query here.<br>        builder: (result, {refetch, fetchMore}) {<br>          if (result.isLoading) return const Center(child: CircularProgressIndicator());<br>          if (result.hasException) return Text(&#39;Error: ${result.exception.toString()}&#39;);<br><br>          // Extract characters from the result.<br>          final characters = result.data![&#39;allPeople&#39;][&#39;people&#39;];<br><br>          return ListView.builder(<br>            itemCount: characters.length,<br>            itemBuilder: (_, index) =&gt; ListTile(<br>              title: Text(characters[index][&#39;name&#39;]),<br>              subtitle: Text(&#39;Gender: ${characters[index][&#39;gender&#39;]}&#39;),<br>            ),<br>          );<br>        },<br>      ),<br>    );<br>  }<br>}</pre><h4>What’s Happening Here?</h4><ul><li><strong>Query Widget</strong>: Executes the GraphQL query and manages states like loading or errors.</li><li><strong>result.data</strong>: Contains the fetched data.</li><li><strong>ListView.builder</strong>: Displays characters in a scrollable list.</li></ul><h3>4. Run the App</h3><p>Fire up your app and see it in action:</p><pre>flutter run</pre><p>You should see a list of Star Wars characters with their names and genders.</p><h3>GraphQL vs REST</h3><p><strong>Data Fetching</strong></p><ul><li>🟢 <strong>GraphQL</strong>: Get only what you need — no more, no less!</li><li>🔴 <strong>REST</strong>: Over-fetch or under-fetch data, often leading to inefficiencies.</li></ul><p><strong>Flexibility</strong></p><ul><li>🟢 <strong>GraphQL</strong>: A single endpoint handles all your queries like a pro.</li><li>🔴 <strong>REST</strong>: Requires juggling multiple endpoints — messy and complicated.</li></ul><p><strong>Versioning</strong></p><ul><li>🟢 <strong>GraphQL</strong>: Makes changes without breaking existing clients.</li><li>🔴 <strong>REST</strong>: Painful upgrades with breaking changes when new versions roll out.</li></ul><p>With GraphQL, your API consumption becomes <strong>smarter, faster</strong>, and way cooler. Why settle for old-school REST when GraphQL is here to save the day?</p><h3>What’s Next?</h3><ol><li>Add <strong>mutations</strong> to create or update data.</li><li>Experiment with <strong>subscriptions</strong> for real-time updates.</li><li>Apply GraphQL to your own backend projects!</li></ol><h3>Wrapping Up</h3><p>Congratulations — you have just built your first GraphQL-powered Flutter app! With a single query, we brought Star Wars characters to life. You now know how to:</p><ul><li>Set up a <strong>GraphQL client</strong> in Flutter.</li><li>Fetch data with precise queries.</li><li>Display API results in a sleek, efficient app.</li></ul><p>If you’re ready to level up further, explore <strong>mutations</strong> for creating/updating data or <strong>subscriptions</strong> for real-time magic.</p><p>Check out the full source code for this project on GitHub: <a href="https://github.com/tech-ramakant/graphql_demo_app">Star Wars GraphQL Demo</a>.<br>If you liked this guide, don’t forget to <strong>follow</strong>, <strong>clap</strong>, and share it with your fellow devs. Let’s keep pushing the boundaries of Flutter together!</p><p>GraphQL makes API consumption faster, easier, and way cooler.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=54c1e11e8f7f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[BLoC Journey to the Next Milestone : Crafting a Task Manager App with DIO and API Integration]]></title>
            <link>https://medium.com/@tech.ramakant/bloc-journey-to-the-next-milestone-crafting-a-task-manager-app-with-dio-and-api-integration-eef60a51391a?source=rss-b01a13ae7644------2</link>
            <guid isPermaLink="false">https://medium.com/p/eef60a51391a</guid>
            <category><![CDATA[apple]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[apps]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Tech Ramakant]]></dc:creator>
            <pubDate>Tue, 12 Nov 2024 10:50:52 GMT</pubDate>
            <atom:updated>2025-08-20T13:34:29.650Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello, Flutter enthusiasts!</p><p>If you’ve been following my journey through BLoC, you’re probably familiar with the fundamentals by now. In previous articles, I’ve discussed <a href="https://medium.com/@tech.ramakant/bloc-too-tough-start-with-cubit-for-a-smoother-ride-2a437435d3e5"><strong>BloC Too Tough? Start with Cubit for a Smoother Ride</strong></a> and <a href="https://medium.com/@tech.ramakant/smooth-transition-from-cubit-to-bloc-7b12e1d4d8ef"><strong>Smooth Transition from Cubit to BLoC</strong></a>. But today, we are about to take our BLoC journey to the next milestone!</p><p>In this article, we will be building a fully functional <strong>Task Manager App</strong>. But here is the twist my for my readers: we will be leveling-up by integrating <strong>API calls</strong> using <strong>DIO</strong> for networking, and we will tackle <strong>state management</strong> with <strong>BLoC</strong>. Sounds crazy, right? Let’s get started!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0keylsIA_aEbXPu-" /><figcaption>Photo by <a href="https://unsplash.com/@averieclaire?utm_source=medium&amp;utm_medium=referral">averie woodard</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Why BLoC and DIO?</h3><p>Before we dive into the code, let’s take a moment to understand importance of <strong>BLoC</strong> and <strong>DIO</strong>:</p><ul><li><strong>BLoC (Business Logic Component)</strong>: As name says it helps separate the UI from the business logic. This makes your app cleaner, more maintainable, and scalable. If you haven’t already, check out my earlier articles to get comfortable with BLoC (<a href="https://medium.com/@tech.ramakant/bloc-too-tough-start-with-cubit-for-a-smoother-ride-2a437435d3e5"><strong>BloC Too Tough? Start with Cubit for a Smoother Ride</strong></a> and <a href="https://medium.com/@tech.ramakant/smooth-transition-from-cubit-to-bloc-7b12e1d4d8ef"><strong>Smooth Transition from Cubit to BLoC</strong></a>).</li><li><strong>DIO</strong>: DIO is an HTTP client for Flutter that makes network requests easy. It comes with lots of powerful features like interceptors, error handling, and more. It’s perfect for integrating APIs calls into your app.</li></ul><p>For our <strong>Task Manager App</strong>, we’ll use the <a href="https://dummyjson.com/docs/todos"><strong>DummyJSON API</strong></a> to fetch a list of tasks.</p><h3>Step 1: Setting Up the Project</h3><p>Start by creating a new Flutter project (or use an existing one). If you haven’t set up your dependencies yet, add these to your pubspec.yaml:</p><pre>dependencies:<br>  flutter:<br>    sdk: flutter<br>  flutter_bloc: ^8.0.1<br>  dio: ^5.0.0<br>  json_annotation: ^4.6.0<br>  equatable: ^2.0.3<br><br><br>dev_dependencies:<br>  build_runner: ^2.0.0<br>  json_serializable: ^6.0.0</pre><p>Now, run flutter pub get to install the packages.</p><h3>Step 2: Create the API Client with DIO</h3><p>Let’s start by creating a service that will handle our API requests. Create a folder lib/data/api/ and inside that, create a file dio_client.dart:</p><pre>import &#39;package:dio/dio.dart&#39;;<br><br>class DioClient {<br>  final Dio _dio = Dio(BaseOptions(<br>    baseUrl: &#39;https://dummyjson.com/&#39;,<br>    connectTimeout: const Duration(milliseconds: 5000),<br>    receiveTimeout: const Duration(milliseconds: 3000),<br>  ));<br><br>  Dio get dio =&gt; _dio;<br>}</pre><h3>Explanation:</h3><ul><li><strong>Dio Client</strong>: This is the class that will handle network requests. Here, we have defined a getTasks method that fetches the task data from the API.</li><li><strong>Base URL &amp; Timeouts</strong>: We specify the base URL for the API and set timeouts for the requests.</li></ul><h3>Step 3: Create Models for Task Data</h3><p>In the lib/data/models/ folder, create task_model.dart:</p><pre>import &#39;package:json_annotation/json_annotation.dart&#39;;<br><br>part &#39;task_model.g.dart&#39;;<br><br>@JsonSerializable()<br>class TaskModel {<br>  final int id;<br>  final String todo;<br>  final bool completed;<br><br>  TaskModel({required this.id, required this.todo, required this.completed});<br><br>  factory TaskModel.fromJson(Map&lt;String, dynamic&gt; json) =&gt;<br>      _$TaskModelFromJson(json);<br>  Map&lt;String, dynamic&gt; toJson() =&gt; _$TaskModelToJson(this);<br>}</pre><p>Run flutter pub run build_runner build to generate the necessary code for JSON serialization.</p><h3>Explanation:</h3><ul><li><strong>Task Model</strong>: This represents the data structure of a task.</li><li><strong>JSON Serializable</strong>: We use the json_annotation package to easily convert JSON data into Dart objects.</li></ul><h3>Step 4: Create the BLoC for Managing State</h3><p>In the lib/bloc/ folder, create the following files:</p><ol><li><strong>task_event.dart</strong>:</li></ol><pre>abstract class TaskEvent {}<br><br>class FetchTasks extends TaskEvent {}</pre><p><strong>2. task_state.dart</strong>:</p><pre>abstract class TaskState {}<br><br>class TaskInitial extends TaskState {}<br><br>class TaskLoading extends TaskState {}<br><br>class TaskLoaded extends TaskState {<br>  final List&lt;TaskModel&gt; tasks;<br>  TaskLoaded({required this.tasks});<br>}<br><br>class TaskError extends TaskState {<br>  final String errorMessage;<br>  TaskError({required this.errorMessage});<br>}</pre><p><strong>3. task_bloc.dart</strong>:</p><pre>import &#39;package:dio/dio.dart&#39;;<br>import &#39;package:flutter_bloc/flutter_bloc.dart&#39;;<br>import &#39;package:task_manager_app_with_bloc/bloc/task_event.dart&#39;;<br>import &#39;package:task_manager_app_with_bloc/bloc/task_state.dart&#39;;<br><br>import &#39;../data/model/task_model.dart&#39;;<br><br>class TaskBloc extends Bloc&lt;TaskEvent, TaskState&gt; {<br>  final Dio _dio;<br><br>  TaskBloc(this._dio) : super(TaskInitial()) {<br>    // Register the FetchTasks event handler<br>    on&lt;FetchTasks&gt;(_onFetchTasks);<br>  }<br><br>  // Handler function for FetchTasks event<br>  Future&lt;void&gt; _onFetchTasks(FetchTasks event, Emitter&lt;TaskState&gt; emit) async {<br>    emit(TaskLoading()); // Emit loading state<br><br>    try {<br>      // Example API call to fetch tasks<br>      final response = await _dio.get(&#39;https://dummyjson.com/todos&#39;);<br><br>      if (response.statusCode == 200) {<br>        // Assuming response data contains a list of tasks<br>        final tasks = (response.data[&#39;todos&#39;] as List&lt;dynamic&gt;)<br>            .map((json) =&gt; TaskModel.fromJson(json))<br>            .toList();<br><br>        emit(TaskLoaded(tasks: tasks)); // Emit loaded state with tasks<br>      } else {<br>        emit(TaskError(<br>          errorMessage: &#39;Failed to load tasks&#39;,<br>        ));<br>      }<br>    } catch (e) {<br>      emit(TaskError(errorMessage: &#39;An error occurred while fetching tasks&#39;));<br>    }<br>  }<br>}</pre><h3>Explanation:</h3><ul><li><strong>Task BLoC</strong>: This class listens to events like FetchTasks, fetches data from the API using the DioClient, and emits different states (loading, success, or error).</li><li><strong>Event &amp; State</strong>: The FetchTasks event triggers data fetching, and the states (TaskLoading, TaskLoaded, and TaskError) represent the app&#39;s UI state.</li></ul><h3>Step 5: Building the UI</h3><p>Now, let’s build the UI to display the tasks. In lib/ui/, create a file task_screen.dart:</p><pre>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:flutter_bloc/flutter_bloc.dart&#39;;<br><br>import &#39;../bloc/task_bloc.dart&#39;;<br>import &#39;../bloc/task_state.dart&#39;;<br><br>class TaskScreen extends StatelessWidget {<br>  const TaskScreen({super.key});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(<br>        title: const Text(&#39;Task Manager&#39;),<br>      ),<br>      body: BlocBuilder&lt;TaskBloc, TaskState&gt;(<br>        builder: (context, state) {<br>          if (state is TaskLoading) {<br>            return const Center(child: CircularProgressIndicator());<br>          } else if (state is TaskLoaded) {<br>            return ListView.builder(<br>              itemCount: state.tasks.length,<br>              itemBuilder: (context, index) {<br>                final task = state.tasks[index];<br>                return ListTile(<br>                  title: Text(task.todo),<br>                  trailing: Icon(<br>                    task.completed ? Icons.check_circle : Icons.circle,<br>                    color: task.completed ? Colors.green : Colors.grey,<br>                  ),<br>                );<br>              },<br>            );<br>          } else if (state is TaskError) {<br>            return Center(child: Text(&#39;Error: ${state.errorMessage}&#39;));<br>          }<br>          return const Center(child: Text(&#39;No tasks found.&#39;));<br>        },<br>      ),<br>    );<br>  }<br>}</pre><h3>Explanation:</h3><ul><li><strong>Task Screen</strong>: This widget listens for changes in the BLoC’s state and updates the UI accordingly. It shows a loading indicator, the list of tasks, or an error message depending on the state.</li></ul><h3>Step 6: Setting Up the Main Entry Point</h3><p>Finally, in lib/main.dart, set up your app to use the BLoC:</p><pre>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:flutter_bloc/flutter_bloc.dart&#39;;<br>import &#39;package:task_manager_app_with_bloc/ui/task_screen.dart&#39;;<br><br>import &#39;bloc/task_bloc.dart&#39;;<br>import &#39;bloc/task_event.dart&#39;;<br>import &#39;data/api/dio_client.dart&#39;;<br><br>void main() {<br>  runApp(const MyApp());<br>}<br><br>class MyApp extends StatelessWidget {<br>  const MyApp({super.key});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return BlocProvider(<br>      create: (context) =&gt; TaskBloc(DioClient().dio)..add(FetchTasks()),<br>      child: MaterialApp(<br>        title: &#39;Flutter Task Manager&#39;,<br>        theme: ThemeData(primarySwatch: Colors.blue),<br>        home: const TaskScreen(),<br>      ),<br>    );<br>  }<br>}</pre><h3>Explanation:</h3><ul><li><strong>BlocProvider</strong>: This initializes the TaskBloc and triggers the FetchTasks event when the app starts.</li><li><strong>TaskScreen</strong>: This is the main screen of the app, where tasks will be displayed.</li></ul><h3>Conclusion</h3><p>And there you have it! We’ve successfully leveled-up our BLoC journey by building a <strong>Task Manager App</strong> with API integration using <strong>DIO</strong>. This app allows us to fetch tasks from an external API, manage state with BLoC, and display the data cleanly using Flutter.</p><h3>Check Out the Source Code!</h3><p>Feel free to check out the full source code on my <a href="https://github.com/tech-ramakant/task_manager_app_with_bloc">GitHub</a>. Explore, play with it, and make it your own! If you find this helpful, don’t forget to <strong>clap</strong> and <strong>follow</strong> me for more exciting Flutter tutorials and updates! Stay tuned!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eef60a51391a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Clean Architecture in Flutter: Keeping Your Code Squeaky Clean!]]></title>
            <link>https://medium.com/@tech.ramakant/clean-architecture-in-flutter-keeping-your-code-squeaky-clean-c77aa6241d96?source=rss-b01a13ae7644------2</link>
            <guid isPermaLink="false">https://medium.com/p/c77aa6241d96</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[apple]]></category>
            <category><![CDATA[apps]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Tech Ramakant]]></dc:creator>
            <pubDate>Sat, 09 Nov 2024 20:42:30 GMT</pubDate>
            <atom:updated>2025-08-19T07:43:22.697Z</atom:updated>
            <content:encoded><![CDATA[<h3>Clean Architecture in Flutter: Keeping Your Code Clean!</h3><p>Imagine moving into a house where the kitchen’s in the bathroom, the bed’s in the garage, and the living room is — wait for it — upstairs in the attic. Confusing, right? Just like in life, when everything is placed in the wrong area, working in that environment becomes disorganize. This is where <strong>Clean Architecture</strong> comes in, target to keep your app source code organized, testable, and sane.</p><p>So, what is Clean Architecture all about, and why should we care? Let us dive in and look at it with some real-life and Flutter examples.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*I2R0fyF8RiMWxF5W" /><figcaption>Photo by <a href="https://unsplash.com/@towfiqu999999?utm_source=medium&amp;utm_medium=referral">Towfiqu barbhuiya</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Why Clean Architecture?</h3><p>Clean Architecture is a way of organizing code that <strong>separates codes </strong>into distinct layers, so each part of your app is responsible for just one thing and does not interfere with the others. So these approach:</p><ul><li>Makes it easier to test and debug,</li><li>Improves flexibility and scalability, and</li><li>Keeps code clean and organized.</li></ul><p>Here is a four main layers in Clean Architecture:</p><ol><li><strong>Entities (Core layer)</strong>: The business logic or rules of your app.</li><li><strong>Use Cases (Application layer)</strong>: Coordinates the app’s tasks.</li><li><strong>Repository (Interface layer)</strong>: Defines the data operations.</li><li><strong>UI / Presentation</strong>: The visible part — where your widgets live.</li></ol><h3>Layer Breakdown (With Real-Life Analogy)</h3><p>Let’s taeke scenario an online coffee ordering app. In real life, you might have:</p><ul><li><strong>The Coffee Recipes (Entities)</strong>: The types of coffee you can order — Latte, Espresso, etc.</li><li><strong>The Barista Instructions (Use Cases)</strong>: Steps the barista follows to make the coffee.</li><li><strong>The Storage (Repository)</strong>: Where the ingredients come from, whether that is a cupboard or an online supplier.</li><li><strong>The Menu (UI)</strong>: The interface where customers order their coffee.</li></ul><p>In a Clean Architecture setup, each of these has its place. The UI doesn’t need to know where the beans come from, and the storage doesn’t care what the menu looks like.</p><h3>Clean Architecture in Flutter</h3><p>Let’s take a practical look with Flutter code examples. Imagine an app that fetches coffee types and displays them to the user. Without Clean Architecture, you might throw all the code into one file, mixing your UI with API calls and logic, like this:</p><h3>Bad Example: No Clean Architecture</h3><pre>class CoffeePage extends StatelessWidget {<br>  Future&lt;List&lt;String&gt;&gt; fetchCoffeeTypes() async {<br>    // Simulating an API call<br>    await Future.delayed(Duration(seconds: 2));<br>    return [&#39;Espresso&#39;, &#39;Latte&#39;, &#39;Cappuccino&#39;];<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return FutureBuilder(<br>      future: fetchCoffeeTypes(),<br>      builder: (context, snapshot) {<br>        if (snapshot.connectionState == ConnectionState.waiting) {<br>          return CircularProgressIndicator();<br>        } else if (snapshot.hasData) {<br>          return ListView(<br>            children: snapshot.data!.map((coffee) =&gt; Text(coffee)).toList(),<br>          );<br>        } else {<br>          return Text(&#39;Failed to load coffee types&#39;);<br>        }<br>      },<br>    );<br>  }<br>}</pre><p><strong>What’s wrong?</strong></p><ul><li>The API call is mixed into the UI. If you wanted to switch from a local list to a network call or add caching, you’d be in for a mess.</li><li>Testing? Forget about it — you’d have to mock the whole widget to test the fetching logic.</li></ul><p>Now, let’s Clean Architecture-ify this app!</p><h3>Step 1: Entities Layer — The Core</h3><p>The <strong>Entities</strong> layer contains the core data structure — in our case, a Coffee class that represents each coffee type.</p><pre>class Coffee {<br>  final String name;<br><br>  Coffee(this.name);<br>}</pre><h3>Step 2: Use Cases Layer — The Brain</h3><p>The <strong>Use Cases</strong> layer contains the logic to get coffee types. This layer doesn’t care <em>where</em> the data comes from; it just says what should be done.</p><pre>import &#39;../entities/coffee.dart&#39;;<br><br>class GetCoffeeTypes {<br>  final CoffeeRepository repository;<br><br>  GetCoffeeTypes(this.repository);<br><br>  Future&lt;List&lt;Coffee&gt;&gt; call() async {<br>    return await repository.fetchCoffeeTypes();<br>  }<br>}</pre><h3>Step 3: Repository Layer — The Data Connector</h3><p>The <strong>Repository</strong> layer acts as the middleman between the Use Cases and the actual data sources. Here’s where we define an interface and add our data fetching logic.</p><pre>import &#39;../../domain/entities/coffee.dart&#39;;<br><br>abstract class CoffeeRepository {<br>  Future&lt;List&lt;Coffee&gt;&gt; fetchCoffeeTypes();<br>}<br><br>// Implementation of CoffeeRepository, fetching data locally for now<br>class LocalCoffeeRepository implements CoffeeRepository {<br>  @override<br>  Future&lt;List&lt;Coffee&gt;&gt; fetchCoffeeTypes() async {<br>    await Future.delayed(Duration(seconds: 2));<br>    return [Coffee(&#39;Espresso&#39;), Coffee(&#39;Latte&#39;), Coffee(&#39;Cappuccino&#39;)];<br>  }<br>}</pre><p>If we decide to fetch from an API instead, we’d create an ApiCoffeeRepository implementing the same CoffeeRepository interface. This keeps our app flexible and easy to update.</p><h3>Step 4: Presentation Layer — The Face of the App</h3><p>Finally, we have the <strong>Presentation</strong> layer, which takes care of the UI. The UI only talks to the Use Cases layer and has no idea about data fetching or storage.</p><pre>import &#39;package:flutter/material.dart&#39;;<br><br>import &#39;../../domain/entities/coffee.dart&#39;;<br>import &#39;../../domain/usecases/get_coffee_types.dart&#39;;<br><br>class CoffeePage extends StatelessWidget {<br>  final GetCoffeeTypes getCoffeeTypes;<br><br>  const CoffeePage(this.getCoffeeTypes, {super.key});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(<br>        title: const Text(<br>          &#39;Available Coffee Types&#39;,<br>          style: TextStyle(color: Colors.white),<br>        ),<br>        backgroundColor: Colors.blue,<br>      ),<br>      body: FutureBuilder&lt;List&lt;Coffee&gt;&gt;(<br>        future: getCoffeeTypes(),<br>        builder: (context, snapshot) {<br>          if (snapshot.connectionState == ConnectionState.waiting) {<br>            return const Center(child: CircularProgressIndicator());<br>          } else if (snapshot.hasData) {<br>            return ListView(<br>              children: snapshot.data!<br>                  .map((coffee) =&gt; Column(<br>                        mainAxisAlignment: MainAxisAlignment.start,<br>                        crossAxisAlignment: CrossAxisAlignment.start,<br>                        children: [<br>                          Padding(<br>                            padding: const EdgeInsets.all(8.0),<br>                            child: Text(<br>                              coffee.name,<br>                              style: const TextStyle(color: Colors.blue),<br>                            ),<br>                          ),<br>                          const Divider(<br>                            color: Colors.blueGrey,<br>                          ),<br>                        ],<br>                      ))<br>                  .toList(),<br>            );<br>          } else {<br>            return const Text(&#39;Failed to load coffee types&#39;);<br>          }<br>        },<br>      ),<br>    );<br>  }<br>}</pre><h3>Wrapping It All Up</h3><p>In your main function or dependency injection setup, you’d initialize everything like this:</p><pre>import &#39;package:flutter/material.dart&#39;;<br><br>import &#39;../presentation/pages/coffee_page.dart&#39;;<br>import &#39;../data/repository/coffee_repo.dart&#39;;<br>import &#39;../domain/usecases/get_coffee_types.dart&#39;;<br><br>void main() {<br>  final repository = LocalCoffeeRepository();<br>  final getCoffeeTypes = GetCoffeeTypes(repository);<br><br>  runApp(MaterialApp(<br>    title: &#39;Flutter Demo&#39;,<br>    theme: ThemeData(<br>      colorScheme: ColorScheme.fromSeed(seedColor: Colors.blue),<br>      useMaterial3: true,<br>    ),<br>    home: CoffeePage(getCoffeeTypes),<br>  ));<br><br>}</pre><h3>Why Clean Architecture Rocks</h3><p>Here’s why this setup is so much better:</p><ul><li><strong>Easier Testing</strong>: Each layer can be tested independently. You can test GetCoffeeTypes without setting up the UI, for example.</li><li><strong>Swappable Data Sources</strong>: Need to switch from local to API? Just create a new repository implementation without changing any UI code.</li><li><strong>Separation of Concerns</strong>: Each class and function does one job, making your code easier to read and debug.</li></ul><h3>Final Thoughts</h3><p>Clean Architecture may seem a bit much at first, but once you try it, you’ll wonder how you ever lived without it. It’s like moving from a junk drawer to labeled bins — you might have to do a bit of setup, but after that, it’s smooth sailing. You’ll feel less overwhelmed, and debugging will become a whole lot easier.</p><p><strong>Want to see the full code?</strong> Check out the complete project on my <a href="https://github.com/tech-ramakant/clean_architecture_sample">GitHub here</a> and feel free to play around with it.</p><p>If you enjoyed this guide, please don’t forget to give it a clap and hit that follow button to stay in the loop with more Flutter tips. Happy coding, and keep it clean!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c77aa6241d96" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering SOLID Principles in Flutter: Coding Wisdom Made Easy!]]></title>
            <link>https://medium.com/@tech.ramakant/mastering-solid-principles-in-flutter-coding-wisdom-made-easy-4f17264d290e?source=rss-b01a13ae7644------2</link>
            <guid isPermaLink="false">https://medium.com/p/4f17264d290e</guid>
            <category><![CDATA[apps]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[apple]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Tech Ramakant]]></dc:creator>
            <pubDate>Wed, 06 Nov 2024 05:22:14 GMT</pubDate>
            <atom:updated>2024-11-06T05:22:14.018Z</atom:updated>
            <content:encoded><![CDATA[<p>Imagine you’re running a coffee shop. You’re the barista, the chef, the cashier, and even the one entertaining guests with bad dad jokes. Pretty soon, your shop is in chaos. That’s how your Flutter app feels when you try to do everything without proper guidelines.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mT1N7s3Vu4GUJeT0" /><figcaption>Photo by <a href="https://unsplash.com/@picsbyjameslee?utm_source=medium&amp;utm_medium=referral">James Lee</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The <strong>SOLID principles</strong> are here to save your app (and your sanity). They’re like five golden rules that make your code cleaner, easier to manage, and less likely to blow up in your face when you make changes. Let’s explore them with some fun real-life analogies and code snippets!</p><h3>What Are SOLID Principles?</h3><p>SOLID stands for:</p><ul><li><strong>S</strong>: Single Responsibility Principle (SRP)</li><li><strong>O</strong>: Open/Closed Principle (OCP)</li><li><strong>L</strong>: Liskov Substitution Principle (LSP)</li><li><strong>I</strong>: Interface Segregation Principle (ISP)</li><li><strong>D</strong>: Dependency Inversion Principle (DIP)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/464/1*kRu91eZk6QPQeyAcv5NFug.gif" /></figure><p>Let’s break these down with some humor, real-life situations, and how they apply to Flutter.</p><h3>1. Single Responsibility Principle (SRP)</h3><p><strong>The Problem</strong>: Imagine hiring a clown for a party who also wants to bake the cake, play the DJ, and officiate the wedding. It won’t end well. In coding terms, this means having one class do too much, making your code hard to manage and debug.</p><p><strong>The Fix</strong>: A class should have <strong>one responsibility</strong> — just like the clown should stick to clowning.</p><p><strong>In Flutter</strong>: Here’s what <strong>not</strong> to do:</p><pre>class UserProfile {<br>  void fetchUserData() {<br>    // Fetch user data from the API<br>  }<br><br>  void authenticateUser() {<br>    // Handle user authentication<br>  }<br><br>  Widget buildProfilePage() {<br>    // Build UI elements<br>    return Text(&#39;Profile Page&#39;);<br>  }<br>}</pre><p><strong>What’s wrong?</strong><br>This class is doing way too much: fetching data, handling authentication, and building the UI. If you need to change one thing, you risk breaking everything else.</p><p><strong>The SRP Fix</strong>:</p><pre>class UserService {<br>  void fetchUserData() {<br>    // Fetch user data from the API<br>  }<br>}<br><br>class AuthService {<br>  void authenticateUser() {<br>    // Handle user authentication<br>  }<br>}<br><br>class UserProfileWidget extends StatelessWidget {<br>  @override<br>  Widget build(BuildContext context) {<br>    return Text(&#39;Profile Page&#39;);<br>  }<br>}</pre><p><strong>Why This Helps</strong>: Now, each class has a single responsibility. If you need to update authentication, you only modify AuthService, leaving the rest untouched.</p><h3>2. Open/Closed Principle (OCP)</h3><p><strong>The Problem</strong>: Let’s say you run a pizza place and suddenly decide to add sushi to the menu. Instead of changing your entire pizza recipe, you just add a new sushi section. Similarly, your classes should be extendable but not modifiable.</p><p><strong>In Flutter</strong>: Here’s what <strong>not</strong> to do:</p><pre>class PaymentProcessor {<br>  void processCreditCardPayment() {<br>    // Process credit card payment<br>  }<br><br>  // Now you need to add PayPal support...<br>  void processPayPalPayment() {<br>    // Process PayPal payment<br>  }<br>}</pre><p><strong>What’s wrong?</strong><br>Every time you need to add a new payment method, you’re modifying the PaymentProcessor class. That’s bad!</p><p><strong>The OCP Fix</strong>:</p><pre>abstract class PaymentMethod {<br>  void pay();<br>}<br><br>class CreditCardPayment implements PaymentMethod {<br>  @override<br>  void pay() {<br>    // Process credit card payment<br>  }<br>}<br><br>class PayPalPayment implements PaymentMethod {<br>  @override<br>  void pay() {<br>    // Process PayPal payment<br>  }<br>}<br><br>class PaymentProcessor {<br>  void processPayment(PaymentMethod paymentMethod) {<br>    paymentMethod.pay();<br>  }<br>}</pre><p><strong>Why This Helps</strong>: Adding a new payment method? No problem! Just create a new class that implements PaymentMethod. Your existing PaymentProcessor stays intact.</p><h3>3. Liskov Substitution Principle (LSP)</h3><p><strong>The Problem</strong>: Imagine ordering a delivery robot that suddenly turns into a vacuum cleaner halfway through. It’s confusing and probably a bit scary. In programming, subclasses should behave like their parent classes without surprises.</p><p><strong>In Flutter</strong>: Here’s what <strong>not</strong> to do:</p><pre>class Bird {<br>  void fly() {<br>    // Birds can fly<br>  }<br>}<br><br>class Penguin extends Bird {<br>  @override<br>  void fly() {<br>    throw Exception(&quot;Penguins can&#39;t fly!&quot;);<br>  }<br>}</pre><p><strong>What’s wrong?</strong><br>A Penguin is a bird, but it doesn’t fly, which breaks expectations. Anyone using Penguin will be shocked when it throws an exception.</p><p><strong>The LSP Fix</strong>:</p><pre>abstract class Bird {<br>  void move();<br>}<br><br>class FlyingBird extends Bird {<br>  @override<br>  void move() {<br>    // Fly<br>  }<br>}<br><br>class Penguin extends Bird {<br>  @override<br>  void move() {<br>    // Swim<br>  }<br>}</pre><p><strong>Why This Helps</strong>: Now, Penguin doesn’t pretend to be a flying bird. Your app behaves as expected, avoiding runtime surprises.</p><h3>4. Interface Segregation Principle (ISP)</h3><p><strong>The Problem</strong>: Ever been given a job description that includes tasks you’ll never need to do, like “must be able to tame lions”? In programming, don’t force classes to implement methods they don’t need.</p><p><strong>In Flutter</strong>: Here’s what <strong>not</strong> to do:</p><pre>abstract class Animal {<br>  void fly();<br>  void swim();<br>}<br><br>class Fish implements Animal {<br>  @override<br>  void fly() {<br>    // Fish can&#39;t fly!<br>  }<br><br>  @override<br>  void swim() {<br>    // Fish swim<br>  }<br>}</pre><p><strong>What’s wrong?</strong><br>Fish shouldn’t have to implement fly(). It’s unnecessary and messy.</p><p><strong>The ISP Fix</strong>:</p><pre>abstract class Swimmer {<br>  void swim();<br>}<br><br>abstract class Flyer {<br>  void fly();<br>}<br><br>class Fish implements Swimmer {<br>  @override<br>  void swim() {<br>    // Fish swim<br>  }<br>}</pre><p><strong>Why This Helps</strong>: Now, Fish only implements what it needs. Interfaces are cleaner, and classes are more focused.</p><h3>5. Dependency Inversion Principle (DIP)</h3><p><strong>The Problem</strong>: Relying on a low-level detail, like always using a specific brand of coffee beans, means you’re stuck. If they stop selling those beans, you’re doomed. In coding, higher-level modules should depend on abstractions, not low-level details.</p><p><strong>In Flutter</strong>: Here’s what <strong>not</strong> to do:</p><pre>class OrderService {<br>  final Database database = SQLiteDatabase();<br><br>  void placeOrder() {<br>    database.saveOrder();<br>  }<br>}</pre><p><strong>What’s wrong?</strong><br>OrderService is tied to SQLiteDatabase. Switching databases would be a nightmare.</p><p><strong>The DIP Fix</strong>:</p><pre>abstract class Database {<br>  void saveOrder();<br>}<br><br>class SQLiteDatabase implements Database {<br>  @override<br>  void saveOrder() {<br>    // Save order to SQLite<br>  }<br>}<br><br>class OrderService {<br>  final Database database;<br><br>  OrderService(this.database);<br><br>  void placeOrder() {<br>    database.saveOrder();<br>  }<br>}</pre><p><strong>Why This Helps</strong>: Now, OrderService depends on an abstraction (Database), making it easy to swap out SQLiteDatabase for something else, like FirestoreDatabase.</p><h3>Wrapping Up</h3><p>SOLID principles might sound complicated, but they’re your best friends for keeping your Flutter code clean and maintainable. Think of them as the rules that keep your code from turning into a house of cards (or a very confused clown).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*CO6TQ0gGmewYRk5Ik2hFig.gif" /></figure><p>Happy coding, and remember: Keep it SOLID, keep it simple, and keep your app from crashing at the worst possible moment!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4f17264d290e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Firebase Todo App: The Fun, Beginner-Friendly Way!]]></title>
            <link>https://medium.com/@tech.ramakant/building-a-firebase-todo-app-the-fun-beginner-friendly-way-75278f93bdde?source=rss-b01a13ae7644------2</link>
            <guid isPermaLink="false">https://medium.com/p/75278f93bdde</guid>
            <category><![CDATA[apple]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[apps]]></category>
            <dc:creator><![CDATA[Tech Ramakant]]></dc:creator>
            <pubDate>Sat, 12 Oct 2024 21:39:38 GMT</pubDate>
            <atom:updated>2025-08-20T13:58:54.444Z</atom:updated>
            <content:encoded><![CDATA[<p>If you have ever thought having your own <strong>Todo App</strong>, Let’s create a <strong>Firebase-powered Todo App</strong> with a sleek design, including <strong>checkboxes for completion, swipe-to-delete with an action</strong>, and so on.</p><p>Ready? Let’s go from zero to hero in no time. Plus, I’ll throw in a sprinkle of humor, because why not?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ahtUOYaLMFgC5pNw" /><figcaption>Photo by <a href="https://unsplash.com/@sableflow?utm_source=medium&amp;utm_medium=referral">Sable Flow</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Why Firebase + Flutter?</h4><p><strong>Firebase</strong> and <strong>Flutter</strong> are a match made in app heaven. Firebase handles your backend, so you don’t any servers hosting anymore, and Flutter takes care of the frontend with cross plateform support, so you can build beautiful apps without losing your mind. And the best part? <strong>Real-time data syncing</strong> with Firestore means your todos stay updated across all devices.</p><h4>Step 1: Overhaul the Default Counter App (From Counting to Completing)</h4><p>We’re upgrading Flutter’s boring default counter app to a <strong>professional Todo app</strong> with a shopping-cart-like list, checkboxes for completion, and swipe-to-delete.</p><ol><li>Start with the default project:</li></ol><pre>flutter create simple_firebase_todo<br>cd simple_firebase_todo</pre><p>2. Add these dependencies in your pubspec.yaml:</p><pre>dependencies:<br>  firebase_core: latest_version<br>  cloud_firestore: latest_version</pre><p>3. Run flutter pub get to install the new dependencies.</p><h4>Step 2: Firebase Setup (No Drama, Just Data)</h4><h4>For Android:</h4><ol><li>Head to the <a href="https://console.firebase.google.com/"><strong>Firebase Console</strong></a> and create a new project.</li><li><strong>Enable Firestore</strong>:<br>Go to the Firestore Database section in the Firebase Console and create a database with the following rules for testing:</li></ol><pre>rules_version = &#39;2&#39;;<br>service cloud.firestore {<br>  match /databases/{database}/documents {<br>    match /todos/{document=**} {<br>      allow read, write: if true; // For testing only<br>    }<br>  }<br>}</pre><p>3. Register your Android app, download the google-services.json, and plop it into the /android/app directory of your Flutter project.</p><p>4. Update your android/build.gradle:</p><pre>buildscript {<br>    dependencies {<br>        classpath &#39;com.google.gms:google-services:4.3.10&#39;<br>    }<br>}</pre><p>5. Modify android/app/build.gradle:</p><pre>apply plugin: &#39;com.google.gms.google-services&#39;</pre><p>6. Add the Internet permission (because, duh):</p><pre>&lt;uses-permission android:name=&quot;android.permission.INTERNET&quot;/&gt;</pre><h4>For iOS:</h4><ol><li>Download the GoogleService-Info.plist and add it to the Runner folder in Xcode.</li><li>Update the Podfile:</li></ol><pre>pod &#39;Firebase/Firestore&#39;</pre><p>3. Add the necessary security tweak to your Info.plist:</p><pre>&lt;key&gt;NSAppTransportSecurity&lt;/key&gt;<br>&lt;dict&gt;<br>    &lt;key&gt;NSAllowsArbitraryLoads&lt;/key&gt;<br>    &lt;true/&gt;<br>&lt;/dict&gt;</pre><p>Boom! Firebase is ready for action.</p><h4>Step 3: Firestore for Todos (Data on Fire )</h4><p>We’ll create a new service to handle Firestore operations.</p><p>Create a firebase_service.dart to manage Firestore interactions:</p><pre>import &#39;package:cloud_firestore/cloud_firestore.dart&#39;;<br><br>class FirebaseService {<br>  final CollectionReference todosRef = FirebaseFirestore.instance.collection(&#39;todos&#39;);<br><br>  Future&lt;void&gt; addTodo(String title) {<br>    return todosRef.add({&#39;title&#39;: title, &#39;is_completed&#39;: false});<br>  }<br><br>  Stream&lt;QuerySnapshot&gt; getTodos() {<br>    return todosRef.snapshots();<br>  }<br><br>  Future&lt;void&gt; updateTodoStatus(String id, bool isCompleted) {<br>    return todosRef.doc(id).update({&#39;is_completed&#39;: isCompleted});<br>  }<br><br>  Future&lt;void&gt; deleteTodo(String id) {<br>    return todosRef.doc(id).delete();<br>  }<br>}</pre><h4>Step 4: <strong>Initialize Firebase</strong></h4><p>In your main.dart file, initialize Firebase</p><pre>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:firebase_core/firebase_core.dart&#39;;<br>import &#39;firebase_options.dart&#39;; // Generated after adding your app to Firebase<br><br>void main() async {<br>  WidgetsFlutterBinding.ensureInitialized();<br>  await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);<br>  runApp(MyApp());<br>}</pre><h4>Step 5: <strong>Building the Todo List UI: Let’s Get Creative!</strong></h4><pre>class TodoList extends StatelessWidget {<br>  @override<br>  Widget build(BuildContext context) {<br>    return StreamBuilder(<br>      stream: FirebaseService().getTodos(),<br>      builder: (context, AsyncSnapshot&lt;QuerySnapshot&gt; snapshot) {<br>        if (!snapshot.hasData) return CircularProgressIndicator();<br><br>        return ListView(<br>          children: snapshot.data!.docs.map((doc) {<br>            bool isCompleted = doc[&#39;is_completed&#39;];<br><br>            return Dismissible(<br>              key: Key(doc.id),<br>              background: Container(<br>                color: Colors.red,<br>                alignment: Alignment.centerLeft,<br>                padding: EdgeInsets.symmetric(horizontal: 20),<br>                child: Icon(Icons.delete, color: Colors.white),<br>              ),<br>              onDismissed: (direction) {<br>                FirebaseService().deleteTodo(doc.id);<br>                ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(&quot;Todo deleted&quot;)));<br>              },<br>              child: ListTile(<br>                leading: Checkbox(<br>                  value: isCompleted,<br>                  onChanged: (value) {<br>                    FirebaseService().updateTodoStatus(doc.id, value!);<br>                  },<br>                ),<br>                title: Text(<br>                  doc[&#39;title&#39;],<br>                  style: TextStyle(<br>                    decoration: isCompleted<br>                        ? TextDecoration.lineThrough<br>                        : TextDecoration.none,<br>                  ),<br>                ),<br>              ),<br>            );<br>          }).toList(),<br>        );<br>      },<br>    );<br>  }<br>}</pre><p>This makes our app feel polished:</p><ul><li><strong>Checkboxes</strong> update the todo’s isCompleted status.</li><li><strong>Swipe-to-delete</strong> shows an action before deletion, just like Gmail.</li><li>Todos appear in a <strong>shopping-cart-like</strong> style, with the title crossed out when completed.</li></ul><h4>Step 6: Adding Todos with a Dialog Box</h4><p>Let’s get that Todo adding functionality in place. We’ll show a <strong>dialog</strong> when the user clicks the FAB.</p><pre>void _addTodoDialog(BuildContext context) {<br>  TextEditingController _controller = TextEditingController();<br><br>  showDialog(<br>    context: context,<br>    builder: (BuildContext context) {<br>      return AlertDialog(<br>        title: Text(&quot;Add Todo&quot;),<br>        content: TextField(<br>          controller: _controller,<br>          decoration: InputDecoration(hintText: &quot;Enter your todo&quot;),<br>        ),<br>        actions: [<br>          TextButton(<br>            onPressed: () {<br>              FirebaseService().addTodo(_controller.text);<br>              Navigator.of(context).pop();<br>            },<br>            child: Text(&quot;Add&quot;),<br>          ),<br>        ],<br>      );<br>    },<br>  );<br>}</pre><h4>Step 7: Setup Display Todos</h4><ol><li>Make MyHomePage <strong>Stateless</strong> because pros know that stateless widgets are where it’s at:</li></ol><pre>class MyHomePage extends StatelessWidget {<br> <br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(<br>        title: Text(widget.title),<br>      ),<br>      body: Column(<br>          mainAxisAlignment: MainAxisAlignment.center,<br>          children: &lt;Widget&gt;[<br>            Text(<br>              &#39;You have pushed the button this many times:&#39;,<br>            ),<br>            Text(<br>              &#39;$_counter&#39;,<br>              style: Theme.of(context).textTheme.headline4,<br>            ),<br>          ],<br>        ),<br>      ),<br>      floatingActionButton: FloatingActionButton(<br>        onPressed: _incrementCounter,<br>        tooltip: &#39;Increment&#39;,<br>        child: Icon(Icons.add),<br>      ),<br>    );<br>  }<br><br>}</pre><ol><li>Attach TodoList to display existing todo list</li></ol><pre>class MyHomePage extends StatelessWidget {<br> <br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(<br>        title: Text(widget.title),<br>      ),<br>      body: TodoList(),<br>      floatingActionButton: FloatingActionButton(<br>        onPressed: _incrementCounter,<br>        tooltip: &#39;Increment&#39;,<br>        child: Icon(Icons.add),<br>      ),<br>    );<br>  }<br><br>}</pre><p>2. Attach _ddTodoDialog to make add new todo working</p><pre>class MyHomePage extends StatelessWidget {<br> <br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(<br>        title: Text(widget.title),<br>        backgroundColor: Colors.blue,<br>      ),<br>      body: TodoList(),<br>      floatingActionButton: FloatingActionButton(<br>        onPressed: _addTodoDialog(context),<br>        child: Icon(Icons.add),<br>      ),<br>    );<br>  }<br><br>}</pre><h4>Conclusion</h4><p>Congratulations! You’ve built a fully functional Firebase todo app from scratch. With this app, you can add, remove, and update tasks, all while learning about Firebase’s real-time capabilities.</p><h4>Key Recap</h4><ul><li><strong>Firebase Project Setup</strong>: Created a Firebase project and added the necessary configuration files.</li><li><strong>Flutter App Structure</strong>: Built a Flutter app with a todo list interface, allowing users to manage tasks.</li><li><strong>Real-Time Database</strong>: Implemented Firebase Firestore for storing and retrieving todos in real-time.</li></ul><h4>Wrap Up</h4><p>That’s it! You’ve successfully created a Firebase todo app using Flutter. Don’t forget to experiment with additional features like user authentication or task categories. The sky’s the limit!</p><p>Check out the full source code for this project on <a href="https://github.com/tech-ramakant/simple_firebase_todo">GitHub</a>. If you found this helpful, give it a clap on Medium (it’s free and motivates us!) and feel free to star the repo on GitHub. Drop your comments and suggestions — let’s keep improving together!</p><p>Happy coding, and enjoy your newfound Firebase powers!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=75278f93bdde" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Smooth Transition from Cubit to Bloc]]></title>
            <link>https://medium.com/@tech.ramakant/smooth-transition-from-cubit-to-bloc-7b12e1d4d8ef?source=rss-b01a13ae7644------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b12e1d4d8ef</guid>
            <category><![CDATA[apps]]></category>
            <category><![CDATA[i̇so]]></category>
            <category><![CDATA[apple]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Tech Ramakant]]></dc:creator>
            <pubDate>Thu, 10 Oct 2024 09:32:17 GMT</pubDate>
            <atom:updated>2024-10-10T09:32:58.911Z</atom:updated>
            <content:encoded><![CDATA[<p>So, you’ve mastered <strong>Cubit</strong> and it feels pretty good, right? But now you’re curious about <strong>Bloc</strong>, the big sibling of Cubit. No worries! We’ve got you covered with a quick guide to make the transition smooth and easy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SIn7rKI86Du-nUo1" /><figcaption>Photo by <a href="https://unsplash.com/@jupp?utm_source=medium&amp;utm_medium=referral">Jonathan Kemper</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>If you’re unfamiliar with Cubit, we already covered that in the <a href="https://medium.com/@tech.ramakant/bloc-too-tough-start-with-cubit-for-a-smoother-ride-2a437435d3e5"><strong>Cubit article</strong></a>, which made Bloc beginner-friendly by introducing Cubit as the starting point. Now, it’s time to step it up a notch with Bloc!</p><h4>Why Even Bother Switching to Bloc? 🤔</h4><p>Cubit is great for simple tasks: it’s lightweight and gets the job done. But when things start to get real, and you’re dealing with more complex features (like handling multiple events), you’ll need Bloc’s superpower: <strong>Event-Driven State Management</strong>.</p><p>Bloc lets you fire off <strong>events</strong> and handle state transitions neatly — it’s like leveling up from a simple pushbike to a motorbike. Let’s see how to turbo-charge your state management.</p><h4>The Old Setup: Cubit Style 🛠️</h4><p>Here’s a quick peek at the <strong>Cubit</strong> version we had before:</p><h4>Cubit Counter Example:</h4><pre>class CounterCubit extends Cubit&lt;int&gt; {<br>  CounterCubit() : super(0);<br><br>  void increment() =&gt; emit(state + 1);<br>}</pre><p>Here, you’d directly call increment() to update the counter. Simple, right? But what if we wanted to handle more complex scenarios or async logic? Enter <strong>Bloc</strong>.</p><h4>Step-by-Step: Transitioning to Bloc 🛤️</h4><p>Here’s how to move from Cubit to Bloc, step-by-step, and it’s easier than you might think.</p><h4>Step 1: Create Some Events 🎉</h4><p>In Bloc, we use events to tell our app, “Hey, something happened — let’s react!” In this case, we’ll create an event called CounterIncremented.</p><pre>abstract class CounterEvent {}<br><br>class CounterIncremented extends CounterEvent {}</pre><p>💡 <strong>Why do this?</strong> It separates <strong>what happens</strong> (events) from <strong>how the app should react</strong> (state changes). This makes things cleaner and scalable.</p><h4>Step 2: Set Up the Bloc Class 🔧</h4><p>Now, let’s make our Bloc. It’s like Cubit, but now it listens for events and then figures out how to update the state.</p><pre>class CounterBloc extends Bloc&lt;CounterEvent, int&gt; {<br>  CounterBloc() : super(0) {<br>    on&lt;CounterIncremented&gt;((event, emit) {<br>      emit(state + 1);<br>    });<br>  }<br>}</pre><p>The key difference here is the on&lt;CounterIncremented&gt; handler. Whenever a CounterIncremented event is fired, Bloc bumps the state by 1.</p><h4>Step 3: Change How We Update the UI 🖼️</h4><p>With Cubit, we called methods like increment(). With Bloc, we trigger <strong>events</strong> and Bloc takes care of the rest.</p><pre>onPressed: () =&gt; context.read&lt;CounterBloc&gt;().add(CounterIncremented()),</pre><p>Instead of directly updating the state, we’re now sending an <strong>event</strong> — CounterIncremented. Bloc catches this and updates the state. Easy, right?</p><h4>Step 4: BlocBuilder Does the Heavy Lifting 💪</h4><p>We still use BlocBuilder to listen to state changes and update the UI, just like with Cubit.</p><pre>BlocBuilder&lt;CounterBloc, int&gt;(<br>  builder: (context, count) {<br>    return Text(&#39;$count&#39;);<br>  },<br>)</pre><p>The UI will re-render when the state changes. So if the counter goes from 0 to 1, boom, the screen updates without breaking a sweat.</p><h4>Step 5: Transitioned from CounterCubit to CounterBloc🎉</h4><p>We still use BlocProvider just like Cubit.</p><pre>class MyApp extends StatelessWidget {<br>  const MyApp({super.key});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return BlocProvider(<br>      create: (context) =&gt; CounterBloc(),  //todo: Step 5: Transitioned from CounterCubit to CounterBloc<br>      child: MaterialApp(<br>        title: &#39;Flutter Demo&#39;,<br>        theme: ThemeData(<br>          colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),<br>          useMaterial3: true,<br>        ),<br>        home: const MyHomePage(title: &#39;Flutter Demo Home Page&#39;),<br>      ),<br>    );<br>  }<br>}</pre><p>Now, CounterBloc is created and provided to the widget tree, just like we did earlier with <strong>Cubit</strong>, but this sets us up for a more event-based state management approach.</p><h4>In a Nutshell 🥜</h4><p>Here’s a quick summary of what changed:</p><ol><li><strong>Events</strong>: Bloc introduces events like CounterIncremented, giving a clear separation between what happens and how the app should react.</li><li><strong>Bloc Class</strong>: This handles incoming events and decides how to change the state.</li><li><strong>UI</strong>: Now we send events to update the UI instead of directly manipulating the state.</li></ol><h4>Wrap Up 🎁</h4><p>That’s it! 🎉 Moving from <strong>Cubit</strong> to <strong>Bloc</strong> is like switching gears in state management. You’re not losing Cubit’s simplicity; you’re gaining more control and scalability.</p><p>Check out the full source code for this transition on <a href="https://github.com/tech-ramakant/counter_app_with_bloc">GitHub</a>. If you found this helpful, give it a <strong>clap</strong> on Medium (it’s free and motivates us!) and feel free to <strong>star the repo</strong> on GitHub. Drop your comments and suggestions — let’s keep improving together!</p><p>Happy coding, and enjoy the ride from Cubit to Bloc! 😄</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b12e1d4d8ef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bloc Too Tough? Start with Cubit for a Smoother Ride!]]></title>
            <link>https://medium.com/@tech.ramakant/bloc-too-tough-start-with-cubit-for-a-smoother-ride-2a437435d3e5?source=rss-b01a13ae7644------2</link>
            <guid isPermaLink="false">https://medium.com/p/2a437435d3e5</guid>
            <category><![CDATA[apple]]></category>
            <category><![CDATA[apps]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[flutt]]></category>
            <dc:creator><![CDATA[Tech Ramakant]]></dc:creator>
            <pubDate>Wed, 09 Oct 2024 15:43:06 GMT</pubDate>
            <atom:updated>2024-10-09T15:43:06.122Z</atom:updated>
            <content:encoded><![CDATA[<p>Hey Flutter devs! 🚀 Are you tired of trying to jump straight into Bloc state management and feeling like you’re drowning in event-to-state mappings? Well, you’re not alone! That’s why we’re going to take a detour and start with <strong>Cubit</strong>, the easier, friendlier cousin of Bloc. It’s like getting on a bike before jumping straight into a race car — smooth and simple.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*82uf30C0NA1Km2Ly" /><figcaption>Photo by <a href="https://unsplash.com/@mukukostudio?utm_source=medium&amp;utm_medium=referral">Mukuko Studio</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>What’s Cubit, You Ask?</h4><p>Think of Cubit as the easier way to manage your app’s state in Flutter. You don’t need to worry about complex event systems. With Cubit, you just call methods and update your state directly. It’s a perfect fit for when you want something that’s powerful but not overwhelming.</p><h4>So… Why Cubit Instead of Bloc?</h4><p>Cubit helps you understand the basics of state management without bogging you down with extra layers of complexity. It’s like being in a tutorial mode of a game before advancing to the boss level. 🕹️ You don’t need to handle events, just <strong>methods</strong>. Easy peasy!</p><p>Let’s take the Flutter default counter app and give it a Cubit makeover to show how easy it is.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*lo0VpO0LEu_8-jVvRZz0ng.gif" /></figure><h4>Cubit Makeover for the Counter App 💅</h4><p>First Add the flutter_bloc package to pubspec.yaml</p><pre>dependencies:<br>  flutter:<br>    sdk: flutter<br>  flutter_bloc: ^8.0.0</pre><p>Run flutter pub get and you’re good to go!<br>This brings in both Bloc and Cubit, but we’re focusing on Cubit today. 🎯</p><p>Here’s a breakdown of the changes made to the default Flutter counter app, step by step, with explanations and code snippets for each part.</p><p><strong>Step 1: Create the Cubit Class:</strong></p><p>Here’s where we say goodbye to setState() and hello to Cubit!</p><pre>import &#39;package:flutter_bloc/flutter_bloc.dart&#39;;<br><br>// Step 1: Create the CounterCubit<br>class CounterCubit extends Cubit&lt;int&gt; {<br>  CounterCubit() : super(0);  // Initial state<br><br>  void increment() =&gt; emit(state + 1);  // Increment state by 1<br>}</pre><p><strong>Explanation:</strong></p><ul><li>CounterCubit inherits from Cubit&lt;int&gt;, which means it manages an integer state (the counter).</li><li>The constructor initializes the state to 0.</li><li>The increment() method is defined to increase the current state value by 1 and emit the new state.</li></ul><p><strong>Step 2: Provide the </strong><strong>CounterCubit Using </strong><strong>BlocProvider</strong></p><pre>class MyApp extends StatelessWidget {<br>  const MyApp({super.key});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return BlocProvider(<br>      create: (context) =&gt; CounterCubit(),  // Step 2: Provide the CounterCubit<br>      child: MaterialApp(<br>        title: &#39;Flutter Demo&#39;,<br>        theme: ThemeData(<br>          colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),<br>          useMaterial3: true,<br>        ),<br>        home: const MyHomePage(title: &#39;Flutter Demo Home Page&#39;),<br>      ),<br>    );<br>  }<br>}</pre><p><strong>Step 3: Use </strong><strong>BlocBuilder to Listen for State Changes</strong></p><pre>class MyHomePage extends StatelessWidget {<br>  const MyHomePage({super.key, required this.title});<br>  <br>  final String title;<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(<br>        backgroundColor: Theme.of(context).colorScheme.inversePrimary,<br>        title: Text(title),<br>      ),<br>      body: Center(<br>        child: Column(<br>          mainAxisAlignment: MainAxisAlignment.center,<br>          children: &lt;Widget&gt;[<br>            const Text(<br>              &#39;You have pushed the button this many times:&#39;,<br>            ),<br>            // Step 3: Listen to changes in Cubit state<br>            BlocBuilder&lt;CounterCubit, int&gt;(<br>              builder: (context, count) {<br>                return Text(<br>                  &#39;$count&#39;,<br>                  style: Theme.of(context).textTheme.headlineMedium,<br>                );<br>              },<br>            ),<br>          ],<br>        ),<br>      ),<br>      floatingActionButton: FloatingActionButton(<br>        // ... (remaining code)<br>      ), <br>    );<br>  }<br>}</pre><p><strong>Explanation:</strong></p><ul><li>BlocBuilder takes two generic parameters: the type of the Cubit (here, CounterCubit) and the type of the state it manages (here, int).</li><li>It listens to the CounterCubit and rebuilds the text widget whenever the counter value changes.</li><li>This replaces the need for calling setState().</li></ul><p><strong>Step 4: Update the Button Logic to Call the Cubit Method</strong></p><pre>floatingActionButton: FloatingActionButton(<br>  // Step 4: Trigger the increment function in Cubit<br>  onPressed: () =&gt; context.read&lt;CounterCubit&gt;().increment(),<br>  tooltip: &#39;Increment&#39;,<br>  child: const Icon(Icons.add),<br>),</pre><p><strong>Explanation:</strong></p><ul><li>context.read&lt;CounterCubit&gt;() retrieves the instance of CounterCubit provided earlier.</li><li>Calling increment() directly updates the state, which in turn causes the BlocBuilder to rebuild with the new counter value.</li></ul><h4>Step 5: Test the App!</h4><p>Go ahead and run the app. The counter should increment just as before, but now we’re using Cubit! 🎉</p><h4>Why Choose Cubit Over setState()? 🤔</h4><ul><li><strong>Separation of Concerns</strong>: Cubit helps you keep your business logic (state management) separate from your UI code.</li><li><strong>Cleaner Code</strong>: Say goodbye to multiple setState() calls scattered across your app.</li><li><strong>Scalable</strong>: When your app grows, Cubit can scale with it. You won’t need to refactor your entire state management.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*lR1L22WWObCWcAznkJKW2Q.gif" /></figure><h4>Why Not Jump Straight to Bloc?</h4><p>Good question! Bloc is great but comes with more complexity because of the event system. If you’re just getting started with state management or you’re building a smaller app, <strong>Cubit</strong> provides an easier and faster solution.</p><p>However, once you’re comfortable with Cubit, moving to Bloc becomes super simple, and you’ll already understand most of the concepts!</p><h3>Wrap Up 🎁</h3><p>That’s it! Cubit makes state management in Flutter a breeze before you tackle Bloc. Check out the full source code here: <a href="https://github.com/tech-ramakant/counter_app_with_cubit">Counter App with Cubit</a>.</p><p>If this helped, give it a ⭐️ on GitHub and a clap on Medium — it’s free and keeps the good vibes coming! Follow for more, and feel free to drop any suggestions on GitHub or Medium.</p><p>Stay awesome, happy coding! 🎉</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2a437435d3e5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Level Up Your Flutter State Management with Riverpod]]></title>
            <link>https://medium.com/@tech.ramakant/level-up-your-flutter-state-management-with-riverpod-1e17957bfb72?source=rss-b01a13ae7644------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e17957bfb72</guid>
            <category><![CDATA[apps]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[apple]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Tech Ramakant]]></dc:creator>
            <pubDate>Wed, 09 Oct 2024 09:37:58 GMT</pubDate>
            <atom:updated>2025-09-20T22:57:18.812Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VebOf9OZctzvcgk2" /><figcaption>Photo by <a href="https://unsplash.com/@levidjones?utm_source=medium&amp;utm_medium=referral">Levi Jones</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Hey there, Flutter aficionados! Are you tired of wrestling with your state management like it’s a wild animal? It’s time to upgrade to <strong>Riverpod</strong>! Buckle up as we navigate this exhilarating journey through state management like pros!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*naL643uVPafeBk-tz-c3mA.gif" /></figure><h4><strong>The Old Way: StateProvider</strong></h4><p>Let’s kick things off with our old buddy, StateProvider. Here’s how it used to look:</p><pre>final counterProvider = StateProvider&lt;int&gt;((ref) =&gt; 0);</pre><p>Looks friendly, right? Like a cozy café! But wait! There’s a hidden menu behind the counter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*qsBebjvUnUjKjwbl__G8aQ.gif" /></figure><h4>Problems with StateProvider</h4><ol><li><strong>Limited Superpowers</strong>: While StateProvider is great for simple tasks, it turns into a pumpkin when your app gets complex. It can’t handle multiple states like a pro!</li><li><strong>Juggling Act</strong>: If you have to deal with loading states and errors, you might end up juggling them like a clown at a circus. And trust me, nobody wants to be that clown!</li><li><strong>Code Chaos</strong>: As your app grows, StateProvider can lead to a messy codebase—like trying to fit all your clothes in a tiny suitcase!</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*CO6TQ0gGmewYRk5Ik2hFig.gif" /></figure><h4><strong>The New Way: Meet Notifier and AsyncNotifier</strong></h4><p><strong>Upgrading to Notifier</strong></p><p>Let’s turbocharge our code with Notifier! This upgrade is like adding a nitrous boost to your old jalopy—it’ll make your code run smoother!</p><p>Here’s how to redefine your counter with Notifier:</p><pre>import &#39;package:flutter_riverpod/flutter_riverpod.dart&#39;;<br><br>// Create a Notifier for managing counter state<br>class CounterNotifier extends StateNotifier&lt;int&gt; {<br>  CounterNotifier() : super(0); // Start at zero<br><br>  void increment() =&gt; state++; // Increment the counter<br>  void decrement() =&gt; state--; // Decrement the counter<br>}<br><br>// Define the provider<br>final counterProvider = StateNotifierProvider&lt;CounterNotifier, int&gt;((ref) {<br>  return CounterNotifier();<br>});</pre><h4>Why Choose Notifier?</h4><ul><li><strong>Organized Chaos</strong>: With Notifier, your state logic is neatly tucked away. Think of it as a superhero—always ready to save the day!</li><li><strong>Built-in Methods</strong>: You can define functions to manage your state, making your code cleaner than your kitchen after a cooking binge!</li></ul><h4>Handling Asynchronous Logic with AsyncNotifier</h4><p>When it’s time to fetch data from an API, AsyncNotifier comes to the rescue! Here’s how you can use it:</p><pre>import &#39;package:flutter_riverpod/flutter_riverpod.dart&#39;;<br><br>// Create an AsyncNotifier for fetching data<br>class DataFetcher extends AsyncNotifier&lt;List&lt;String&gt;&gt; {<br>  @override<br>  Future&lt;List&lt;String&gt;&gt; build() async {<br>    await Future.delayed(Duration(seconds: 2)); // Simulate network delay<br>    return [&#39;Data 1&#39;, &#39;Data 2&#39;, &#39;Data 3&#39;]; // Simulated data<br>  }<br>}<br><br>// Define the provider<br>final dataProvider = AsyncNotifierProvider&lt;DataFetcher, List&lt;String&gt;&gt;((ref) {<br>  return DataFetcher();<br>});</pre><h4>Advantages of AsyncNotifier</h4><ul><li><strong>Async Awesomeness</strong>: Managing async operations with AsyncNotifier is smoother than butter on hot toast!</li><li><strong>User Experience Bliss</strong>: Your UI will respond to state changes like a well-trained puppy!</li></ul><h4>Conclusion</h4><p>To sum it up, while StateProvider served its purpose, it’s time to embrace Notifier and AsyncNotifier. They’ll not only tidy up your code but also make your Flutter apps a delight to maintain!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/464/1*kRu91eZk6QPQeyAcv5NFug.gif" /></figure><p>So, let’s put on our capes and fly into the future of state management in Flutter! Happy coding, and may your states always be in your favor!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e17957bfb72" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[State Management in Flutter: Unleashing the Power of Riverpod!]]></title>
            <link>https://medium.com/@tech.ramakant/state-management-in-flutter-unleashing-the-power-of-riverpod-04069a6baf6b?source=rss-b01a13ae7644------2</link>
            <guid isPermaLink="false">https://medium.com/p/04069a6baf6b</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[apple]]></category>
            <category><![CDATA[apps]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Tech Ramakant]]></dc:creator>
            <pubDate>Tue, 08 Oct 2024 05:31:51 GMT</pubDate>
            <atom:updated>2025-09-20T22:34:58.084Z</atom:updated>
            <content:encoded><![CDATA[<p>Hey Flutter Fam!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WMdO70RgZRPiXHKj" /><figcaption>Photo by <a href="https://unsplash.com/@doctype?utm_source=medium&amp;utm_medium=referral">Aleks Dorohovich</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>You might be thinking — recently I walked you through <a href="https://medium.com/@tech.ramakant/state-management-in-flutter-with-provider-89fc16ae7700">Provider</a> for state management, and it seemed like a good choice, right? So why am I suddenly introducing another library, Riverpod? Sounds confusing? Don’t worry — by the end of this article, things will be crystal clear.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/426/1*O3vaGLc_ng1eNPTUZFKmHg.gif" /></figure><h3>Why Riverpod is Your New Best Friend</h3><p>You’ve heard of <strong>Provider</strong>, right? Well, <strong>Riverpod</strong> is like Provider’s cooler, faster, more polished sibling who gets all the compliments at family dinners. Riverpod simplifies things while giving you superpowers. Here’s why:</p><ul><li><strong>No BuildContext Hassle</strong>: Forget awkward BuildContext gymnastics. Riverpod works without it—making refactoring a breeze!</li><li><strong>Compile-time Safety</strong>: Riverpod stops bugs <strong>before</strong> they ruin your day. It checks your code at compile time, so you get fewer surprises in production.</li><li><strong>Unmatched Flexibility</strong>: Whether it’s a Flutter or Dart-only project, Riverpod’s got your back.</li></ul><h3>Let’s Get Rolling with Riverpod</h3><p>Install it by adding this to your pubspec.yaml:</p><pre>dependencies:<br>  flutter_riverpod: ^2.0.0</pre><p>Next, wrap your app in a <strong>ProviderScope</strong> like this:</p><pre>void main() {<br>  runApp(ProviderScope(child: MyApp()));<br>}</pre><p>Now, create a simple counter provider:</p><pre>final counterProvider = StateProvider&lt;int&gt;((ref) =&gt; 0);</pre><p>And, tada! Here’s your shiny new counter app:</p><pre>class CounterApp extends ConsumerWidget {<br>  @override<br>  Widget build(BuildContext context, WidgetRef ref) {<br>    final count = ref.watch(counterProvider);<br>    return Scaffold(<br>      appBar: AppBar(title: Text(&quot;Riverpod Counter&quot;)),<br>      body: Center(child: Text(&#39;$count&#39;, style: TextStyle(fontSize: 50))),<br>      floatingActionButton: FloatingActionButton(<br>        onPressed: () =&gt; ref.read(counterProvider.notifier).state++,<br>        child: Icon(Icons.add),<br>      ),<br>    );<br>  }<br>}</pre><p>BOOM! Just like that, you’ve mastered Riverpod state management. <strong>High five!</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*08reszmf1Sy8oub82EvmEg.gif" /></figure><h3>Final Thoughts</h3><p>Ready to leave setState() behind and live your best state-management life? With Riverpod, you can! Trust me, your future self (and your app) will thank you.</p><p>Check out my <strong>GitHub repo</strong> for the source code: <a href="https://github.com/tech-ramakant/counter_app_with_riverpod">GitHub Repo</a><br>Follow me on <strong>Medium</strong> for more Flutter goodness: <a href="https://medium.com/@tech.ramakant">My Profile</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=04069a6baf6b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>