<?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 Ajeet Kumar on Medium]]></title>
        <description><![CDATA[Stories by Ajeet Kumar on Medium]]></description>
        <link>https://medium.com/@ajeet2511?source=rss-832bb7be7335------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ZiAdKDnskucGS-JxtdAWTA.jpeg</url>
            <title>Stories by Ajeet Kumar on Medium</title>
            <link>https://medium.com/@ajeet2511?source=rss-832bb7be7335------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 07:30:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ajeet2511/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[[Flutter Recipe] Cooking up a Recipe App in Flutter: Grids, Widgets, and Navigation [Part — 2]]]></title>
            <link>https://digitalcurry.in/flutter-recipe-cooking-up-a-recipe-app-in-flutter-grids-widgets-and-navigation-part-2-f0dc460bbaac?source=rss-832bb7be7335------2</link>
            <guid isPermaLink="false">https://medium.com/p/f0dc460bbaac</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[100appsin100daysflutter]]></category>
            <dc:creator><![CDATA[Ajeet Kumar]]></dc:creator>
            <pubDate>Sat, 02 Nov 2024 08:37:32 GMT</pubDate>
            <atom:updated>2024-11-02T08:37:32.245Z</atom:updated>
            <content:encoded><![CDATA[<h3>[Flutter Recipe] Cooking up a Recipe App in Flutter: Grids, Widgets, and Navigation [Part — 2]</h3><h4>Day — 3 | 100 Apps in 100 Days Challenge with Flutter</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oxC39AHxUdPXHRLcTpBiHA.png" /></figure><p>Hey there! Glad you’re back for the second part of our Recipe App tutorial. If you’ve been following along with <strong>Part 1</strong>, you’ve already got a solid foundation with the project setup and a nice trending recipes section. If not then here is a quick link to Part — 1 of the tutorial:</p><p><a href="https://digitalcurry.in/flutter-recipe-cooking-up-a-recipe-app-in-flutter-grids-widgets-and-navigation-775272f9f8b8">[Flutter Recipe] Cooking up a Recipe App in Flutter: Grids, Widgets, and Navigation</a></p><p>But one section doesn’t make a full course, right? Let’s add some more flavor to our app!</p><p>In this part, we’re going to transform our app from a simple recipe list into a full-fledged cooking companion. We’ll add some mouth-watering features like:</p><ul><li>A scrollable list of popular cooking categories (because sometimes you just need breakfast inspiration!)</li><li>A “Recent Recipes” section to showcase what’s fresh out of the kitchen</li><li>A spotlight on our fantastic recipe creators (everyone loves to know who’s behind those delicious dishes)</li><li>A way for users to share their own culinary masterpieces with a Create Recipe screen</li></ul><p>And don’t worry — we’ll keep things organized with our trusty BLoC pattern. Think of it as our mise en place, keeping all our app’s ingredients (I mean, components) neatly arranged and ready to go.</p><p>Ready to cook up something special? Let’s dive in!</p><h3>Module — Popular Categories</h3><p>Navigation is key in any recipe app, and that’s where our “Popular Category” section comes in. Think of it as your kitchen’s filing system, but way more fun! With horizontal-scrolling chips for categories like “Salad,” “Appetizer,” and “Breakfast,” users can quickly jump to their preferred cooking style. Below these, we’ll showcase featured recipes from each category with their cooking times and a handy bookmark feature.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZI9qSZ31hb27JprBGTrynA.png" /></figure><p>Create and add following files to the app for this section:</p><h4>Repository</h4><p><strong>category_repository.dart</strong></p><p>The CategoryRepository class handles data fetching operations for recipe categories and their associated recipes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ff626ca7f1269111b1d2e2dd4578428a/href">https://medium.com/media/ff626ca7f1269111b1d2e2dd4578428a/href</a></iframe><p>It includes two main methods that simulate API calls using local JSON data:</p><ul><li>FetchPopularCategories() — Retrieves a list of popular recipe categories with their associated recipes.</li><li>FetchAllRecipesForSelectedCategory(String categoryName) — Retrieves all recipes for a specific category name.</li></ul><h4><strong>BLoC files for this section</strong></h4><p>Create and add following files to /lib/blocs/category .</p><p><em>popular_category_event.dart</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/894835127ce50089a4645c9ad4eb7ef7/href">https://medium.com/media/894835127ce50089a4645c9ad4eb7ef7/href</a></iframe><p>These events tell our recipe app what’s happening with categories. The base PopularCategoryEvent class sets up a foundation for all category-related events, while two specific events handle distinct actions: FetchPopularCategoriestriggers the initial category load, and PopularCategorySelected carries information about which category a user has chosen. Thanks to Equatable, we can easily compare these events when needed.</p><p><em>popular_category_state.dart</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f8a9a3df598f565e332672dc43e3882d/href">https://medium.com/media/f8a9a3df598f565e332672dc43e3882d/href</a></iframe><p>These states represent different snapshots of our recipe category feature. Starting from PopularCategoryInitial, the state transitions through PopularCategoryLoading while fetching data, to either PopularCategoryLoaded (containing the category list, selected category, and its recipes) or PopularCategoryError if something goes wrong. Like our events, these states use Equatable for easy comparisons.</p><p><em>popular_category_bloc.dart</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/315f718c7f01bccbff185e34fdc0fd56/href">https://medium.com/media/315f718c7f01bccbff185e34fdc0fd56/href</a></iframe><p>The PopularCategoryBloc serves as the brains behind our recipe category management. It works with our repository to fetch categories and their recipes, handling two main tasks: loading all categories initially (with the first one selected by default) and updating the view when a user selects a different category. When things are loading, it lets the UI know to show a loading state, and if anything goes wrong, it gracefully handles the error. Think of it as a smart assistant that keeps your recipe categories organized and your UI updated!</p><h4><strong>Models</strong></h4><p>Create and add following models to /lib/models/category.</p><p><strong>popular_category_response.dart</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3474c383240d0c2a0dd65e22ce8af39b/href">https://medium.com/media/3474c383240d0c2a0dd65e22ce8af39b/href</a></iframe><p><strong>popular_category.dart</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c0ab8fde3c9200ab46df28b06a455b34/href">https://medium.com/media/c0ab8fde3c9200ab46df28b06a455b34/href</a></iframe><h4>UI Widgets and Components</h4><p>Now lets create the UI to present data to the user. It has two sections —</p><ul><li>Top section show category options like salad, appetizers, etc.</li><li>Bottom section show the recipes under that category.</li></ul><p><strong>popular_category_section.dart</strong></p><p>Create the widget in /lib/screens/home/sub_sections . This widget will be responsible for create the popular category section.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6b95e7e78f9b17206117da9aa9cd8ebe/href">https://medium.com/media/6b95e7e78f9b17206117da9aa9cd8ebe/href</a></iframe><p><strong>category_name_card.dart</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9dde5887085d5bc9343eb8e343b6e91d/href">https://medium.com/media/9dde5887085d5bc9343eb8e343b6e91d/href</a></iframe><p><strong>category_recipe_card.dart</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/83c89ba32964efffca6b5d00d151582a/href">https://medium.com/media/83c89ba32964efffca6b5d00d151582a/href</a></iframe><p>With this we are done with our category. Now we need to enable it into our homescreen.</p><p>Open home_screen.dart and add following lines to MultiBlocProvider</p><pre>BlocProvider&lt;PopularCategoryBloc&gt;(<br>            create: (context) =&gt; PopularCategoryBloc(categoryRepository: CategoryRepository())..add(FetchPopularCategories()),<br>          ),</pre><p>This will ensure that our provider is available to our popular category section.</p><p>Add below method to SingleChildScrollView, just below TrendingSection() method.</p><pre>TrendingSection(),<br>PopularCategorySection(), // To be added</pre><p>If you run this code now, you should be able to see popular category section under trending section now.</p><p>In the similar way, we will also be creating the — Recent Recipes and Popular Creators sections. The basic principles remains the same.</p><ol><li>Create all BLoC file — Event, State and BLoC. These files are created under /lib/blocs/&lt;module name&gt;.</li><li>A separate repository class to handle data retrieval for the section. It&#39;s usually best to keep them separate but you can take call based on your project requirements.</li><li>Model — API response pojo.</li><li>Sub-section — Parent widget to create and manage the section.</li><li>UI Components — any UI components used by the sub-section widget created above.</li></ol><p>Just to keep this post short we will try to move past it quickly.</p><h3>Module — Recent Recipes</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u9sMCBseK9ox0twuiGgizg.jpeg" /></figure><p>Create and add the following files to the project.</p><h4>Repository</h4><p><strong>/lib/repositories/recent_recipe_repository.dart</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cad8584d711b07aaa17e6fe0400c06cc/href">https://medium.com/media/cad8584d711b07aaa17e6fe0400c06cc/href</a></iframe><h4>BLoC Files</h4><p><strong>/lib/blocs/recent_recipe/recent_recipe_event.dart</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/293e3ef0d29d8c24de955cc9b020ba8a/href">https://medium.com/media/293e3ef0d29d8c24de955cc9b020ba8a/href</a></iframe><p>The recent_recipe_event.dart establishes the foundation for user interactions in our recipe feature. It defines two key events: one for loading recent recipes(LoadRecentRecipies) and another for handling recipe selection(RecentRecipeSelected). This clean separation of events makes it straightforward to add new user interactions as the feature grows.</p><p><strong>/lib/blocs/recent_recipe/recent_recipe_state.dart</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7c33a3144c1b5a23695b26e525e9a478/href">https://medium.com/media/7c33a3144c1b5a23695b26e525e9a478/href</a></iframe><p>The recent_recipe_state.dart maps out all the possible states our recent recipes feature can exist in. It provides a comprehensive state lifecycle from initial loading through to success or error conditions. What&#39;s particularly useful is how it encapsulates the loaded recipe data and selected recipe information, making it easy for the UI to react appropriately to state changes.</p><p><strong>/lib/blocs/recent_recipe/recent_recipe_bloc.dart</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/295e048798e5b2af5f33e6495e92da7f/href">https://medium.com/media/295e048798e5b2af5f33e6495e92da7f/href</a></iframe><p>The recent_recipe_bloc.dart serves as the core orchestrator of the recent recipes feature, functioning as a BLoC (Business Logic Component). It&#39;s designed to work with a repository to fetch recipe data and manages the flow between user actions and UI states.</p><h4>Models</h4><p><strong>/lib/models/recent_recipes/recent_recipe_response.dart</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fc39ba48a6e55e8a34222415b345a4cb/href">https://medium.com/media/fc39ba48a6e55e8a34222415b345a4cb/href</a></iframe><h4>UI Widgets</h4><p><strong>/lib/screens/home/sub_sections/recent_recipe_section.dart</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3920b3cf5909730ccab37eaad23fa7a3/href">https://medium.com/media/3920b3cf5909730ccab37eaad23fa7a3/href</a></iframe><p>The RecentRecipeSection widget employs Flutter&#39;s BLoC pattern for state management, featuring a clean and organized layout with a &quot;Recent Recipes&quot; header and a &quot;See all&quot; action button styled in pink. Through its BlocBuilder implementation, it handles various states of the recipe loading process - from initial loading through to error states - ensuring a smooth user experience. The section presents recipe cards in a horizontal scroll view when data is successfully loaded, with appropriate padding and spacing for visual appeal.</p><p><strong>/lib/widgets/recent_recipe_card.dart</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8edd55766cc7f009c38c1b0083d3e94e/href">https://medium.com/media/8edd55766cc7f009c38c1b0083d3e94e/href</a></iframe><h3>Module — Popular Creators</h3><p>This gives us opportunity to create another variation of grid card items.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kHlUHTaD1xTXVV_yjA1Q_g.jpeg" /></figure><p>Create and add following files to the project.</p><h4>Repository</h4><p><strong>/lib/repositories/creator_repository.dart</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d7d5d8a7801687729cbb902f76527dd6/href">https://medium.com/media/d7d5d8a7801687729cbb902f76527dd6/href</a></iframe><h4>BLoC Files</h4><p><strong>/lib/blocs/creator/creator_event.dart</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/184d88966bc7b388eae803ed42e449b1/href">https://medium.com/media/184d88966bc7b388eae803ed42e449b1/href</a></iframe><p>This file presents a minimalist yet extensible approach to event handling for the creator feature. Through the use of Equatable, it establishes a foundation for event comparison and management. While currently implementing only the FetchPopularCreators event, the abstract base class CreatorEvent is structured to easily accommodate future event types as the feature grows, demonstrating good architectural foresight.</p><p><strong>/lib/blocs/creator/creator_state.dart</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f4ac95e7c9ad9201032eed8343c04f41/href">https://medium.com/media/f4ac95e7c9ad9201032eed8343c04f41/href</a></iframe><p>The state management implementation in this file provides a comprehensive set of states for the creator feature using Equatable for efficient state comparison. It defines four distinct states: initial, loading, loaded (with creator data), and error (with message). The CreatorLoaded state specifically carries a list of Creator models, while the CreatorLoadErrorstate ensures proper error message propagation. This structure enables the UI to respond appropriately to all possible states of the creator data lifecycle.</p><p><strong>/lib/blocs/creator/creator_bloc.dart</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2dc4b5cab8263f7133234d8f2b3acb7f/href">https://medium.com/media/2dc4b5cab8263f7133234d8f2b3acb7f/href</a></iframe><p>The CreatorBloc demonstrates a focused implementation of the BLoC pattern, specifically designed to manage popular creator data in the recipe application. It maintains a clean dependency on the PopularCreatorRepository and handles a single event for fetching popular creators. The bloc&#39;s structure emphasizes error handling through try-catch blocks and proper state emissions, ensuring the UI layer receives appropriate feedback during the data fetching process.</p><h4>Models</h4><p><strong>/lib/models/creator/popular_creator_response.dart</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a37b35bb9bd4f2e198a002ef2bdec18d/href">https://medium.com/media/a37b35bb9bd4f2e198a002ef2bdec18d/href</a></iframe><h4>UI Widgets</h4><p><strong>/lib/screens/home/sub_sections/creator_section.dart</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1c8213420d4aeb79656599e92b5d46d8/href">https://medium.com/media/1c8213420d4aeb79656599e92b5d46d8/href</a></iframe><p>the PopularCreatorsSection brings the creator_card cards together in a cohesive layout. This section coordinates the overall presentation with a bold header and pink-accented &quot;See all&quot; navigation, while implementing BloC pattern integration for robust state management. The horizontal scrolling list of creator cards creates an engaging browsing experience, with thoughtful handling of loading states and error scenarios.</p><p><strong>/lib/widgets/creator_card.dart</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0d757f20fc9bc960e800aa0b05a59837/href">https://medium.com/media/0d757f20fc9bc960e800aa0b05a59837/href</a></iframe><p>The heart of our creator display system lies in the CreatorCard widget, a sleek component that encapsulates each creator&#39;s profile in a visually appealing circular format.</p><p>With these we have created all the files to successfully create the UI for home screen. Now open the home_screen.dart file and update it as following:</p><pre>body: MultiBlocProvider(<br>        providers: [<br>          BlocProvider&lt;TrendingBloc&gt;(<br>            create: (context) =&gt; TrendingBloc(TrendingRepository())..add(LoadTrendingRecipes()),<br>          ),<br>          BlocProvider&lt;PopularCategoryBloc&gt;(<br>            create: (context) =&gt; PopularCategoryBloc(categoryRepository: CategoryRepository())..add(FetchPopularCategories()),<br>          ),<br>// New lines to be added<br>          BlocProvider&lt;RecentRecipeBloc&gt;(<br>            create: (context) =&gt; RecentRecipeBloc(repository: RecentRecipeRepository())..add(LoadRecentRecipes()),<br>          ),<br>          BlocProvider&lt;CreatorBloc&gt;(<br>            create: (context) =&gt; CreatorBloc(repository: PopularCreatorRepository())..add(FetchPopularCreators()),<br>          ),<br>        ],</pre><pre>TrendingSection(),<br>PopularCategorySection(),<br>// New lines to be added<br>RecentRecipeSection(),<br>PopularCreatorsSection(),</pre><h3>Home Screen Completion</h3><p>Yay! 👏 We have successfully created the beautiful looking home screen with different functional sections each being modular in nature while maintaining responsive and cohesive relationship with each other. If you run the app now, you should be able to see UI as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S73-c7V3kjR9zw_72pEIlQ.png" /></figure><p><em>Please don’t forget to update the json files. i have updated them with these great looking images.</em></p><p>If you try to click on a recipe you will see an error. To avoid it, comment out the below code from recipe_recipe_card, trending_recipe_card and category_recipe_card. We will be shortly enabling these navigation in the next section of this post:</p><pre>Navigator.pushNamed(<br>  context,<br>  &#39;/recipe_details&#39;,<br>  arguments: {<br>    &#39;recipe&#39;: recipe,<br>  },<br>);</pre><h3>Adding Some Navigation In App</h3><p>Now let’s build some navigation into our app. To keep the scope limited for this post while still creating opportunity to showcase how navigation can be implemented using BLoC pattern we will be handling only the following two scenarios:</p><ol><li>Whenever user click on a recipe, app navigates to a Recipe Details screen.</li><li>When user click on the center “plus” button, app navigates to a simple Create Recipe screen.</li></ol><p>Both these navigation will be implement via app routes.</p><h3>Module — Recipe Details</h3><p>It’s a static screen for now. It takes the data and displays as shown in the following screenshot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y27ZfQfgYJqfo81wNaMmWg.png" /></figure><p>Create and copy the following code to file /lib/screens/recipe_details/recipe_details_screens.dart.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fc52d542f0e7fc96e5003fcdfd37e1a7/href">https://medium.com/media/fc52d542f0e7fc96e5003fcdfd37e1a7/href</a></iframe><p>The RecipeDetailsScreen is where our recipe app truly shines. Let’s look at <strong>three key features</strong> we’re implementing:</p><ul><li>We’re using Flutter’s powerful CustomScrollView with SliverAppBar to create that sleek, collapsible header effect as users scroll through the recipe. When users scroll up, the recipe image elegantly collapses into the app bar — a polished touch that elevates the user experience.</li><li>For content organization, we’ve carefully structured our recipe details with nested ListViews. We’re handling ingredients, instructions, and creator information in distinct sections, while ensuring smooth scrolling behavior using appropriate scroll physics — a crucial detail that prevents those annoying scroll conflicts.</li><li>To keep our code clean and maintainable, we’ve extracted common UI elements like the ingredient cards into separate methods (see _buildIngredientItem). This approach not only makes our code more readable but also ensures consistent styling throughout the screen.</li></ul><p>Check and verify that following lines are uncommented in files — trending_recipe_card, category_recipe_card and recent_recipe_card</p><pre>Navigator.pushNamed(<br>  context,<br>  &#39;/recipe_details&#39;,<br>  arguments: {<br>    &#39;recipe&#39;: recipe,<br>  },<br>);</pre><h4>app.dart</h4><p>We need to also update the app.dart file to define and allow the navigation via the mentioned route. Open the app.dart file and add the following code:</p><pre>class App extends StatelessWidget {<br>  @override<br>  Widget build(BuildContext context) {<br>    return MaterialApp(<br>      title: &#39;Recipe App&#39;,<br>      initialRoute: &#39;/&#39;,<br>      routes: {<br>        &#39;/&#39;: (context) =&gt; OnboardingScreen(),<br>        // &#39;/home&#39;: (context) =&gt; HomeScreen(),<br>        &#39;/recipe_details&#39;: (context) {<br>          final args = ModalRoute.of(context)!.settings.arguments as Map&lt;String, dynamic&gt;;<br>          return RecipeDetailsScreen(recipe: args[&#39;recipe&#39;]);<br>        },<br>      },<br>    );;<br>  }<br>}</pre><p>Now when you run the app, you should be able to navigate to Recipe Details screen whenever you tap on a recipe on the home screen. Look at how the top back button navigation is also handled in the code itself.</p><p><em>You might notice that all ingredients have same image, it’s because i got lazy finding and updating urls with actual images in json. 😅 Please feel free to update the urls if you want to or have time.</em></p><h3>Module — Create Recipe</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lv7E22I64PH-16sl5hw2kg.png" /></figure><p>This is another important opportunity for us to see how input data can be captured using BLoC and send to backend server via api call. Let’s create all the required files:</p><h4>app.dart</h4><p>Add /create_recipe navigation to routes property as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2b24fc320b15b32b65a15917df0aea34/href">https://medium.com/media/2b24fc320b15b32b65a15917df0aea34/href</a></iframe><h4>BLoC Files</h4><p>Create a new folder under /lib/blocs and name it create_recipe to house all module related files.</p><p><strong>create_recipe_event.dart</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9c3fe99616cd086182ce9ed18c2e7faa/href">https://medium.com/media/9c3fe99616cd086182ce9ed18c2e7faa/href</a></iframe><p><strong>create_recipe_state.dart</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/99265e76adfb3dad36f75598ac4902f4/href">https://medium.com/media/99265e76adfb3dad36f75598ac4902f4/href</a></iframe><p><strong>create_recipe_bloc.dart</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/55f8df7ccd743b2b3178c2570391f820/href">https://medium.com/media/55f8df7ccd743b2b3178c2570391f820/href</a></iframe><p>Let’s explore how we’re handling recipe creation using the BLoC pattern.</p><p>In our BLoC implementation, we’ve broken down the recipe creation flow into three key components: the Bloc itself, Events, and States. The CreateRecipeBloc handles the business logic, responding to SubmitRecipeEvent with appropriate states. When a user submits a recipe, we capture essential details like name, servings, cooking time, and ingredients list. The bloc then manages the creation process through distinct states — Initial, Loading, Success, and Error — giving users clear feedback at each step.</p><p>For now, we’re simulating the API call with a delay, but you can easily swap this with your actual API integration by uncommenting the provided HTTP call code. This architecture ensures our recipe creation process is both maintainable and scalable.</p><h4>UI Widget and Components</h4><p>Now lets make a simple UI to allow users to add their recipes to the app. Create a new create_recipe_screen.dart file at /lib/screens/create_recipe. Follow the following code to the file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/adca22c2d4e2803f8834bf7e054c2c9f/href">https://medium.com/media/adca22c2d4e2803f8834bf7e054c2c9f/href</a></iframe><p>We’re using Flutter’s Form widget along with TextFormFields to capture recipe details cleanly. Notice how we’ve implemented form validation and proper input handling for different types of data — text for recipe names, numbers for servings and cooking time, and a comma-separated list for ingredients.</p><p>The screen integrates with our BLoC pattern through BlocListener and BlocBuilder. The listener handles success and error states, showing snackbar messages or navigating back as needed, while the builder manages our submit button’s state, displaying a loading indicator during submission. This creates a smooth, user-friendly experience while maintaining clean separation of concerns.</p><p><em>One neat touch</em>: when users hit the create button, we automatically parse and clean up their ingredient list by splitting the comma-separated input and trimming whitespace — small details that make a big difference in user experience.</p><h3>Final Result 🏆</h3><p>First of all, if you have followed till here, thank you so much for sticking around 🙌. I know it has been a long article. But, as covers one of the most fundamental use cases in a flutter developer life, I thought it should be give the appropriate amount of time.</p><p>I hope I was able to provide a good hands on example to understand how to build flutter apps with BLoC pattern.</p><p>Go ahead and run the app! You should be able to use the functionality as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*8uvsVPHgzZjOfOHPUdBjtw.gif" /></figure><p>If you face any difficulties while running the app, try to compare your code with the project github repository shared below.</p><p><a href="https://github.com/ajeet-repos/recipe_app.git">GitHub - ajeet-repos/recipe_app</a></p><h3>Wrapping Up: Your Recipe for Flutter Success 🎉</h3><p>Congratulations! You’ve just added some serious flavor to your Flutter recipe app. We’ve covered quite a feast of features:</p><ul><li>A scrollable category system that makes recipe discovery a breeze</li><li>An engaging recent recipes section to keep content fresh</li><li>A spotlight on creative chefs through the creators’ showcase</li><li>A seamless recipe details view with that professional sliding header</li><li>A create recipe feature that puts the power in users’ hands</li></ul><p>But remember, like any good recipe, the magic happens when you start experimenting. Try tweaking the UI, adding your own features, or even implementing some of the advanced patterns we discussed. The kitchen of app development is always open for innovation!</p><h4>Areas Of Improvement</h4><p>The current version of the project has a lot of opportunities to make it better. I haven’t covered them here just to keep the scope limited, but we will be covering them separately in future articles. But feel free to experiment, add, delete or update any or all part of the project. The more you experiment the more you will become comfortable. To keep you started here are few areas that you can start with:</p><ol><li><strong>Recipe Details</strong> — Improve the instructions UI in the layout.</li><li><strong>Search filter </strong>— Implement it in a way that when user presses enter/search after entering the text, app takes user to a search_screen and display the recipe list into a vertical list view.</li><li><strong>See all</strong> — When user preses on see all, app takes user to another screen where all recipes are listed in your choise of layout. Be it grid, list or anything else.</li><li><strong>Creator Page </strong>— When user clicks on a creator card, app should take user to a creator_details screen just like the flow we have for recipe details.</li></ol><h3>Stay Connected</h3><p>If you found this tutorial helpful, I’d love to keep you in the loop! Here’s how you can stay connected and support my work:</p><ul><li>Follow me on <a href="https://tinyurl.com/ajeetkumar-at-x">Twitter</a>, <a href="https://tinyurl.com/ajeet-at-linkedin">LinkedIn</a>, and <a href="https://tinyurl.com/ajeet-at-github">GitHub</a> for the latest articles, tips, and insights.</li><li>If you enjoyed this article, please give it some 👏 to help others discover it and encourage me to do more of it.</li><li>Feeling generous? <a href="https://tinyurl.com/support-ajeet">Buy me a coffee</a> to fuel my coding sessions and keep the content flowing!</li></ul><h3>Share Your Feedback</h3><p>I am looking forward to your feedback and suggestions! If you have any comments, questions, or ideas for future tutorials, feel free to reach out to me. You can:</p><ul><li>Leave a comment below the tutorial</li><li>Send me a direct message on Twitter or LinkedIn</li><li>Open an issue or pull request on the GitHub repository</li></ul><p>Your feedback helps me improve the quality of the content and tailor it accordingly.</p><p>Thanks for being a part of my journey! Don’t forget to connect, clap, and support if you found this helpful.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f0dc460bbaac" width="1" height="1" alt=""><hr><p><a href="https://digitalcurry.in/flutter-recipe-cooking-up-a-recipe-app-in-flutter-grids-widgets-and-navigation-part-2-f0dc460bbaac">[Flutter Recipe] Cooking up a Recipe App in Flutter: Grids, Widgets, and Navigation [Part — 2]</a> was originally published in <a href="https://digitalcurry.in/">Digital Curry</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[Flutter Recipe] Cooking up a Recipe App in Flutter: Grids, Widgets, and Navigation]]></title>
            <link>https://digitalcurry.in/flutter-recipe-cooking-up-a-recipe-app-in-flutter-grids-widgets-and-navigation-775272f9f8b8?source=rss-832bb7be7335------2</link>
            <guid isPermaLink="false">https://medium.com/p/775272f9f8b8</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[100appsin100daysflutter]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Ajeet Kumar]]></dc:creator>
            <pubDate>Thu, 17 Oct 2024 13:15:14 GMT</pubDate>
            <atom:updated>2024-11-02T08:54:37.498Z</atom:updated>
            <content:encoded><![CDATA[<h3>[Flutter Recipe] Cooking up a Recipe App in Flutter: Grids, Widgets, and Navigation [Part — 1]</h3><h4>Day — 3 | 100 Apps in 100 Days Challenge with Flutter</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aR4-E5_SUSqEWrLADlIx1w.png" /></figure><p>Are you ready to whip up something delicious in the world of Flutter development? Today, we’re going to cook up a mouthwatering Recipe App that will not only satisfy your hunger for coding but also introduce you to some essential ingredients of Flutter development. We’ll be mixing in grid layouts, custom widgets, and navigation to create a delightful user experience. And to add some extra flavor, we’ll be using the BLoC (Business Logic Component) pattern to keep our app’s state management as organized as a well-stocked pantry.</p><p>By the end of this tutorial, you’ll have a functional Recipe App that allows users to browse trending recipes, explore popular categories, view recipe details, and even create their own culinary masterpieces. Along the way, you’ll gain hands-on experience with:</p><ul><li>Implementing grid layouts for an visually appealing recipe display</li><li>Creating custom widgets to enhance reusability and maintainability</li><li>Setting up navigation to move between different screens seamlessly</li><li>Utilizing the BLoC pattern for efficient state management</li></ul><p>By incorporating the BLoC library into our Recipe App, we’ll demonstrate how it helps separate business logic from the presentation layer, making our code more testable, scalable, and maintainable. You’ll learn how to leverage the power of BLoC to manage app state, handle user interactions, and keep your code organized.</p><p>So, put on your chef’s hat (and your developer’s cap), and let’s start cooking up some code!</p><h3>Prerequisites</h3><p>Before we fire up our development stove, make sure you have the following ingredients ready:</p><ol><li>Flutter SDK — To set up your development environment, follow the official Flutter installation guide: <a href="https://flutter.dev/docs/get-started/install">Flutter: Get Started</a></li><li>An IDE of your choice (we will be using Android Studio for this post)</li><li>Basic knowledge of Dart and Flutter concepts</li></ol><p>For this recipe, we’ll also be using the BLoC library. To add it to your project, run the following command in your terminal:</p><pre>flutter pub add flutter_bloc</pre><h3>Quick Overview of BLoC</h3><p>Before we dive into the recipe for our mouthwatering Flutter app, let’s take a moment to appreciate the secret ingredient that will elevate our coding experience — the BLoC (Business Logic Component) pattern!</p><p>Just like a well-organized kitchen, BLoC helps us keep our app’s state management tidy and efficient. It’s the perfect seasoning to separate the presentation layer (our UI) from the business logic layer, ensuring a clean, scalable, and testable architecture.</p><h4>The Flavors of BLoC</h4><ol><li><strong>Separation of Concerns</strong>: BLoC allows you to decouple the UI from the business logic, making your code more modular and maintainable. It is like having a designated prep station for your veggies and a separate area for cooking.</li><li><strong>Testability</strong>: With BLoC, you can easily write unit tests for your business logic without worrying about the UI layer.</li><li><strong>Scalability</strong>: BLoC enables you to manage complex app states efficiently, making it suitable for small to large-scale production ready applications.</li><li><strong>Reusability</strong>: The separated business logic can be reused across multiple screens or even different apps.</li></ol><h4>The Ingredients of BLoC</h4><ul><li><strong>Events</strong>: Events are the orders coming into the kitchen. They represent actions or user interactions that trigger state changes.</li><li><strong>States</strong>: States are the delightful dishes that come out of the kitchen. They represent the current state of the application or a particular feature.</li><li><strong>Bloc</strong>: The Bloc class is the master chef that manages the state changes. It receives orders (events), processes them, and sends out new dishes (states).</li></ul><h4>Putting It All Together</h4><ol><li>The UI sends an order (event) to the Bloc when a user interacts with the app or when an action needs to be performed.</li><li>The Bloc receives the order (event) and prepares the dish (processes the event) based on the current state and any additional business logic.</li><li>After processing the event, the Bloc sends out a new dish (emits a new state).</li><li>The UI listens to the state changes and updates itself accordingly.</li></ol><p>By following this unidirectional flow of data, the BLoC pattern ensures a predictable and controlled state management process, just like a well-orchestrated kitchen.</p><h4>Serving Up BLoC in Your Flutter App</h4><p>To implement BLoC in our Recipe App, we’ll follow these steps:</p><ol><li>Define the events and states for our app screens or features.</li><li>Create a Bloc class that extends the Bloc base class from the flutter_bloc package.</li><li>Implement the event handling logic in the Bloc class by overriding the mapEventToState method.</li><li>Use the BlocProvider widget to provide the Bloc instance to the widget tree.</li><li>Use the BlocBuilder widget to listen to state changes and rebuild the UI accordingly.</li></ol><p>You can have single of multiple BLoCs for a screen depending on your app and design choices. For example — We will have 4 BLoCs for our home screen respectively for each section — TrendingRecipes , Popular Categories, Recent Recipes and Popular Creators. Whereas other screen will only have one BLoC based on their needs.</p><p>By leveraging the BLoC pattern, we’ll create a scalable and maintainable architecture for our Recipe App, ensuring a smooth development experience and a robust state management solution.</p><p>So, let’s roll up our sleeves, put on our aprons, and get ready to cook up a delicious Flutter app with BLoC!</p><h3>Scope</h3><p>To keep this tutorial detailed enough for us to demonstrate how beautiful UIs can be easily made via Flutter and configure navigation between them, we would have to keep the scope of it very focused.</p><p>We would aim to achieve following functionality for this app:</p><ol><li>Onboarding Screen — Shown at app startup and help navigate user to home screen.</li><li>Home Screen — creates sub sections to build the UI and use BLoC to manage state and navigate user to recipe details screen</li><li>Recipe Details Screen — Detailed view of any selected recipe. Everything presented in a good looking vertically scrollable UI.</li></ol><p>Even these will make this post very long, so we will be splitting the entire post into 2 parts where:</p><ul><li><strong>Part 1</strong> — will cover BLoC overview, project setup, onboarding screen and one complete BLoC powered reactive section in home screen.</li><li><strong>Part 2</strong> — will build on top of part 1, adding all the missing sections to Home Screen, recipe detail screen and navigating between them.</li></ul><h3>Project Setup</h3><p>Let’s start by creating a new Flutter project. Open Android Studio and create a new flutter project. Here is how I created this project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5EqO5DAirTqVpPgzE_cojA.png" /></figure><p>Or you can use Terminal to do the same by running following command:</p><pre>flutter create recipe_app</pre><h4>Add Dependencies</h4><p>Open pubspec.yaml file and add the following dependencies to the project:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W4pBYod2hKPg3zkJPiDLxA.png" /></figure><p>Click Pub get to download the new packages to the project.</p><h4>Add Mock Data</h4><p>Generally in production apps, it pulls data from some backend server. We have already covered that part in our previous post. You can check it out here — Link.</p><p>For this app it would increase the scope of the post significantly. Therefore, to make it easier and still be able to simulate the API response processing, we are going to directly feed the API responses in our app. App repositories will directly read the data from json files and pass it on to our app just like in case of actual API calls.</p><p>Let’s create a folder named assets to the project. This folder will hold our mock API response json files. This folder needs to be created within project root folder not under lib folder as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/1*puVfoXPxQciw4FHLhcsljg.png" /></figure><p>Add following json files to the folder. We will add more files to the folder as we move along.</p><p><a href="https://gist.github.com/ajeet-repos/d6e967c932f9ac3acba3ca99be9bc3f8">popular_categories.json</a></p><p><a href="https://gist.github.com/ajeet-repos/85cbcae02f183ce1179688ec7ca3842f">popular_creators.json</a></p><p><a href="https://gist.github.com/ajeet-repos/465ce0c08566b60491d6595077e6ed7b">recent_recipes.json</a></p><p><a href="https://gist.github.com/ajeet-repos/14370c3c4d2f7389091b2a1d6e0b419c">trending_recipes.json</a></p><p><em>Please ignore if the urls mentioned in the json files seem fake or not working. We will take care of it later.</em></p><p>So, we have added the files, but how will our app access them? For our app to access them we have to define them in our pubspec.yaml file. Open the file and mention the assets as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fEG_b6ebrGdqcMh-lUP8sA.png" /></figure><h4>Project structure</h4><p>Let’s now setup our project structure. We will organize our code into the following directories:</p><pre>lib/<br>  ├── blocs/<br>  ├── models/<br>  ├── screens/<br>  ├── widgets/<br>  ├── repositories/<br>  ├── main.dart</pre><p>Here’s a brief explanation of each directory:</p><ul><li>blocs/: Contains our BLoC classes for state management</li><li>models/: Holds data models for our app</li><li>screens/: Houses the main screens of our app</li><li>widgets/: Stores reusable custom widgets</li><li>repositories/: Contains classes for data fetching and manipulation</li></ul><p>You can create sub-structure within these folders. For example, I will be placing each feature BLoCs into their own folder. We will talk more when we get there, so don’t worry if it feels a little out-of-your-comfort-zone.</p><p>With this we are now ready to start cooking!</p><h3>Module — Onboarding Screen</h3><p>This is the first screen user will see when they open the app. Create a new onboarding_screen.dart file in /lib/screens/onboarding and paste the following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ff1ece226d86bd48962a8f15ef6aa72f/href">https://medium.com/media/ff1ece226d86bd48962a8f15ef6aa72f/href</a></iframe><p>It consists of a fullscreen background image with an overlay added on top of it. It also has a button to take user to the Home Screen.</p><h4><strong>app.dart</strong></h4><p>Create an app.dart file in /lib folder which will define the app it’s configurations. Copy the following code to the file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b1d48c821ff30eb2db1c08aaa49041f2/href">https://medium.com/media/b1d48c821ff30eb2db1c08aaa49041f2/href</a></iframe><p>Here, we have defined an initial route and where it should lead to — OnboardingScreen().</p><h4><strong>main.dart</strong></h4><p>Replace the code in main.dart with the following code:</p><pre>void main() {<br>  runApp(App());<br>}</pre><p>If you want to run the app now, just comment the onPressed property of ElevatedButton in onboarding_screen.dart as we haven’t create the home screen yet. You should be able to see a similar output as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*arhL1Y6f6RKg5u7mzZQuBw.png" /></figure><h3>Module — Home</h3><p>This is the main module for the app where most of the action and opportunity to implement beautiful UI comes from. For our project we will be attempting to create something similar as shown here.</p><p>You can get this design inspiration from figma community — <a href="https://www.figma.com/design/YK7VaWxOgtv1DRvZsIIs5f/Food-Recipe-App-(Community)?node-id=131-561&amp;node-type=frame&amp;t=uRrsfSxT136Aq8JO-0">link</a>. I have made some changes to make it more tutorial friendly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*2Sz2TlpvvzUOE3TpJjab7Q.png" /></figure><p>If you look at the design, you will see that the entire home screen is divided into 5 sections and a bottom app bar.</p><ul><li>Search bar — To search for recipe. When you click on it and search, it would take user to another search screen.</li><li>Trending Recipe Section — This section shows the most trending recipes. All items are displayed in a horizontally scrollable fashion.</li><li>Popular Categories Section — There are two sub parts to it. You have some popular categories on top with the left most selected by default. Then the list of popular dishes from that category displayed below it. When you select another category, the recipe list below should also change accordingly.</li><li>Recent Recipe Section — Its purpose would be to show the most recent recipe uploaded in the system</li><li>Popular Creator Section — This shows the list of most popular chefs on the platform.</li><li>Each section has see all -&gt; also indicating that when you will click on see all you would go to another view where all the recipes from section would be shown.</li></ul><p>We will now divide these into there respective modules/sub-modules and go through with them one-by-one.</p><h4>Add all required models</h4><p>We will simulate the workflow assuming the data is returned from server itself.<em> To keep the scope small, we will also be hard coding the image and video urls.</em></p><p>Create following files in /lib/models and copy the code as shared below:</p><p><strong>ingredients.dart</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/877841cbd001e0028ab7319e28b25b31/href">https://medium.com/media/877841cbd001e0028ab7319e28b25b31/href</a></iframe><p><strong>category.dart</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3857689be2f0553875721d2223127cc2/href">https://medium.com/media/3857689be2f0553875721d2223127cc2/href</a></iframe><p><strong>creator.dart</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cd1b7f8e3b6f3f227c06b7edde39a344/href">https://medium.com/media/cd1b7f8e3b6f3f227c06b7edde39a344/href</a></iframe><p><strong>review.dart</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4538e0fb5f55228997d6f3c869a44265/href">https://medium.com/media/4538e0fb5f55228997d6f3c869a44265/href</a></iframe><p><strong>video.dart</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4a4fa8738556affe311447578f119be7/href">https://medium.com/media/4a4fa8738556affe311447578f119be7/href</a></iframe><p><strong>recipe.dart</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6a41b0a46c41b4a656716766624f7279/href">https://medium.com/media/6a41b0a46c41b4a656716766624f7279/href</a></iframe><p><strong>trending_recipes_response.dart</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/15b8dd957e217494e93dcd6444672172/href">https://medium.com/media/15b8dd957e217494e93dcd6444672172/href</a></iframe><p>Your /models folder now should look like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/652/1*g_Z91JOiRzH72EtpXNjNbg.png" /></figure><p>With models out of the way, we will now focus on our home screen and its trending section.</p><h4>Setting Up BLoC Pattern</h4><p>Since there are multiple sections on home screen solving a different use case it would make sense to have one respective BLoC for each of those sections. Accordingly, lets create following structure within our project.</p><pre>lib/<br>├── blocs/<br>│   ├── category/<br>│   ├── creator/<br>│   ├── recent_recipe/<br>│   └── trending/<br>│       ├── trending_bloc.dart<br>│       ├── trending_event.dart<br>│       └── trending_state.dart<br>├── models/<br>├── repositories/<br>│   └── trending_repository.dart<br>├── screens/<br>│   ├── home/<br>│   │   └── sub_sections/<br>│   │       ├── category_section.dart<br>│   │       ├── creator_section.dart<br>│   │       ├── recent_recipe_section.dart<br>│   │       └── trending_section.dart<br>│   ├── home_screen.dart<br>│   ├── onboarding/<br>│   │   └── onboarding_screen.dart<br>│   └── recipe_details/<br>├── widgets/<br>│   └── trending_recipe_card.dart<br>├── app.dart<br>└── main.dart</pre><p>Here if you might notice that we have created folder for all the section but only created files that would be required to build trending section. Its intentional because it would easier to follow, understand and implement BLoC pattern for only one section first. Once done successfully, whatever we have done for trending section will get replicated for other sections as well.</p><h4>Configuring BLoC For Trending Section</h4><p>Let’s define the trending_repository.dart first which we will be using for this section. It primary responsibility is to fetch data and pass it on when asked. How its fetched and from where are also encapsulated within it. For our example we will be fetching the data from the respective json files, but you can just as easily make changes to fetch it from database or server. Copy the following code to the file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5faac1c83f566fed70145c005ca5e858/href">https://medium.com/media/5faac1c83f566fed70145c005ca5e858/href</a></iframe><p>Here you can see how we are reading our response from json file in assets folder.</p><p><strong>trending_event.dart</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/19f9459a4fc31947aac1aa99d971286b/href">https://medium.com/media/19f9459a4fc31947aac1aa99d971286b/href</a></iframe><p>This file is like our recipe request menu. It’s pretty simple — we’ve got two options here. You can either say “Show me what’s trending” (LoadTrendingRecipes) when you first open the app, or “What’s new in the trending world?” (RefreshTrendingRecipes) when you want to see if any new recipes have climbed the charts. These events are what kickstart our TrendingBloc into action.</p><p><strong>trending_start.dart</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bbe6143fd4eac02104cfafdfaf6a8004/href">https://medium.com/media/bbe6143fd4eac02104cfafdfaf6a8004/href</a></iframe><p>Here’s where we define the different “moods” our trending recipes section can be in. It’s like the stages of cooking a meal. We start with TrendingInitial (turning on the stove), move to TrendingLoading (water’s heating up), then hopefully reach TrendingLoaded (dinner is served, here’s your list of trending recipes!). But sometimes things go wrong, and we end up in TrendingError (oops, we overcooked it).</p><p>Each state gives our app a clear picture of what’s happening with our trending recipes, so it can show the right information to our users.</p><p><strong>trending_bloc.dart</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b30faa45e8931715a7e1f489b135211c/href">https://medium.com/media/b30faa45e8931715a7e1f489b135211c/href</a></iframe><p>Think of this as the brain of our trending recipes feature. It’s like a chef who knows how to handle different situations in the kitchen. When we ask for trending recipes (that’s our LoadTrendingRecipes event) or want to refresh them (RefreshTrendingRecipes event), this bloc springs into action.</p><p>It talks to our recipe repository to fetch the latest trending recipes. As it works, it keeps us updated — “Hey, I’m looking for recipes!” (TrendingLoading state), “Here are the hot recipes right now!” (TrendingLoaded state), or “Oops, I burned the toast” (TrendingError state). It’s all about keeping our app’s users in the loop about what’s happening with trending recipes.</p><p><strong>trending_section.dart</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3e7bc7f78d3470d5a0fbe935a7044357/href">https://medium.com/media/3e7bc7f78d3470d5a0fbe935a7044357/href</a></iframe><p>This file is a widget that shows off what’s hot right now in our app’s culinary world. It uses BlocBuilder to stay in sync with our TrendingBloc, so it always knows what’s cooking.</p><p>When it’s loading up the trending recipes (TrendingLoading state), it shows a spinning circle to let users know app is trying to fetch the information. Once the recipes are ready (state changed to TrendingLoaded), it lays them out in a horizontal scroll view, each recipe presented in its own TrendingRecipeCard. There’s a stylish “Trending now 🔥” header at the top, complete with a “See all” button for those who want to dive deeper into the trending menu.</p><p>If something goes wrong (like if our data fetch burns the metaphorical toast), it’ll show an error message instead (TrendingError state). It’s all about keeping our users informed and engaged, whether things are sizzling perfectly or if we’ve hit a small snag in our recipe retrieval.</p><p><strong>trending_recipe_card.dart</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/537/1*youbWEa0BUbV8Kpc1OwfYA.png" /></figure><p>Copy the copy below to create the above looking UI for recipes in trending section.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4189b76b024e9a8a1ea245dbde1c31f7/href">https://medium.com/media/4189b76b024e9a8a1ea245dbde1c31f7/href</a></iframe><h4>Linking It All Together</h4><p>First of all, thank you for sticking with me till this point. It means a lot to me. We now have only one last step remaining for this post. Let’s finish it in style!</p><p>Create a home_screen.dart file in /lib/screens/home folder and copy the following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4272bbeb6a3dd8a8bbd111caf460d711/href">https://medium.com/media/4272bbeb6a3dd8a8bbd111caf460d711/href</a></iframe><p>This file is like the grand entrance hall of our recipe app. It’s setting up the main stage where all the culinary action happens. Let’s walk through it:</p><p>At the top, we have a customized AppBar with a prominent title. The body of the screen is structured using a MultiBlocProvider, which sets up the state management architecture for different sections of the app. Currently, it initializes the TrendingBloc, with provisions for additional blocs (CategoryBloc, RecentRecipeBloc, and CreatorBloc) to be implemented in future iterations. Rest of the BLoCs will get covered in next part of this post.</p><p>The main content area begins with a search functionality, implemented as a TextField with custom styling to enhance usability. This is followed by placeholder sections for Trending, Categories, Recent Recipes, and Creators, each designed to showcase different aspects of the app’s content.</p><p>Navigation is facilitated through a custom BottomAppBar, featuring home and settings icons. it also uses the centered notch functionality to give it a more professional and distinct look. The design incorporates a FloatingActionButton, prominently placed in the center of the bottom bar, intended for the “Create Recipe” functionality. This button’s positioning and styling make it a focal point of the interface, encouraging user interaction.</p><p>Overall, the HomeScreen layout is optimized for intuitive navigation and engagement, providing a solid foundation for the app’s core functionalities while allowing for future expansions and refinements.</p><h4>MultiBlocProvider</h4><p>The MultiBlocProvider is a crucial component in our app’s state management architecture. It’s a widget from the flutter_bloc package that allows us to efficiently provide multiple Bloc instances to the widget tree.</p><p>In our HomeScreen, we use MultiBlocProvider like this:</p><pre>MultiBlocProvider(<br>  providers: [<br>    BlocProvider&lt;TrendingBloc&gt;(<br>      create: (context) =&gt; TrendingBloc(TrendingRepository())..add(LoadTrendingRecipes()),<br>    ),<br>    // Additional BlocProviders...<br>  ],<br>  child: // Widget tree<br>)</pre><p>This setup offers several advantages:</p><ol><li><em>Centralized State Management</em>: It allows us to initialize and provide all necessary Blocs in one place, making our code more organized and easier to maintain.</li><li><em>Efficient Resource Management</em>: Each Bloc is created only when it’s needed and can be automatically disposed of when it’s no longer required.</li><li><em>Scalability</em>: As our app grows, we can easily add more BlocProviders within the MultiBlocProvider to handle new features or sections.</li><li><em>Improved Readability</em>: By grouping all our Bloc initializations together, we get a clear overview of the app’s state management structure.</li><li><em>Performance Optimization</em>: MultiBlocProvider is more efficient than nesting multiple individual BlocProviders, as it reduces the widget tree depth.</li></ol><p>In our current implementation, we’re initializing the TrendingBloc and immediately triggering the LoadTrendingRecipes event. This ensures that the trending recipes data is fetched as soon as the HomeScreen is built.</p><p>By using MultiBlocProvider, we’re setting up a robust, maintainable foundation for managing the various data streams in our recipe app.</p><h3>Final Result</h3><p>Go ahead and run the app. You have successfully implemented BLoC framework to create a beautiful and functional UI like shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JYTcsYNpnPfwoZVWti7JOg.png" /></figure><h3>Conclusion</h3><p>Congratulations! You’ve just built a good looking App using Flutter and the BLoC pattern. Let’s recap the key ingredients we’ve mixed into our app:</p><ol><li>We set up a solid project structure, organizing our code into logical directories for better maintainability.</li><li>We implemented the BLoC pattern for efficient state management, keeping our business logic separate from the UI.</li><li>We created custom widgets like the TrendingRecipeCard to enhance reusability and maintain a consistent look throughout the app.</li><li>We used Flutter’s navigation system to move between different screens, providing a smooth user experience.</li><li>We designed an appealing user interface with grid layouts, custom themes, and responsive widgets.</li></ol><p>These skills will serve you well as you continue your journey in Flutter development. For this post, we would have to end it here itself, but I will be back with the next post very soon. In the next part, we will be covering the following items:</p><ul><li>Build and integrate remaining section in the HomeScreen — Popular Category, Recent Recipes and Popular Creators.</li><li>Recipe Details screen. When you tap on any recipe on the HomeScreen, you should get navigated to Recipe details screen and back.</li><li>See All — When user taps on it, they are navigated to a dedicated UI when the entire recipe list is show in the grid view.</li><li>Setting up to and fro navigation between screens in the app.</li></ul><p>So stay tuned for the next post.</p><p>If you face any issue running any code, here is the link to this project’s GitHub repository:</p><p><a href="https://github.com/ajeet-repos/recipe_app.git">GitHub - ajeet-repos/recipe_app</a></p><h3>Stay Connected</h3><p>If you found this tutorial helpful, I’d love to keep you in the loop! Here’s how you can stay connected and support my work:</p><ul><li>Follow me on <a href="https://tinyurl.com/ajeetkumar-at-x">Twitter</a>, <a href="https://tinyurl.com/ajeet-at-linkedin">LinkedIn</a>, and <a href="https://tinyurl.com/ajeet-at-github">GitHub</a> for the latest articles, tips, and insights.</li><li>If you enjoyed this article, please give it some 👏 to help others discover it and encourage me to do more of it.</li><li>Feeling generous? <a href="https://tinyurl.com/support-ajeet">Buy me a coffee</a> to fuel my coding sessions and keep the content flowing!</li></ul><h3>Share Your Feedback</h3><p>I am looking forward to your feedback and suggestions! If you have any comments, questions, or ideas for future tutorials, feel free to reach out to me. You can:</p><ul><li>Leave a comment below the tutorial</li><li>Send me a direct message on Twitter or LinkedIn</li><li>Open an issue or pull request on the GitHub repository</li></ul><p>Your feedback helps me improve the quality of the content and tailor it accordingly.</p><p>Thanks for being a part of my journey! Don’t forget to connect, clap, and support if you found this helpful.</p><h3>Move to Part 2</h3><p><a href="https://tinyurl.com/100Apps100DaysFlutter-Day3-2">Cooking up a Recipe App in Flutter: Grids, Widgets, and Navigation [Part — 2]</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=775272f9f8b8" width="1" height="1" alt=""><hr><p><a href="https://digitalcurry.in/flutter-recipe-cooking-up-a-recipe-app-in-flutter-grids-widgets-and-navigation-775272f9f8b8">[Flutter Recipe] Cooking up a Recipe App in Flutter: Grids, Widgets, and Navigation</a> was originally published in <a href="https://digitalcurry.in/">Digital Curry</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[Flutter Recipe] Create a Weather App in Flutter: Integrating APIs and Handling Data]]></title>
            <link>https://digitalcurry.in/flutter-recipe-create-a-weather-app-in-flutter-integrating-apis-and-handling-data-0c4649ba4db1?source=rss-832bb7be7335------2</link>
            <guid isPermaLink="false">https://medium.com/p/0c4649ba4db1</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[100appsin100daysflutter]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Ajeet Kumar]]></dc:creator>
            <pubDate>Sat, 12 Oct 2024 18:19:23 GMT</pubDate>
            <atom:updated>2024-11-02T08:53:01.812Z</atom:updated>
            <content:encoded><![CDATA[<h4>Day — 2| 100 Apps in 100 Days Challenge with Flutter</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*Ur3PoUenHkEpV_czlu9iLg.png" /></figure><p>Welcome to day-2 of our series on learning Flutter by building apps! In this tutorial, we’ll focus on how to integrate APIs to fetch data and handling that data efficiently using the GetX library.</p><p>Throughout this post, we’ll cover the following topics:</p><ul><li>Setting up a Flutter project and installing necessary dependencies</li><li>Integrating with the OpenWeatherMap API to fetch weather data</li><li>Parsing JSON responses and handling errors</li><li>Using GetX for state management and dependency injection</li><li>Implementing a clean and organized project structure</li><li>Building the user interface for the home screen, location search screen, and about screen</li><li>Navigating between screens using GetX navigation</li></ul><p>We’ll concentrate on the core functionality of fetching and managing data from server/backend.</p><p>By the end, you’ll have a fully functional weather app that demonstrates best practices in Flutter development, including API integration, state management, and code organization.</p><h3>Prerequisites</h3><p>To follow along, you will need:</p><ul><li>Basic knowledge of Dart programming language. If not, no issues, it&#39;s really easy to learn if you know any other programming language.</li><li>Flutter SDK installed on your machine (<a href="https://flutter.dev/docs/get-started/install">Installation Guide</a>)</li><li>A code editor of your choice (e.g., Android Studio, VS Code). <em>For this post and future posts we will be using Android Studio as I am more comfortable with that. But, you can use anything that you are comfortable with.</em></li><li>GetX library added to your Flutter project (<a href="https://pub.dev/packages/get#installing">GetX Installation Guide</a>)</li></ul><h3>Setting Up the Project</h3><p>Lets create a new Flutter project.</p><ol><li>You can create a new flutter project by using the following command.</li></ol><pre>flutter create weather_app</pre><p>You can also use Android Studio to create a flutter project as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/988/1*vVdq_dvsS_QjdIZP5r15aA.png" /></figure><p>2. Once project is created, open pubspec.yaml file and add the following dependencies.</p><pre>dependencies:<br>  flutter:<br>    sdk: flutter<br>  get: ^4.3.8<br>  http: ^0.13.3</pre><p>After editing your file should look like as follows. Use Pub get to download the added dependencies to the project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gw3osMYQQq7LvTALrrHudQ.png" /></figure><p>You can also use the following command from your project directory to download the dependencies using Terminal.</p><pre>flutter pub get</pre><p>Your project is now setup.</p><h3>App Architecture</h3><p>Our app will have the following responsibilities and features:</p><ol><li>Fetch weather data for a city using OpenWeatherMap APIs.</li><li>Show that information on Home screen.</li><li>User should also be able to add multiple cities to Home screen and swipe left-right to see weather information for other cities.</li><li>App should also have an About screen to show general information about the app, developer, etc.</li></ol><p>Below shows a round architecture of the app as described above.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BgKUWK3EfM7ty-A5hcFkEg.png" /></figure><p>Below I have tried to show how our project will look like at the end.</p><pre>lib/<br>└── app/<br>    ├── controllers/<br>    │   └── app_controller.dart<br>    ├── modules/<br>    │   ├── about/<br>    │   │   └── about_screen.dart<br>    │   ├── home/<br>    │   │   ├── bindings/<br>    │   │   │   └── home_binding.dart<br>    │   │   ├── models/<br>    │   │   │   └── weather_data.dart<br>    │   │   ├── views/<br>    │   │   │   ├── weather_screen/<br>    │   │   │   │   └── weather_screen.dart<br>    │   │   │   └── home_view.dart<br>    │   │   └── widgets/<br>    │   │       └── weather_details.dart<br>    │   └── location_search/<br>    │       ├── bindings/<br>    │       │   └── add_place_binding.dart<br>    │       └── views/<br>    │           └── add_place_view.dart<br>    ├── routes/<br>    │   └── app_pages.dart<br>    ├── services/<br>    │   └── api_service.dart<br>    ├── app.dart<br>    └── main.dart</pre><p>If you look closely, I have divided the features into</p><ul><li><strong>modules</strong> — about, home and location_search</li><li><strong>routes</strong> — defines routes and manage navigation within the app</li><li><strong>controllers</strong> — Since for this app it makes sense to have a global controller so its defined at top level. But, if your app manages complexities of a feature or module then it can also be defined at the module level. It entirely depends on your preference and the app you are building.</li><li><strong>services</strong> — This generally covers network layer classes.</li><li><strong>models</strong> — These are defined at module level as required for this app. But you can take another approach which might suite your app requirements better.</li></ul><p>This ensures that the code is managable while clearly segregating the responsibilities. This structure also makes extending the app with new features very easy.</p><h3>Integrating the Weather API</h3><p>We will be using OpenWeatherMap APIs to fetch weather information for our app. But, you can use any weather service that you prefer. If you do decide to use some other service, then make sure to make necessary changes to the files mentioned below.</p><ol><li>Sign up for a free API key at <a href="https://openweathermap.org/">OpenWeatherMap</a>.</li><li>Once you have the key, create a new fileapi_service.dart inside lib folder as shown below:</li></ol><pre>lib/<br>└── app/<br>    ├── services/<br>    │   └── api_service.dart<br></pre><p>Paste the following code in the file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a83b5b3fe595750461de662f8984aefd/href">https://medium.com/media/a83b5b3fe595750461de662f8984aefd/href</a></iframe><p>We will also need the weather_data.dart file which defines the structure of the API response. We have created the file at the following location.</p><pre>lib/<br>└── app/<br>    ├── modules/<br>    │   ├── home/<br>    │   │   ├── models/<br>    │   │   │   └── weather_data.dart</pre><p>Paste the following code into it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7f1545aa4260bda61d03dfaf53360920/href">https://medium.com/media/7f1545aa4260bda61d03dfaf53360920/href</a></iframe><p>This object is used to parse the json response from the server. Here, we have also tried to extend the class by adding an additional variable — cityImgUrl to store the background image respective to the city.</p><p>Replace &#39;&lt;PROVIDE YOUR OWN API KEY&gt;&#39; with the API key you obtained from OpenWeatherMap. This code defines an ApiService class with a static method getWeatherData that takes a city parameter. It constructs the API URL, sends a GET request using the http package, and returns the parsed JSON response as a WeatherData object for easier use within the app. If the request fails or the response status code is not 200, it throws an exception.</p><h3>Handling Data with GetX</h3><p>In the context of the weather app, it’s generally recommended to have a single global controller (in this case, the AppController) that manages the state and business logic related to weather data across multiple screens. This promotes a centralized and cohesive approach to state management.</p><p>Here are a few reasons why using a single global controller is preferred in this scenario:</p><ol><li><em>Shared state</em>: The AppController holds the list of added cities and their corresponding weather data. This state is shared between the HomeScreen and the AddPlaceView. By using a single controller, you can easily access and modify the shared state from both screens without the need for complex state synchronization.</li><li><em>Consistency</em>: Having a single source of truth for weather-related data ensures consistency throughout the app. It prevents duplication of data and avoids potential inconsistencies that may arise from managing the same data in multiple controllers.</li><li><em>Simplified communicatio</em>n: With a single global controller, communication between screens becomes simpler. For example, when a city is added in the AddPlaceView, it can directly call the fetchWeatherData method of the AppController to update the weather data. There&#39;s no need for additional coordination between separate controllers.</li><li><em>Reusability</em>: If you decide to add more screens or features related to weather data in the future, having a centralized AppController makes it easier to reuse the existing state and logic. You can easily extend or modify the controller to accommodate new requirements without affecting other parts of the app.</li><li><em>Testing</em>: With a single controller responsible for managing weather-related state and logic, testing becomes more straightforward. You can focus on testing the AppController independently, ensuring that it behaves correctly and handles different scenarios properly.</li></ol><p>Create a new file named app_controller.dart inside the lib/app/controllers/ folder and add the following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8d30579e1bd6a76b10e5acb15948ed9d/href">https://medium.com/media/8d30579e1bd6a76b10e5acb15948ed9d/href</a></iframe><p>This code defines a AppController class that extends GetxController. It has a reactive _weatherData map that stores the weather data for each added city. The fetchWeatherData method calls the ApiService.getWeatherDatamethod to fetch the weather data for a given city and stores it in the _weatherData map. If an error occurs, it displays a snackbar using Get.snackbar. The getWeatherDataForCity method retrieves the weather data for a specific city, and the addedCities getter returns a list of all the added cities.</p><p>Its also defines a changePage method to record when user is switching the page. It updates another reactive currentPage variable. This helps control which city to show and also manage the state of page indicator in HomeView.</p><h3>Defining App Navigation</h3><p>With the APIs being handled, let’s define the app screens and navigation routes for our app.</p><ol><li>Create a new app_page.dart file at location lib/app/routes and paste the following code.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/023ecf2ce6509facf5c1e41e53e8c666/href">https://medium.com/media/023ecf2ce6509facf5c1e41e53e8c666/href</a></iframe><p>The AppPages class serves as a central place to declare the app&#39;s routes and their corresponding screens and bindings. Each route is represented by a GetPage object, specifying the route name, screen widget, and binding (if any). The INITIAL constant in AppPages sets the initial route of the app.</p><p>The Routes and _Paths abstract classes provide constants for route names and path strings, respectively.</p><p>Bindings (e.g., HomeBinding, AddPlaceBinding) are used for dependency injection or setup logic before navigating to a screen.</p><p>2. Create another file app.dart at /lib/app and paste the code below. This class define the GetMaterialApp and specifies the routes and pages.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/680275b483e694b0cf59254c6c5f6cfd/href">https://medium.com/media/680275b483e694b0cf59254c6c5f6cfd/href</a></iframe><p>Here you can see how the app is navigated to HomeView using initialRoute property.</p><p>3. Update the code in main.dart to include the above.</p><pre>void main() {<br>  runApp(MyApp());<br>}</pre><h3>Module — Home</h3><p>This is the main module in our app. As a rule of thumb we always have following structure for our module to make is well defined and manageable.</p><pre>module<br>|-bindings // for bindings related to the views in the module<br>|-models  // any data classes that is used by the view is placed here<br>|-views  // all views associated with this module<br>|-widgets  // any widgets which are specific to this module.</pre><p>The GetX library suggests structuring Flutter app code into modules, which offers several key benefits:</p><ol><li>Organizing code into feature-specific modules improves code organization, navigation, and understanding.</li><li>GetX’s lazy loading capability enhances app performance by loading modules on-demand, reducing initial startup time and memory usage.</li><li>The modular architecture also facilitates effective testing and debugging, as modules can be tested independently.</li></ol><p>Additionally, GetX’s dependency injection system integrates well with modular architecture, promoting loose coupling between modules. By adopting the modular approach suggested by GetX helps build well-structured, efficient, and maintainable apps that are easier to scale and enhance over time.</p><p>Create new files home_binding.dart, weather_screen.dart, weather_details.dart and home_view.dart as shown in the structure below:</p><pre><br>lib/<br>└── app/<br>    ├── modules/<br>    │   ├── home/<br>    │   │   ├── bindings/<br>    │   │   │   └── home_binding.dart<br>    │   │   ├── models/<br>    │   │   │   └── weather_data.dart<br>    │   │   ├── views/<br>    │   │   │   └── home_view.dart<br>    │   │   └── widgets/<br>    │   │       └── weather_details.dart<br>    |   │       └── weather_screen.dart<br> <br><br><br><br>  </pre><p><strong>home_binding.dart</strong></p><p>Open the file and paste the code as shown:</p><pre>import &#39;package:get/get.dart&#39;;<br>import &#39;package:weather_app/app/controllers/app_controller.dart&#39;;<br><br>class HomeBinding extends Bindings {<br>  @override<br>  void dependencies() {<br>    Get.lazyPut&lt;AppController&gt;(<br>          () =&gt; AppController(),<br>    );<br>  }<br>}</pre><p>HomeBinding class extending the Bindings class from the GetX library, is used to bind dependencies for the home module.</p><p>Get.lazyPut&lt;AppController&gt;() takes a factory function as a parameter, which is responsible for creating an instance of the AppController class. The Get.lazyPut&lt;AppController&gt;() function ensures that the AppController instance is created lazily, meaning it will only be instantiated when it is first accessed or required.</p><p><strong>home_view.dart</strong></p><p>It is the main screen of the weather app. It displays a PageView that allows users to swipe between different cities&#39; weather information. Copy the below code to the file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7815a8a86fa687c155af3ef5093c6b4e/href">https://medium.com/media/7815a8a86fa687c155af3ef5093c6b4e/href</a></iframe><ul><li>The HomeView extends GetView&lt;AppController&gt;, which automatically injects the AppController instance and makes it accessible through the controller property.</li><li>The build method returns a Scaffold widget that contains a Stack with two main components:</li><li>A PageView.builder that creates a scrollable list of WeatherScreen widgets, one for each added city.</li><li>A SafeArea widget that contains a static top bar with an &quot;Add City&quot; button and an &quot;About&quot; button, as well as a page indicator at the bottom.</li><li>The PageView.builder uses the addedCities list from the AppController to determine the number of pages and the city names.</li><li>For each city, the corresponding weather data is retrieved using the getWeatherDataForCity method from the AppController.</li><li>The WeatherScreen widget is created with the retrieved weather data and displayed in the PageView.</li><li>The _buildStaticTopBar and _buildPageIndicator methods are helper methods to create the top bar and page indicator widgets, respectively.</li></ul><p><strong>weather_screen.dart</strong></p><p>It’s the widget that creates the UI for the home screen. One such example for Paris is shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*us7hnYPKXtlrVQWjHP1mIw.png" /></figure><p>Copy the following code to the file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d707e331549b2d38e8f9031350f97e2d/href">https://medium.com/media/d707e331549b2d38e8f9031350f97e2d/href</a></iframe><ul><li>The WeatherScreen widget receives a WeatherData object through its constructor.</li><li>The background image is loaded using the cityImgUrl property from the WeatherData object. Right now the urls are hard coded into the app, but there are free api servies using which you can fetch an image for a city at runtime and load it into the UI.</li><li>A random dark pastel color is generated using the _getRandomDarkPastelColor method and applied as a semi-transparent overlay on top of the background image.</li><li>The weather information is displayed using the WeatherDetails widget.</li></ul><p><strong>weather_details.dart</strong></p><p>It displays additional weather details such as pressure, wind speed, and humidity. Copy the following code to the file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/168b0bcf31a357868808f5ba94540b63/href">https://medium.com/media/168b0bcf31a357868808f5ba94540b63/href</a></iframe><ul><li>The WeatherDetails widget receives the pressure, humidity, and wind speed data through its constructor.</li><li>Inside the container, a Row widget is used to display three detail items: pressure, wind speed, and humidity.</li><li>Each detail item is created using the _buildDetailItem method, which takes an icon, label, and value as parameters.</li><li>The detail items are evenly spaced using the MainAxisAlignment.spaceAround property of the Row widget.</li></ul><h3>Module — Location Search</h3><p>This module adds the capability to search and add a place to the app to check their weather information. Right now the city list is hard coded but very easily it can be made to load the city list from server by following how we are loading data from OpenWeatherMap api.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r0BageHKwSWcuwpxumCySw.png" /></figure><p>Create 2 new files — add_place_binding.dart, add_place_view.dart within the location search module at /lib/app/modules/location_search/bindings and /lib/app/modules/location_search/views respectively.</p><p><strong>add_place_binding.dart</strong></p><p>Copy the following code to the file:</p><pre>class AddPlaceBinding extends Bindings {<br>  @override<br>  void dependencies() {<br>    Get.lazyPut&lt;AppController&gt;(<br>        () =&gt; AppController()<br>    );<br>  }<br>}</pre><p>The purpose of this file is to set up the dependency injection for the AddPlaceView. It uses Get.lazyPut() to lazily initialize the AppController. By setting up the binding, the AppController becomes available for injection in the AddPlaceView, allowing the view to access and interact with the controller&#39;s methods and properties.</p><p><strong>add_place_view.dart</strong></p><p>It represents the “Add Place” screen in the weather app. Add the following code to the file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f9a94ca6b6b003375c8473feb5a019ae/href">https://medium.com/media/f9a94ca6b6b003375c8473feb5a019ae/href</a></iframe><p>The AddPlaceView extends GetView&lt;AppController&gt;, which automatically injects the AppController instance and makes it accessible through the controller property.</p><p>The view contains a search field where users can enter a city name to filter the list of available cities. The list of cities is stored in the _cities list, and the filtered list is managed by the _filteredCities reactive list.</p><p>The view also defines a map called _cityUrls, which associates each city with a corresponding image URL. These image URLs will be used as background images for the weather screens.</p><p>When the user taps the add button next to a city, the _addCity method is called. It invokes the fetchWeatherData method of the AppController, passing the selected city and its corresponding image URL. After fetching the weather data, it navigates back to the previous screen using Get.back().</p><h3>Module — About</h3><p>Its a simple screen showing some details about the app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-psik6VrKDmLgaMBz0FjMA.png" /></figure><p>Create a about_Screen.dart file at /lib/app/module/about and add the following code to the file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6a4a9261f541402c294e928a9b90a480/href">https://medium.com/media/6a4a9261f541402c294e928a9b90a480/href</a></iframe><p>It displays the app name, the developer’s name, and a copyright notice. It also includes a “Close” button at the bottom, which allows the user to dismiss the “About” screen and return to the previous screen.</p><h3>Final Result</h3><p>You can now run the weather app on an emulator or a physical device either from command line or the play button. You should be able to add cities and view their weather information now, similar to what is shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/222/1*xRi2Z4V2DybDD8shDF7RRQ.gif" /></figure><p>You can find the entire code for this app at the following github repository:</p><p><a href="https://github.com/ajeet-repos/weather-app.git">GitHub - ajeet-repos/weather-app: A fully functional weather app using Flutter and GetX.</a></p><h3>Conclusion</h3><p>Congratulations! 👏 You have successfully built a weather app in Flutter that integrates with the OpenWeatherMap API, handles data using the GetX library, and provides a user-friendly interface. You’ve learned how to:</p><ul><li>Set up a Flutter project and install the required dependencies</li><li>Integrate with a weather API to fetch data</li><li>Parse JSON responses and handle errors</li><li>Use GetX for state management across different screens and navigate between them</li><li>Implement the UI for the home screen, location search screen, and about screen</li></ul><p>You can further enhance the app by adding more features, such as:</p><ul><li>Displaying more detailed weather information (e.g., daily forecasts, weather maps, etc.)</li><li>Historical charts</li><li>Adding dynamic animations based on the type of weather.</li></ul><p>These are some of the ways but the possibilities are endless.</p><h3>Share Your Feedback</h3><p>I am looking forward to your feedback and suggestions! If you have any comments, questions, or ideas for future tutorials, feel free to reach out to me. You can:</p><ul><li>Leave a comment below the tutorial</li><li>Send me a direct message on Twitter or LinkedIn</li><li>Open an issue or pull request on the GitHub repository</li></ul><p>Your feedback helps me improve the quality of the content and tailor it accordingly.</p><h3>Stay Connected</h3><p>If you found this tutorial helpful, I’d love to keep you in the loop! Here’s how you can stay connected and support my work:</p><ul><li>Follow me on <a href="https://x.com/__ajeetkumar__">Twitter</a>, <a href="https://www.linkedin.com/in/ajeet2511/">LinkedIn</a>, and <a href="https://github.com/ajeet-repos">GitHub</a> for the latest articles, tips, and insights.</li><li>If you enjoyed this article, please give it some 👏 to help others discover it.</li><li>Feeling generous? <a href="https://buymeacoffee.com/ajeet">Buy me a coffee</a> to fuel my coding sessions and keep the content flowing!</li></ul><p>Thanks for being a part of my journey! Don’t forget to connect, clap, and support if you found this helpful.</p><h3>Move To Day — 3</h3><p><a href="https://tinyurl.com/100Apps100DaysFlutter-Day3-1">Cooking up a Recipe App in Flutter: Grids, Widgets, and Navigation [Part — 1]</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0c4649ba4db1" width="1" height="1" alt=""><hr><p><a href="https://digitalcurry.in/flutter-recipe-create-a-weather-app-in-flutter-integrating-apis-and-handling-data-0c4649ba4db1">[Flutter Recipe] Create a Weather App in Flutter: Integrating APIs and Handling Data</a> was originally published in <a href="https://digitalcurry.in/">Digital Curry</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[Flutter Recipe] Building a ToDo App with Flutter: Mastering the Fundamentals]]></title>
            <link>https://digitalcurry.in/flutter-recipe-building-a-todo-app-with-flutter-mastering-the-fundamentals-53a83e50b1f8?source=rss-832bb7be7335------2</link>
            <guid isPermaLink="false">https://medium.com/p/53a83e50b1f8</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[100appsin100daysflutter]]></category>
            <dc:creator><![CDATA[Ajeet Kumar]]></dc:creator>
            <pubDate>Wed, 09 Oct 2024 04:49:30 GMT</pubDate>
            <atom:updated>2024-10-12T18:27:41.785Z</atom:updated>
            <content:encoded><![CDATA[<h4>Day — 1 | 100 Apps in 100 Days Challenge with Flutter</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*vFyBZ4N84ZJlCp-FXLWlHQ.png" /></figure><p>Flutter has taken the mobile app development world by storm, and for good reason. This powerful framework, developed by <a href="https://medium.com/u/be36e94a7e47">Google</a>, allows any developer/company to create beautiful, high-performance apps for both iOS and Android from a single code base while maintaining the same experience for the users. With its rich set of customizable widgets, reactive programming model, and extensive package ecosystem, Flutter makes it easy to build stunning and functional apps in record time.</p><p>In this post, we’ll dive into the world of Flutter and explore its fundamental concepts by building a practical and feature-rich <strong>ToDo</strong> app. We’ll learn how to:</p><ul><li>Set up a Flutter development environment</li><li>Design an attractive user interface using Flutter widgets</li><li>Manage app state efficiently with the GetX library</li><li>Implement data persistence for offline functionality</li></ul><p>For state management in Flutter, their are two popular choices — GetX and BLoC (Business Logic Component). While both approaches have their merits, we’ve chosen to use GetX in this tutorial for following reasons:</p><ol><li><strong>Simplicity</strong>: GetX offers a simple and intuitive way to manage state, navigate between screens, and handle dependencies. It provides a cohesive solution without the need for excessive boilerplate code or complex setup.</li><li><strong>Reactive Programming</strong>: GetX leverages the power of reactive programming, allowing you to easily update the UI whenever the underlying data changes. With its observable variables and streams, GetX makes it straightforward to create responsive and dynamic user interfaces.</li><li><strong>Flexibility</strong>: GetX is a flexible library that can be used in conjunction with other Flutter packages and architectures. It doesn’t enforce strict architectural patterns, giving you the freedom to structure your app in a way that suits your needs.</li><li><strong>Comprehensive Ecosystem</strong>: GetX goes beyond state management and provides a wide range of useful features, such as route management, dependency injection, internationalization, and more. It offers a comprehensive solution for building complete Flutter apps.</li></ol><p>By the end of this tutorial, we’ll have a solid understanding of Flutter’s core principles and be well-equipped to create our own impressive mobile apps. Let’s get started and unleash the power of Flutter! 🚀 🚀🚀</p><h3>Prerequisites</h3><p>Before we embark on this journey, please make sure you have the following prerequisites in place:</p><ul><li>Basic knowledge of Dart programming language. If not, no issues, its really easy to learn if you know any other programming language.</li><li>Flutter SDK installed on your machine (<a href="https://flutter.dev/docs/get-started/install">Installation Guide</a>)</li><li>A code editor of your choice (e.g., Android Studio, VS Code). <em>For this post and future posts we will be using Android Studio as I am more comfortable with that. But, you can use anything that you are comfortable with.</em></li><li>GetX library added to your Flutter project (<a href="https://pub.dev/packages/get#installing">GetX Installation Guide</a>)</li></ul><h3>Step 1: Setting up the Project</h3><p>Let’s start by creating a new Flutter project and configuring the necessary dependencies.</p><ol><li>Open Android Studio and create a new Flutter project.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LcW5xba4CfiqFLNvkx4_GA.png" /></figure><p>2. Click on Next to specify project name and location of the project directory. For this demo I have specified it as shown in the image. You can you choose any name of your choice.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7C0ONsOLMH5AdGOFQPkrkg.png" /></figure><p>For now, I have selected only iOS and Android as these will be the focus of this series. <em>Based on what feedback i get from this challenge, I will try to take them up in another series.</em></p><p>3. Open pubspec.yaml file and add the dependency for Get library to the project as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vHm-CVcz7F0UDyIMFaW-Vw.png" /></figure><p>4. If you run the project now, you should be able to see the following output in your iOS or Android simulator or device.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*IUiQ6rdjt2VwyQNsXm4xNg.png" /></figure><p>With the project setup complete, we’re now ready to start building our app!</p><h3>Step 2: Designing the User Interface</h3><p>A well-designed user interface is crucial for a seamless user experience and must for a developer to be able to implement in a cleaner and robust manner. In this step, we’ll create the basic UI for our app using Flutter widgets and the GetX library.</p><ol><li>Open the lib/main.dart file and replace its contents with the following code:</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b3d4456a47385b0cc6c2e35040f0b28c/href">https://medium.com/media/b3d4456a47385b0cc6c2e35040f0b28c/href</a></iframe><p>In this code, we define the TodoApp widget, which serves as the root of our application. We use the GetMaterialApp widget provided by the GetX library to set up the app&#39;s title, theme, and home screen.</p><p>The TodoListScreen widget represents the main screen of our app, where the list of todo items will be displayed. It includes an AppBar with a title, a centered placeholder text, and a floating action button for adding new todo items.</p><ol><li>Run the app using the following command or play button in Android Studio.</li></ol><pre>flutter run</pre><p>You should see a basic UI with an app bar, a placeholder text, and a floating action button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*qn2Z5Acx1Vdq1AzxfPqF4w.png" /></figure><p><em>Feel free to make any changes to the UI to make it yours.</em></p><h3>Step 3: Managing State with GetX</h3><p>State management is a one of the most critical aspect of building dynamic and interactive apps. GetX provides a simple and efficient way to manage state in Flutter apps. In this step, we’ll create a TodoController to handle the state of our todo items.</p><ol><li>Create a new file named todo_controller.dart in the lib directory.</li><li>Open the todo_controller.dart file and add the following code:</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d19657e6f817ca654775b4ef60d587aa/href">https://medium.com/media/d19657e6f817ca654775b4ef60d587aa/href</a></iframe><p>In above code, we define a TodoItem class to represent an individual todo item, with a title and a completed status.</p><p>The TodoController class extends GetxController and manages the state of our todo list. It includes an observable list of TodoItem objects (todoList) and methods to add, toggle, and remove todo items.</p><p>The .obs extension makes the todoList observable, allowing GetX to automatically update the UI whenever the list changes. This helps remove the entire code responsibility of manually updating the data and syncing the UI to reflect the same.</p><p>3. Update the main.dart file to use the TodoController:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8e83b230325943e2c39f2a78987c31b4/href">https://medium.com/media/8e83b230325943e2c39f2a78987c31b4/href</a></iframe><p>In this updated code, we create an instance of the TodoController using Get.put() and access it in the TodoListScreen widget.</p><p>We use the Obx widget provided by GetX to automatically rebuild the UI whenever the todoList changes. The ListView.builder constructs the list of todo items based on the todoList data. It comes in handy when you want to do quick prototyping.</p><p>The floating action button now opens a dialog where the user can enter a new todo title. When the title is submitted, it calls the addTodo method of the TodoController to add the new item to the list.</p><p>4. Run the app again and you should see a functional todo list where you can add, toggle, and remove items.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*ZVj1zXCXJqtKgIQJyDjYPg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*GB7ln-XQudGK40LU9emYhw.png" /></figure><h3>Step 4: Persisting Data with GetX</h3><p>To ensure that our todo items are not lost when the app is closed or restarted, we need to persist the data. GetX provides a simple way to store and retrieve data using its GetStorage package.</p><p>When you use GetStorage to save data, it automatically determines the appropriate storage location based on the platform. Here’s where GetStorage saves the data:</p><ul><li><strong>Android</strong>: GetStorage uses SharedPreferences to store data. The data is saved in a file located at /data/data/&lt;package-name&gt;/shared_prefs/ on the device&#39;s internal storage.</li><li><strong>iOS</strong>: GetStorage uses NSUserDefaults to store data. The data is saved in the app’s preferences plist file, typically located at /Documents/Library/Preferences/&lt;bundle-identifier&gt;.plist in the app&#39;s sandbox directory.</li></ul><p>GetStorage handles the platform-specific storage implementation details for you, providing a unified and convenient API to store and retrieve data across both Android and iOS.</p><ol><li>Add the get_storage package to your pubspec.yaml file:</li></ol><pre>dependencies:<br>  flutter:<br>    sdk: flutter<br>  get: ^4.6.6<br>  get_storage: ^2.1.1</pre><p>2. Run flutter pub get or use Pub get option from the Android Studio to fetch the new dependency.</p><p>3. Update the todo_controller.dart file to use GetStoragepackage.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c149575df746d68b4e846dce4660f3d1/href">https://medium.com/media/c149575df746d68b4e846dce4660f3d1/href</a></iframe><p>In this updated code, we add toJson and fromJson methods to the TodoItem class to convert todo items to and from JSON format.</p><p>We create an instance of GetStorage in the TodoController and use it to load and save the todo list.</p><p>The loadTodos method reads the stored JSON data and converts it back into a list of TodoItem objects.</p><p>The saveTodos method converts the current todoList into JSON format and writes it to storage.</p><p>We call loadTodos in the onInit method to load the persisted data when the controller is initialized, and we call saveTodos after each operation (add, toggle, remove) to keep the stored data in sync with the current state.</p><p>4. If you run the app now, you will notice that the todo lists are not loaded whenever the app is restarted. Reason for this error is that GetStorage needs to be initialized before it can be used to read or write.</p><p>To fix this error, we need to initialize GetStorage before initializing the app. Modify the main() function in main.dart file as follows:</p><pre>Future&lt;void&gt; main() async {<br>  await GetStorage.init();<br>  runApp(TodoApp());<br>}</pre><p>Above changes would ensure that GetStorage is ready whenever app is launched/restarted.</p><p><em>Notice that we had to change the signature of </em><em>main() function because of using </em><em>await inside the function.</em></p><p>5. Run the app again and your todo items should now persist even when you close and reopen the app.</p><h3>Conclusion</h3><p>Congratulations! We’ve built a fully functional todo app using Flutter and the GetX library. Throughout this tutorial, we’ve learned the fundamentals of Flutter development, including:</p><ul><li>Basic UI design using Flutter widgets</li><li>State management with GetX and observable variables</li><li>Data persistence using GetX’s GetStorage package</li></ul><p>We now have a solid foundation to expand our todo app with additional features and customize it to your liking. Some ideas for further enhancements include:</p><ul><li>Adding due dates and reminders for todo items</li><li>Implementing categories or tags for better organization</li><li>Integrating cloud sync for accessing todos across multiple devices</li></ul><p>Feel free to explore the GetX documentation to discover more advanced features and capabilities. The official Flutter and GetX websites also provide a wealth of resources and tutorials to deepen your knowledge.</p><p>We hope this tutorial has been informative and engaging. If you have any questions or feedback, please don’t hesitate to reach out. Happy coding, and enjoy using your new todo app to boost your productivity!</p><p>Please find the repository for this project linked below. Use it however you like it. If you find any issue with the code, feel free to either raise a PR request or mention that in the comments.</p><p><a href="https://github.com/ajeet-repos/todo_app.git">GitHub - ajeet-repos/todo_app: A quick and dirty ToDo app made using flutter and GetX package.</a></p><h3>Continue to your journey to day 2 of learning flutter</h3><p><a href="https://digitalcurry.in/flutter-recipe-create-a-weather-app-in-flutter-integrating-apis-and-handling-data-0c4649ba4db1">Day — 2 | 100AppsIn100Days Challenge With Flutter</a></p><p>In this we will cover the following topics:</p><ul><li>Setting up a Flutter project and installing necessary dependencies</li><li>Integrating with the OpenWeatherMap API to fetch weather data</li><li>Parsing JSON responses and handling errors</li><li>Using GetX for state management and dependency injection</li><li>Implementing a clean and organized project structure</li><li>Building the user interface for the home screen, location search screen, and about screen</li><li>Navigating between screens using GetX navigation</li></ul><p><em>Thanks for reading. If you liked this article make sure to give it a </em>👏.<em> And if you would like to support me, please consider buying me a coffee. </em>🙂</p><figure><a href="http://buymeacoffee.com/ajeet"><img alt="" src="https://cdn-images-1.medium.com/max/217/0*TCm-goQvCzrOmeVk.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=53a83e50b1f8" width="1" height="1" alt=""><hr><p><a href="https://digitalcurry.in/flutter-recipe-building-a-todo-app-with-flutter-mastering-the-fundamentals-53a83e50b1f8">[Flutter Recipe] Building a ToDo App with Flutter: Mastering the Fundamentals</a> was originally published in <a href="https://digitalcurry.in/">Digital Curry</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[100 Days of Flutter: Mastering Mobile App Development through Hands-On Projects]]></title>
            <link>https://digitalcurry.in/100-days-of-flutter-mastering-mobile-app-development-through-hands-on-projects-11e34bb7646c?source=rss-832bb7be7335------2</link>
            <guid isPermaLink="false">https://medium.com/p/11e34bb7646c</guid>
            <category><![CDATA[100appsin100daysflutter]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Ajeet Kumar]]></dc:creator>
            <pubDate>Tue, 08 Oct 2024 20:03:18 GMT</pubDate>
            <atom:updated>2024-10-13T07:09:19.292Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*StdNkdKOEZx3Krs6q0VUSw.jpeg" /></figure><p>Are you ready to embark on an exciting journey to become a proficient Flutter developer? Look no further! I have taken on the ambitious challenge of learning Flutter from scratch in just 100 days by building 100 unique and practical apps.</p><p>Why learn by building, you might ask? Traditional tutorials and courses are valuable resources, but they often lack the hands-on experience and real-world problem-solving that are crucial for mastering a framework like Flutter. By diving headfirst into building apps, you’ll encounter a wide range of scenarios, challenges, and opportunities to apply your knowledge in meaningful ways.</p><p>Over the course of these 100 days, I will be creating a diverse portfolio of Flutter apps, each focusing on specific concepts and features. From basic user interfaces and navigation to advanced state management and API integration, these projects will cover the essential aspects of Flutter development.</p><p>By taking this project-based approach, we’ll gain several key benefits:</p><ol><li><strong>Rapid skill acquisition</strong>: Building apps from scratch allows you to learn by doing, accelerating your understanding of Flutter’s core concepts and best practices.</li><li><strong>Problem-solving prowess</strong>: As you encounter challenges and obstacles along the way, you’ll develop the problem-solving skills necessary to overcome them, making you a more resilient and adaptable developer.</li><li><strong>Real-world experience</strong>: Working on a variety of projects exposes you to different use cases, designs, and requirements, preparing you for the diverse needs of real-world app development.</li><li><strong>Portfolio building</strong>: By the end of the 100 days, you’ll have an impressive portfolio of Flutter apps to showcase your skills and attract potential clients or employers.</li></ol><p>Throughout this journey, I will be sharing my progress, insights, and lessons learned, providing you with a roadmap to follow along and embark on your own Flutter learning adventure.</p><p>So, are you ready to accept the challenge and transform yourself into a confident and capable Flutter developer? Join me on this 100-day journey, and let’s unlock the power of Flutter together, one app at a time!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*opHGGsXDS0CFt7WL" /><figcaption>Photo by <a href="https://unsplash.com/@bradencollum?utm_source=medium&amp;utm_medium=referral">Braden Collum</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Day — 1</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*AC4JwpZn-DnP4mWkRcxtWg.gif" /></figure><p><a href="https://digitalcurry.in/flutter-recipe-building-a-todo-app-with-flutter-mastering-the-fundamentals-53a83e50b1f8">[Flutter Recipe] Building a ToDo App with Flutter: Mastering the Fundamentals</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=11e34bb7646c" width="1" height="1" alt=""><hr><p><a href="https://digitalcurry.in/100-days-of-flutter-mastering-mobile-app-development-through-hands-on-projects-11e34bb7646c">100 Days of Flutter: Mastering Mobile App Development through Hands-On Projects</a> was originally published in <a href="https://digitalcurry.in/">Digital Curry</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Meet Llama 3.1: The Open-Source AI That Rivals the Giants]]></title>
            <link>https://digitalcurry.in/meet-llama-3-1-the-open-source-ai-that-rivals-the-giants-7c34dc264d99?source=rss-832bb7be7335------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c34dc264d99</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[meta]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[llama-3-1]]></category>
            <dc:creator><![CDATA[Ajeet Kumar]]></dc:creator>
            <pubDate>Wed, 24 Jul 2024 11:51:23 GMT</pubDate>
            <atom:updated>2024-07-24T11:51:23.310Z</atom:updated>
            <content:encoded><![CDATA[<h3>Meta’s Llama 3.1: A Deep Dive into the Open-Source AI Revolution</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Tbz_olyaTXWvWWzG9A7NsA.png" /></figure><p>Hold onto your hats, AI aficionados! Meta’s just dropped a bombshell with Llama 3.1, and trust me, it’s not just hype. This isn’t a casual stroll down the AI avenue; it’s a full-blown sprint towards a future where open-source reigns supreme. As someone who likes exploring the intricacies of AI, let me break down why Llama 3.1 is sending shockwaves through the industry.</p><h3>Unveiling the Powerhouse: Llama 3.1 405B</h3><p>At the heart of this release is the behemoth itself: <strong>Llama 3.1 405B</strong>. This isn’t just another large language model (LLM) flexing its parameter count; it’s a statement. With a staggering 405 billion parameters, it stands shoulder-to-shoulder with industry giants like GPT-4 in terms of sheer capability. We’re talking next-level proficiency in:</p><ul><li><strong>General Knowledge and Reasoning:</strong> From acing complex exams to generating creative text formats, Llama 3.1 displays an uncanny ability to understand and reason about the world.</li><li><strong>Multilingual Prowess:</strong> Language barriers crumble before this polyglot. Llama 3.1’s multilingual capabilities open up a world of possibilities for global communication, research, and understanding.</li><li><strong>Unprecedented Context Length:</strong> Remember those AI chatbots that seemingly suffered from amnesia after a few sentences? Llama 3.1 scoffs at such limitations with its 128K context window, enabling it to maintain coherence and understanding over incredibly long conversations or documents.</li></ul><h3><strong>Openness: The Cornerstone of the Llama Philosophy</strong></h3><p>Now, here’s where things get truly revolutionary. Unlike its closed-source counterparts, Llama 3.1 isn’t hidden behind APIs and usage restrictions. Its model weights are freely available for download and customization. This means:</p><ul><li><strong>Unleashing Developer Freedom:</strong> Imagine the possibilities when developers can tinker with the very core of a state-of-the-art AI. They can fine-tune Llama 3.1 on specialized datasets, adapt it for unique tasks, and even build entirely new applications on top of its powerful foundation.</li><li><strong>Democratizing AI Access:</strong> Open source levels the playing field. Researchers, startups, and individuals now have access to the same cutting-edge AI technology that was once exclusive to tech giants. This fosters innovation, accelerates research, and democratizes the benefits of AI.</li></ul><h3><strong>Safety First: A Non-Negotiable Priority</strong></h3><p>Now, I know what you might be thinking — isn’t releasing such a powerful AI model into the wild a recipe for disaster? Meta’s acutely aware of the potential risks, and they’ve taken concrete steps to ensure Llama 3.1 is used responsibly:</p><ul><li><strong>Robust “Red-Teaming”:</strong> Imagine a team of ethical hackers relentlessly probing a system for weaknesses. That’s “red-teaming,” and Meta’s deployed it extensively to identify and mitigate potential vulnerabilities in Llama 3.1. This proactive approach helps ensure the model is less susceptible to misuse or malicious manipulation.</li><li><strong>Fine-Tuned for Safety:</strong> Beyond just identifying vulnerabilities, Meta’s gone a step further by “tuning” Llama 3.1 specifically for safety. This involves training the model on vast datasets that emphasize ethical considerations, reducing its likelihood of generating biased, harmful, or inappropriate content.</li><li><strong>Transparency is King:</strong> Meta’s not just <em>telling</em> us Llama 3.1 is safe; they’re <em>showing</em> us. They’ve released a detailed system card that outlines their safety methodology, evaluation metrics, and the results they’ve achieved. This transparency allows for independent scrutiny, builds trust, and encourages further collaboration within the AI community.</li></ul><h3><strong>Beyond the Model: The Llama Ecosystem</strong></h3><p>Llama 3.1 isn’t just about the model itself; it’s about building a thriving open-source ecosystem around it:</p><ul><li><strong>Llama Stack: A Common Language for AI:</strong> Imagine a world where AI tools and components seamlessly interoperate. That’s the vision behind Meta’s “Llama Stack” — a set of standardized interfaces designed to make it easier for developers to build, integrate, and share AI tools and applications.</li><li><strong>Community-Driven Development:</strong> Meta recognizes the power of collaboration. They’re actively encouraging researchers and developers to contribute to the Llama ecosystem. This collaborative spirit is already yielding impressive results, with developers creating innovative applications, fine-tuning models for specialized tasks, and even pushing the boundaries of AI safety research.</li></ul><h3><strong>The Future is Open (and Exciting!)</strong></h3><p>Meta’s release of Llama 3.1 is a defining moment in the evolution of AI. It’s a bold statement that prioritizes openness, collaboration, and responsible development. The potential applications are vast — from next-generation chatbots and virtual assistants to powerful tools for scientific research, personalized education, and creative expression.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iVgN975jDTRlpDxpouG-tA.png" /></figure><p>As someone who’s been deeply involved in the AI field for years, I’m incredibly excited about the possibilities that Llama 3.1 unlocks. This isn’t just about building better AI; it’s about building a better future — one that’s driven by collaboration, accessibility, and a shared commitment to harnessing the power of AI for good.</p><p>For more detailed information, visit the official<a href="https://ai.meta.com/blog/meta-llama-3-1/"> Meta Llama 3.1 blog post</a>.</p><p>Feel free to share your thoughts and experiences with Llama 3.1 in the comments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c34dc264d99" width="1" height="1" alt=""><hr><p><a href="https://digitalcurry.in/meet-llama-3-1-the-open-source-ai-that-rivals-the-giants-7c34dc264d99">Meet Llama 3.1: The Open-Source AI That Rivals the Giants</a> was originally published in <a href="https://digitalcurry.in/">Digital Curry</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[Flutter Recipe] How to write Unit Tests 101]]></title>
            <link>https://digitalcurry.in/flutter-recipe-how-to-write-unit-tests-101-3093179be767?source=rss-832bb7be7335------2</link>
            <guid isPermaLink="false">https://medium.com/p/3093179be767</guid>
            <category><![CDATA[ui-testing]]></category>
            <category><![CDATA[flutter-test]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <dc:creator><![CDATA[Ajeet Kumar]]></dc:creator>
            <pubDate>Sat, 25 Feb 2023 04:19:07 GMT</pubDate>
            <atom:updated>2023-02-25T04:19:07.192Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/638/1*lzcklbA9AvswHKLrIRsKvA.jpeg" /></figure><p>In coming few weeks I would be publishing articles very focused on automation testing on mobile, especially flutter given its growing interest in developer’s community. If you would like me to include the same for android or iOS please mention that in the comments and I will try to publish separate articles covering them too.</p><p>Now, getting on with testing. As you might already have some idea but for the uninitiated, there are two types of testing which we do in mobile apps or any other frontends.</p><ol><li>Functional or Usability Testing</li><li>Unit Testing.</li></ol><h3>Functional or Usability Testing</h3><p>These are the tests which try to cover user interactions within the app and how app’s UI is responding to it.</p><p>For example,</p><ul><li>What happen when a user click’s on a button?</li><li>Does camera opens when user taps on the camera button or not?</li><li>Does app moves to correct screen after successful API call, etc.</li></ul><p>There many tools present to write these kind of tests like Espresso, UIAutomator, etc.</p><h3>Unit Testing</h3><p>In this article, we’ll look at how to write unit tests for Flutter applications. Unit testing is an important aspect of software development and can help ensure the quality and reliability of your code.</p><p>In Flutter, unit tests are executed in a separate process and can be run automatically as part of your development process.</p><p>Another advantage of writing unit tests are that they run very fast because they don’t need simulator to spin up.</p><p>As the name suggests, it needs a unit or a function to test. It doesn’t test for any user interaction or flow. What it tests is if the output of a function is matching the expectation or not.</p><p>To set very simple scope for this article, we will try to write a unit test to cover a function that adds 2 numbers and outputs it’s sum.</p><p>We generally write unit tests for any kind of business logic or calculation that you are doing in the app.</p><h3>Let’s get started</h3><p>Open terminal or command prompt on your machine and type following to create a simple flutter project.</p><pre>flutter create unit_test_101</pre><p>You can change <strong>unit_test_101</strong> to any project name that you would like. Once you execute this command, flutter will try to generate a vanilla project for you.</p><p>Once finished, open the project in your favourite code editor, Visual Studio Code or Android Studio, etc.</p><p>Next, open the project’s <strong>pubspec.yaml</strong> file and verify if test dependency is already added or not. If its not present, please paste the following lines to the file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/1*kJQRk_AF_zg1TyWdkPBRbw.png" /><figcaption>pubspec.yaml</figcaption></figure><p>With project setup and all the dependencies in place, we are ready to start writing tests.</p><h3>Write you first unit test case</h3><p>In flutter, all tests are defined in Dart files with the suffix <strong>_test.dart</strong>. These test files are kept within the test directory of the project. If you look at your project right now there would already be an example test file there — widget_test.dart.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/351/1*4RZrUrdlslgh_gRuxJLfMw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/519/1*iiwD9-eugN6XmcTiS_YmEA.png" /></figure><p>Right click on test’s folder and lets create a new file named — <strong>my_first_unit_test.dart</strong>. You can choose any name for the file that you want, but always ensure that it end with suffix <strong>_test.dart</strong>. Otherwise, it won’t be recognised as a test file when you are trying to execute the test.</p><p>First thing we need to do here is to import the test package. Add following line in the code to import it.</p><pre>import &#39;package:flutter_test/flutter_test.dart&#39;;</pre><p>Then lets create a function which takes two numbers as input and returns there sum.</p><pre>int add(int a, int b) {<br>  return a+b;<br>}</pre><p>Since, we now got a unit or a function, we can then write test for it. Paste the following lines in the file. Don’t worry we will go through each line one by one.</p><pre>void main() {<br>  test(&#39;add&#39;, () {<br>    int result = add(2, 3);<br>    expect(result, 5);<br>  });<br>}</pre><p>Here, as you can see we have created a main() function as this is the starting point of execution in flutter.</p><p>Then we have used test() function. This function takes two arguments:</p><ol><li>String — Text description for the test.</li><li>Callback function — This function would contain the code for the test we would like to write.</li></ol><p>In this example, the test case verifies that the add() function is returning the expected value when called with the arguments 2 and 3.</p><p>The expect() function takes two arguments:</p><ol><li>arg 1 — This the result value that we would like to compare against the expected outcome.</li><li>arg 2 — This the expected outcome.</li></ol><p>If arg 1 matches arg 2 then we will assume that the test have passed otherwise it will give a failure error.</p><p>Your file should now look like this —</p><pre>import &#39;package:flutter_test/flutter_test.dart&#39;;<br><br>int add(int a, int b) {<br>  return a+b;<br>}<br><br>void main() {<br>  test(&#39;add&#39;, () {<br>    int result = add(2, 3);<br>    expect(result, 5);<br>  });<br>}</pre><p>Just like that, you have written your first unit test. Yay!</p><h3>Running the tests</h3><p>Running the unit tests is also very simple as it doesn’t require an active mobile simulated environment.</p><p>To run the test simple, open <strong><em>Terminal</em></strong> or <strong><em>command prompt</em></strong> on your machine → Go to your project folder and execute the following command.</p><pre>flutter test</pre><p>That’s it.</p><p>Flutter will now run all the test cases defined within test folder in your project and display the results in the terminal or command prompt window. If all the test passes then you should see a message similar to the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/921/1*WpCpzHe6W0rvcRqC9tjp3g.png" /></figure><p>To simulate a failure scenario just change the arg 2 in expect()function to some value other than 5 and run the same command. You should see a similar result showing test failure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/963/1*5LKpREQyXScDFbk45sK-Ig.png" /></figure><h3>Writing more complex test cases</h3><p>While the previous example shows how to write a simple unit test case, in practice, you will often need to write unit test cases that verify more complex behaviour.</p><p>In upcoming articles, we will try to look at more real world complex cases and discuss how to write unit tests for asynchronous code and user interface components.</p><p>Please find the repo for the same linked below.</p><p><a href="https://github.com/ajeet-repos/unit_test_101--Flutter-">GitHub - ajeet-repos/unit_test_101--Flutter-</a></p><p><em>Thanks for reading. If you liked this article make sure to give it a </em>👏.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3093179be767" width="1" height="1" alt=""><hr><p><a href="https://digitalcurry.in/flutter-recipe-how-to-write-unit-tests-101-3093179be767">[Flutter Recipe] How to write Unit Tests 101</a> was originally published in <a href="https://digitalcurry.in/">Digital Curry</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[SwiftUI Recipe] How to create a beautiful iOS Calculator App in less than 200 LOC]]></title>
            <link>https://digitalcurry.in/how-i-created-a-beautiful-calculator-in-less-than-200-loc-with-swiftui-f1640504a50d?source=rss-832bb7be7335------2</link>
            <guid isPermaLink="false">https://medium.com/p/f1640504a50d</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Ajeet Kumar]]></dc:creator>
            <pubDate>Wed, 08 Jul 2020 14:16:36 GMT</pubDate>
            <atom:updated>2020-07-09T05:28:48.105Z</atom:updated>
            <content:encoded><![CDATA[<h4>A quick recipe to showcase how significant SwiftUI is for iOS and MacOS development.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FK3xVUw093bqcD1aexMCbA.jpeg" /></figure><p>Yes, you read it right. That is how powerful SwiftUI is for iOS and MacOS development. And those who say any different, probably should give it a chance to impress themselves.</p><p>I started exploring SwiftUI after this year’s DubDub or WWDC and really liked it. A similar approach I find Google is also taking with Flutter. Given no prior experience in Swift/SwiftUI, I wanted to quickly get a glimpse of how easy and powerful it actually is. What better way to do that than create a good looking working app.</p><p>I choose to make a calculator because its a single view app and have good enough complexity to start with. And also I had the design of the app lying around. :)</p><p><em>Before we dive in, just a note that to follow this guide no prior Swift or SwiftUI is required.</em></p><h3>Step 1: Create a Xcode project</h3><p>Open Xcode, create a new <strong><em>SingleView</em></strong> application and give it a name “Calculator swiftUI”. Choose any name you like. Make sure to select <strong><em>SwiftUI</em> </strong>for <strong><em>User Interface</em></strong>. Also, select both Unit Tests and UI Tests. I will writing another piece for automated test using the same project. Its not required for this article though.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ngVEsRJ7UeAVon8KPyEsVg.png" /><figcaption>Create a project in Xcode</figcaption></figure><p>Open ContentView.swift file and add-</p><ol><li>primaryColor to the file just above the ContentView so that its accessible from the entire file.</li><li>Replace Text(“Hello World!”) with a VStack.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6982dd3ca28d3c469a7a3a85a7aaeaf4/href">https://medium.com/media/6982dd3ca28d3c469a7a3a85a7aaeaf4/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/414/1*WUyoiWcvnKFnACSSL4361A.png" /><figcaption>Basic UI building block</figcaption></figure><p>Two things to note here are how we are creating a custom color with RGB values and VStack.</p><p>VStack is a UI component which places all its child elements vertically one after another. Here we are adding two VStacks as a child to our main VStack to divide the whole screen into two parts.</p><p>To make sure both child VStack occupy the same vertical height, I am setting the maxHeight property of .frame() as .infinity. I am also setting an idealHeight reference as 414 which is half of the screen for iPhone 11.</p><p>This will create an output like the image on the left here. Don’t worry if Xcode is throwing errors to you at this instance. Its because we have not yet added any UI elements to our VStacks.</p><p>Pay attention to .edgesIgnoringSageArea(.all) . This stretches the UI to cover all available space. Without this option there would be a white bar added to top and bottom of the UI which are are considered as safe area of the screen.</p><h3>Step 2: Let’s build the top half</h3><p>The top half will be used to display the expression which our user is trying to evaluate and also show the result of the expression. It will also show a welcome text when the app is opened the first time. Update the project code as shown below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/822d09356c8ead02e50b5f3f7ad1a913/href">https://medium.com/media/822d09356c8ead02e50b5f3f7ad1a913/href</a></iframe><p>Here we are declaring two @State variables. It’s a quick way to create a binding where the UI automatically updates whenever the value of the variables changes.</p><p>finalValue will hold the final result of the expression and calExpression will hold the expression that user has entered as a string array.</p><h3>Step 3: Now the bottom half</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/414/1*cO1Le1IKZEDIWF84kKIKSw.png" /><figcaption>Bottom half UI layout</figcaption></figure><p>We will do it in two parts. First we will create the UI and then add operating logic to the UI.</p><p>To create the UI there are two requirement s— numbers should be buttons without background with white font colors and arithmetic operators have two types of background, one with top-left corner rounded and another without.</p><p>There is a very helpful method cornerRadius available to many element. But it didn’t offer functionality to round only one corner. So, I had to look at masking for doing the same.</p><p>I found this very helpful article on masking:</p><p><a href="https://adrianhall.github.io/swift/2020/05/03/swiftui-masks/">https://adrianhall.github.io/swift/2020/05/03/swiftui-masks/</a></p><p>Using the learning, I created a function that will create a rounded corner shape which we will later use to mask the buttons. Add the following code to your project.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a726272f05732512ad18d962de9e4e99/href">https://medium.com/media/a726272f05732512ad18d962de9e4e99/href</a></iframe><p>Now, lets add all the buttons to the UI keeping following in mind:</p><ol><li>All the buttons need to be of equal size.</li><li>Each row will have 4 buttons.</li><li>Arithmetic operator should have different background and text size. Within themselves, <em>division(</em>÷<em>)</em> and <em>equal-to(</em>=<em>)</em> symbols should have the above mask applied to it.</li></ol><p>The whole bottom part we can visualize as shown in the image below, where one VStack has multiple HStack, which then aligns all four buttons horizontally.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*NWbHuRbCQCscCyT2pj_OVA.png" /><figcaption>UI element mapping for bottom half</figcaption></figure><p>Add the following code to your project.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eec37964df3b88c37917ce50e25694b6/href">https://medium.com/media/eec37964df3b88c37917ce50e25694b6/href</a></iframe><p>A lot is happening here. We will go through each one by one:</p><ol><li>We created a 2D array to hold all button titles. We loop through the array to add HStack for each row and then for each item in a row we add a button inside HStack. Pay special attention to maxWidth and maxHeight which are set as .infinity . This ensures that all buttons are of equal height and width .</li><li>We added checkIfOperator() function to check if the passed string is one of the operators or not.</li><li>We added getFontSize() and getBackground() to return different font size and background color based on whether the button is a number button or an operator button.</li><li>We have also added mask to our button with the help of CustomShape struct. It decides for which buttons top-left corner have to rounded and with what radius.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*pLXfAuXJ1Hudy7s0Ibj-2Q.png" /><figcaption>Final UI output</figcaption></figure><p>You can refresh your preview now. It should look something similar like this. Yay! 😄</p><p>We have successfully created the UI for the app. Doing the same thing earlier would have taken a lot more code and effort. Setting up constraints programmatically is a task in itself.</p><p>Now the only remaining thing is wiring up all the Button and Text and we will be done.</p><h3>Step 4: Add the logic sauce</h3><p>There are many ways how calculator app could evaluate the expression. Here I am choosing a simpler approach where all the numbers and operator are pushed to a list and a function evaluates the expression. If we choose to extend the functionality further with features like square-root, trigonometry functions, etc we might need to improve upon or choose a different approach.</p><p>We will start with declaring a @State variable as part of ContentView struct so that we don’t have to manage UI updates for the same as</p><pre>@State var noBeingEntered: String = “” //This will save the number which our user is entering.</pre><p>Now add the following function which will evaluate the expression and return the final result as a String.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9a806aee5c8fba2f3bf9d12e55594b45/href">https://medium.com/media/9a806aee5c8fba2f3bf9d12e55594b45/href</a></iframe><p>Update the Button’s action like following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/04e2f55f3a25a486777ac92a665fc4cb/href">https://medium.com/media/04e2f55f3a25a486777ac92a665fc4cb/href</a></iframe><p>What we are doing here is, whenever the user presses any button, our logic decides if its part of a number being entered or an operator and then update the noBeingEntered or calExpression variables accordingly. After making changes it calls on processExpression() to update the UI with the latest result. Pressing = will reset the expression. This also make sure the the operation are always evaluated on rolling basis on the final result rather than evaluating the whole expression from scratch.</p><p><em>If you are thinking of building a commercial calculator app then I would suggest building something where you keep the history of past expressions and process it from scratch using </em>BODMAS<em> rules everytime user adds to the expression. Most of the commercial calculator that you could find out there, does the process like this.</em></p><p>But, since our goal here is different, this simple logic serves our purpose. You can run the project and play with it in the simulator. Here is the final output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*B4zYvQj97D0iMY97oU3IIA.gif" /><figcaption>Final result</figcaption></figure><p>Congratulations! We have successfully build the app in less than 200 Lines-Of-Code. 👍</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*x6_L_NICnWAmo9V_Hc4A4g.png" /></figure><h3>Where to from here</h3><p>This is just a glimpse of how <strong>SwiftUI</strong> helps make a developer’s life easy. But obviously, there is a lot to be desired here in terms of functionality. You can start with updating the calculation logic or add more features like square-roots, brackets, delete, etc.</p><p>You can find the entire project here on github:</p><p><a href="https://github.com/ajeet-repos/Calculator-SwiftUI/tree/master">ajeet-repos/Calculator-SwiftUI</a></p><p><em>Thanks for reading. If you liked this article make sure to give it a </em>👏.<em> And if you would like to support me, please consider buying me a coffee. </em>🙂</p><figure><a href="https://www.buymeacoffee.com/ajeet"><img alt="" src="https://cdn-images-1.medium.com/max/217/1*zprvZqOkJyZf-etnGKXYcQ.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f1640504a50d" width="1" height="1" alt=""><hr><p><a href="https://digitalcurry.in/how-i-created-a-beautiful-calculator-in-less-than-200-loc-with-swiftui-f1640504a50d">[SwiftUI Recipe] How to create a beautiful iOS Calculator App in less than 200 LOC</a> was originally published in <a href="https://digitalcurry.in/">Digital Curry</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[Xcode Recipe] Getting Started With Unit and UI Testing in iOS]]></title>
            <link>https://digitalcurry.in/xcode-recipe-getting-started-with-unit-and-ui-testing-in-ios-9e7201208e4b?source=rss-832bb7be7335------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e7201208e4b</guid>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[ui-testing]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[xcode]]></category>
            <dc:creator><![CDATA[Ajeet Kumar]]></dc:creator>
            <pubDate>Mon, 29 Jun 2020 07:33:45 GMT</pubDate>
            <atom:updated>2020-07-08T18:08:37.694Z</atom:updated>
            <content:encoded><![CDATA[<h4>A quick and simple approach to testing on iOS + Xcode.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TbuTSiCyfjqQYRS0yX57bQ.jpeg" /><figcaption>Two pillars of testing in iOS</figcaption></figure><p>A major part of any great app is how robust it is in handling different situations and edge cases. And the complexity of doing the same increases exponentially as the features in the app grows with time.</p><p>One way how we generally like to ensure the quality of the app is by testing the app manually either by ourselves or having a team to test it. This approach quickly starts to show limitations with our extending delivery timelines and confidence in the build going out.</p><p>If you are here then you might also have faced something similar or just wanted to learn something new. Either way believe me its not something as complex as people generally like to advertise.</p><p>In this recipe we going to do following:</p><ol><li>Create a simple <strong>Xcode</strong> project for testing Unit and UI test scenarios with the help of <strong>SwiftUI</strong>.</li><li>Write and run a <strong>Unit Test</strong>: These are used to test out the logic in the app. Mostly we use it to test working of a function by setting up some preconditions and comparing the output with expected ones.</li><li>Write and run a <strong>UI Test</strong>: These were introduced in <em>WWDC 2015</em>. It solely focuses on the behavioral part of app testing where we are are able to simulate the behavior of a user like tapping a <strong><em>Button</em></strong>, typing in a <strong><em>TextField</em></strong>, etc. And compare app responses to expected UI changes.</li></ol><h3>Create a Sample Project</h3><p>First lets create a project. Go to <strong><em>File </em></strong>→<strong><em> New Project</em></strong> or <strong><em>Shift+Cmd+N</em></strong>. Choose <strong><em>Single View Application</em></strong> and click <strong><em>Next</em></strong>. Give a name to your project but remember to select both the options like shown in the image below. For user interface select <strong><em>SwiftUI</em></strong>. It is very easy to create beautiful UI with its help.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ryq2w-8O-RiLxo4E2v0xhw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/411/1*mHbZDKLEa5NPLK4nNFpCvA.png" /></figure><p>Once the project is created, you can see that Xcode has create two additional folders in the project as show in the image on the left. These folders are for segregating the test cases based on whether they are unit test cases or UI test cases.</p><p>Now lets make our test app working. For the sake of simplicity, we will have a very simple flow in the app where we will be changing the text of a<strong> TextView</strong> based on <strong>Button</strong> click. Here’s how the app will work:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f1rH7fyw0Lrlb2p5LTDaKw.png" /></figure><p>To create the UI for the app, copy paste the following code into the file <strong><em>ContentView.swift</em></strong>. Take a look at <strong><em>lable:</em></strong> on how I created the button. Its this simple to create a UI with <strong><em>SwiftUI</em></strong>. It kind of reminds me of how we create UI in <strong><em>Flutter</em></strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7300fb1956e97fd6014ca3cd246ed503/href">https://medium.com/media/7300fb1956e97fd6014ca3cd246ed503/href</a></iframe><p>You can now run the app and click on the button to make sure that its working.</p><p>Since, we now have our app up and running, we can focus on writing automated tests for the same. For this app we will be automating the following scenarios:</p><ol><li><strong>Unit Test:</strong> When <strong><em>counter</em></strong> is set to <strong><em>2</em></strong> → <strong><em>calculatedRandomString()</em></strong> method output is as <strong><em>“Random text 3”</em></strong>.</li><li><strong>UI Test:</strong> Open the app → Tap on the <strong><em>Button</em></strong> with text <strong><em>“Click Me!”</em></strong> → Assert if the value of the <strong><em>TextView</em></strong> changes to <strong><em>“Random text 1”</em></strong>.</li></ol><h3>Write and Run a Unit Test</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/269/1*xVqLGt65b_cUat_uEz9brQ.png" /></figure><p>To write the unit tests either press <strong><em>Cmd+6</em></strong> or navigate to <strong><em>Test Navigator</em></strong> as shown in the image from project inspector layout. Open the file under the folder <strong><em>&lt;Your app name&gt;Tests</em></strong>. For me its <strong><em>“Simple App to TestTests”</em></strong>. Clear all the methods from the class and add the following to the file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b55cd42879814ab69cb4c8ad7532016a/href">https://medium.com/media/b55cd42879814ab69cb4c8ad7532016a/href</a></iframe><p>In the above code, we are setting the <strong><em>counter</em></strong> to <strong><em>2</em></strong>, it can be set to any value. Then, capturing the output of function <strong><em>calculateRandomString()</em></strong> to assert that the output is <strong><em>“Random text &lt;counter+1&gt;”</em></strong>. You can run the tests by clicking on the notch on the left of the editor as show below.</p><p><strong>Note:</strong> Its very important that <strong><em>“test”</em></strong> prefix is there in the method otherwise Xcode won’t recognize the method for testing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dTZY1NvHvMo7TRBdiqFk_w.png" /><figcaption>Unit Test in iOS</figcaption></figure><p>If the test is successful you will see a green check mark. Viola! You have successfully written and ran a unit test successfully.</p><h3>Write and run a UI Test</h3><p>Writing UI tests is a little tricky in the sense that the test here doesn’t have access to global variables like Unit tests do. But, you do get a lot of levers to play around for comparing the outcome of a simulated user action. Like text of TextView, count of a list item, etc.</p><p>Open the file under the folder <strong><em>&lt;Your app name&gt;UITests</em></strong>. For me its <strong><em>Simple_App_To_TestUITests.swift</em></strong>.<strong><em> </em></strong>Clear the methods and add the following to the file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1edbb6f3d501f30c05eeb9f2e885e980/href">https://medium.com/media/1edbb6f3d501f30c05eeb9f2e885e980/href</a></iframe><p>In the above code, we are</p><ol><li>Getting an instance of the application → app</li><li>Finding the button with the text → Click ME! and tapping it to trigger the action.</li><li>Querying the app for any UIElement with text → “Random text 1”. Since the default value of <strong><em>counter</em></strong> is “0” when the app start that is why are are choosing “1” here as Button tap increases the value of <strong><em>counter</em></strong> as 1.</li><li>If the element is found tests is passed otherwise it fails.</li></ol><p>To run the test, click on the small notch in Xcode along the line numbers similar to what we did for Unit Tests.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*58P-uPGGq3QOFtkI9a1YLQ.png" /><figcaption>Successful test completion</figcaption></figure><p>Done! You have successfully ran a Unit and UI Tests on Xcode. Github repository for the same can be found at below given link.</p><p><a href="https://github.com/ajeet-repos/Getting-Started-With-Unit-and-UI-Testing-with-SwiftUI">ajeet-repos/Getting-Started-With-Unit-and-UI-Testing-with-SwiftUI</a></p><h3>Where to from here</h3><p>You can improve upon the current project by adding complex behaviors to hone your skills further. Also, do checkout WWDC videos from Apple related to testing. You can find some great content there.</p><p><em>Thanks for reading. If you liked this article make sure to give it a </em>👏.<em> And if you would like to support me, please consider buying me a coffee. </em>🙂</p><figure><a href="https://www.buymeacoffee.com/ajeet"><img alt="" src="https://cdn-images-1.medium.com/max/217/1*zprvZqOkJyZf-etnGKXYcQ.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e7201208e4b" width="1" height="1" alt=""><hr><p><a href="https://digitalcurry.in/xcode-recipe-getting-started-with-unit-and-ui-testing-in-ios-9e7201208e4b">[Xcode Recipe] Getting Started With Unit and UI Testing in iOS</a> was originally published in <a href="https://digitalcurry.in/">Digital Curry</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[Tensorflow Android] Quickly Create Image Editing App Like Prisma on Android]]></title>
            <link>https://digitalcurry.in/tensorflow-android-how-to-integrate-a-pre-trained-tensorflow-model-in-an-android-app-b2d5089dacb0?source=rss-832bb7be7335------2</link>
            <guid isPermaLink="false">https://medium.com/p/b2d5089dacb0</guid>
            <category><![CDATA[tensorflow-mobile]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[convolution-neural-net]]></category>
            <dc:creator><![CDATA[Ajeet Kumar]]></dc:creator>
            <pubDate>Sat, 08 Sep 2018 23:21:35 GMT</pubDate>
            <atom:updated>2018-09-17T11:44:31.397Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BtKaa3PWbkc2_jIcrSbzcw.png" /></figure><p>Tensorflow is an open source library released by Google for machine learning. It performs exceptionally well when it comes to deep learning tasks than its other competitors. And libraries like <strong>Keras</strong>, make it very easy to learn, train and deploy neural networks for numerous tasks like image classification, NLP, etc.</p><p>Soon after the launch, a lighter version of tensorflow was announced for mobile and embedded systems like android phones, Raspberry Pi, etc.</p><h3>What is the big deal?</h3><p>Till now all the intelligence were concentrated on the server side and that created significant delays in many real-time requirements.</p><p>As the number of mobile users grows, so will the demand for more intelligent, personal and immersive experience on mobile. And I strongly believe that tensorflow for mobile can bridge that gap by providing fast, on-device processing of data like images, text, etc and providing a personalized experience to each individual.</p><p>Few of the areas where deep learning intelligence on mobile can improve the user’s experience are:</p><ol><li><strong>Language Translation</strong>: With the help of camera, a user can be able to understand the food menu, traffic sign, etc.</li><li><strong>Image Classification</strong>: One of the reason searching for anything on Photos app is so fast because it internally applies deep learning techniques to capture information from the image.</li><li><strong>Augmented Reality</strong>: One of the example here could be when the user is able to see the information related to plants or seeds or any other object just by pointing camera to it. Snapchat’s filters are a great example of how engaging experiences can be created using machine learning / deep learning.</li></ol><p>There are numerous other possibilities on which many startups around the world are working day and night.</p><h3>Getting your feet wet..</h3><p>So to start out on this exciting path we will be doing a simple “Hello World!”ish application, demonstrating the steps in deploying a tensorflow model on android successfully.</p><p>For this demonstration, we will be using the famous <strong>“Artistic Style Transfer”</strong> neural network which take in a simple camera image and applies the style from the selected paintings. A similar kind of behavior you can observe in the <a href="https://play.google.com/store/apps/details?id=com.neuralprisma"><strong><em>PRISMA</em></strong><em> app</em></a></p><h3>Preface</h3><p>The code that generated this network is available here : <a href="https://github.com/tensorflow/magenta/blob/master/magenta/models/image_stylization/model.py#L28">https://github.com/tensorflow/magenta/blob/master/magenta/models/image_stylization/model.py#L28</a></p><p>Its part of a broader MAGENTA project available on GitHub at given below link. Check it out for many other interesting work using tensorflow.</p><p><a href="https://github.com/tensorflow/magenta">tensorflow/magenta</a></p><p><strong>Note: </strong>One thing that needs to be pointed out here is that neural network cannot be deployed as-it-is on a mobile device. Owning to many hardware limitations in terms of processor, memory, etc. each network must be optimized and transformed to use smaller data types and as-less-as-possible redundant calculations.</p><h3>Step 1: Create a project and import necessary library</h3><p>Lets create a new project with empty activity as below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/911/1*1Ffbb4eMfP8DRagWSnWKnQ.png" /></figure><p>And add the following library to <strong>build.gradle(Module:app)</strong>. It will import tensorflow for android and butterknife which is a very popular and useful library for accessing UI elements.</p><pre><em>// add tensorflow library. &quot;+&quot; will make it download the latest version<br></em><strong>implementation &#39;org.tensorflow:tensorflow-android:+&#39;</strong></pre><pre><em>// add butterknife. Its a great library to access ui elements without writing findviewbyid() methods</em><strong><br>implementation &#39;com.jakewharton:butterknife:8.8.1&#39;<br>annotationProcessor &#39;com.jakewharton:butterknife-compiler:8.8.1&#39;</strong></pre><h3>Step 2: Add architecture specific JNI libraries</h3><p>Copy all the folders, except <em>stylize_quantized.pb</em>, from the GitHub repository mentioned here</p><p><a href="https://github.com/ajeet-repos/tensorflow_demo-files">ajeet-repos/tensorflow_demo-files</a></p><p>to the <strong>libs</strong> folder inside the <strong>app </strong>folder in the project. If <strong>libs</strong> folder is not there please create it. At the end the project structure should look like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/462/1*UOr3or922giDlmjAmeNgEQ.png" /></figure><p>This files are JNI libraries that our app will use. But to be recognized as same we have to make some changes to our <strong>build.gradle</strong> file.</p><p>Copy these lines of code to <strong>android{}</strong> block and sync the gradle file.</p><pre><em>// Add these lines after copying *.so files in app/libs folder<br></em>sourceSets {<br>    main {<br>        jniLibs.srcDirs = [<strong>&#39;libs&#39;</strong>]<br>    }<br>}</pre><p>After the sync, android project would recognize these as lib folder. If you change the view to <strong>Android</strong> in projects pane you should see something similar.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/1*W5Xg5SsoTDB7jYCam4lWgw.png" /></figure><h3>Step 3: Add the optimized Tensorflow graph</h3><p>Create an <strong>assets</strong> folder and copy the <strong>stylize_quantized.pb</strong> from above mentioned GitHub repo to it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/464/1*_XlNlC-0em0mo6fzGMSARA.png" /></figure><p>The final structure of the project now should be similar to what is shown above.</p><h3>Step 4: Create UI</h3><p>For the sake of making the project simple we have chosen only 3 style to be applied. But you can modify the project to use all 26 style that this Tensorflow graph has been trained to do.</p><p>Apart from that we will have a menu button which will take the image from camera and load that into the text view. UI graphic and code are provided below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/376/1*5gCqqBiY2o6AKWunF1rS1A.png" /></figure><p>You can refer the xml code <a href="https://github.com/ajeet-repos/Artistic-Style-Transfer-Using-Tensorflow-on-Android/blob/master/app/src/main/res/layout/activity_main.xml"><strong>here</strong></a><strong>.</strong> To add the menu, create a resources folder inside <strong>res </strong>and name it <strong>menu</strong>. Inside <strong>menu </strong>create layout file named — <strong>main_menu.xml</strong> and paste the following code inside it.</p><pre><em>&lt;?</em><strong>xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;</strong><em>?&gt;<br></em>&lt;<strong>menu xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;</strong>&gt;<br><br>    &lt;<strong>item android:id=&quot;@+id/camera_image&quot;<br>        android:title=&quot;camera&quot;<br>        android:icon=&quot;@android:drawable/ic_menu_camera&quot;<br>        app:showAsAction=&quot;always&quot;</strong>/&gt;<br>&lt;/<strong>menu</strong>&gt;</pre><h3>Finally to the exciting bit..</h3><p><a href="https://github.com/ajeet-repos/Artistic-Style-Transfer-Using-Tensorflow-on-Android/blob/master/app/src/main/java/in/digitalcurry/artisticstyletransfer/MainActivity.java"><strong>MainActivity.java</strong></a> houses all the functionality for the app. Link to this repo is given below for reference. Out of that there are four portions of the code that are very important.</p><ol><li>Create an instance of <strong>TensorFlowInferenceInterface </strong>with the path to the tensorflow graph in <strong>onCreate()</strong>. In our case — <strong>stylize_quantized.pb.</strong></li></ol><pre><strong>inferenceInterface </strong>= <strong>new </strong>TensorFlowInferenceInterface(getAssets(), <strong><em>MODEL_FILE</em></strong>);</pre><ol><li><strong>Taking image from camera:</strong> Here I am opening the camera while passing the url for image. This will make sure that we get a full resolution image.</li></ol><pre>File imageFile = <strong>new </strong>File(android.os.Environment.<em>getExternalStorageDirectory</em>(), <strong>&quot;temp.jpg&quot;</strong>);<br><br><strong>fileUri </strong>= Uri.<em>fromFile</em>(imageFile);<br><br>Intent intent = <strong>new </strong>Intent(<strong>&quot;android.media.action.IMAGE_CAPTURE&quot;</strong>);<br>intent.putExtra(MediaStore.<strong><em>EXTRA_OUTPUT</em></strong>, <strong>fileUri</strong>);<br>startActivityForResult(intent, <strong>OPEN_CAMERA_FOR_CAPTURE</strong>);</pre><p>3. <strong>**Scaling the image for the Tensorflow network</strong>**<strong>:</strong> This is an important bit. Every tensorflow network will going to be have specification on what kind of input it can take. For our case here, the network requires a <strong>256x256</strong> size color image to be passed. So, in <strong>onActivityForResult()</strong> method we are getting the full size image from the above mentioned path and downscale it to <strong>256x256</strong> resolution. The same is populated in the central <strong>imageview</strong>.</p><pre>@Override<br><strong>protected void </strong>onActivityResult(<strong>int </strong>requestCode, <strong>int </strong>resultCode, Intent data) {<br>    <strong>super</strong>.onActivityResult(requestCode, resultCode, data);<br><br>    <strong>if </strong>(requestCode == <strong>OPEN_CAMERA_FOR_CAPTURE </strong>&amp;&amp; resultCode == Activity.<strong><em>RESULT_OK</em></strong>) {<br><br>        <strong>try </strong>{<br><br>            <strong>cameraImageView</strong>.setImageBitmap(getScaledBitmap(<strong>fileUri</strong>));<br>        } <strong>catch </strong>(NullPointerException e) {<br>            e.printStackTrace();<br>        }<br>    }<br>}</pre><pre><strong>public </strong>Bitmap getScaledBitmap(Uri fileUri) {<br><br>    Bitmap scaledPhoto = <strong>null</strong>;<br><br>    <strong>try </strong>{<br><br>        <em>// Get the dimensions of the bitmap<br>        </em>BitmapFactory.Options bmOptions = <strong>new </strong>BitmapFactory.Options();<br>        bmOptions.<strong>inJustDecodeBounds </strong>= <strong>true</strong>;<br><br>        Bitmap bitmap = BitmapFactory.<em>decodeFile</em>(fileUri.getPath());<br><br>        ExifInterface ei = <strong>new </strong>ExifInterface(fileUri.getPath());<br>        <strong>int </strong>orientation = ei.getAttributeInt(ExifInterface.<strong><em>TAG_ORIENTATION</em></strong>, ExifInterface.<strong><em>ORIENTATION_UNDEFINED</em></strong>);<br><br>        <em>// if orientation is 6 or 3 then the photo taken is portrait<br>        </em><strong>switch</strong>(orientation) {<br>            <strong>case </strong>ExifInterface.<strong><em>ORIENTATION_ROTATE_90</em></strong>:<br>                bitmap = rotateImage(bitmap, 90);<br>                <strong>break</strong>;<br>            <strong>case </strong>ExifInterface.<strong><em>ORIENTATION_ROTATE_180</em></strong>:<br>                bitmap = rotateImage(bitmap, 180);<br>                <strong>break</strong>;<br>        }<br><br>        bmOptions.<strong>inJustDecodeBounds </strong>= <strong>false</strong>;<br>        bmOptions.<strong>inPurgeable </strong>= <strong>true</strong>;<br><br>        <em>// Scaling down the original image taken from camera<br>        </em>scaledPhoto = Bitmap.<em>createScaledBitmap</em>(bitmap, <strong>desiredSize</strong>, <strong>desiredSize</strong>, <strong>false</strong>);<br><br>    }<br>    <strong>catch </strong>(Exception ex) {<br><br>    }<br><br>    <strong>return </strong>scaledPhoto;<br>}</pre><p>4. <strong>Applying style to the image:</strong> Once the user has selected a style, he/she can press apply button to apply the selected style to the captured image.</p><pre><strong>private void </strong>stylizeImage(Bitmap bitmap) {<br><br>    <strong>cameraImageView</strong>.setImageBitmap(bitmap);<br><br>    bitmap.getPixels(<strong>intValues</strong>, 0, bitmap.getWidth(), 0, 0, bitmap.getWidth(), bitmap.getHeight());<br><br>    <strong>for </strong>(<strong>int </strong>i = 0; i &lt; <strong>intValues</strong>.<strong>length</strong>; ++i) {<br>        <strong>final int </strong>val = <strong>intValues</strong>[i];<br>        <strong>floatValues</strong>[i * 3] = ((val &gt;&gt; 16) &amp; 0xFF) / 255.0f;<br>        <strong>floatValues</strong>[i * 3 + 1] = ((val &gt;&gt; 8) &amp; 0xFF) / 255.0f;<br>        <strong>floatValues</strong>[i * 3 + 2] = (val &amp; 0xFF) / 255.0f;<br>    }<br>    <em>// Copy the input data into TensorFlow.<br>    </em><strong>inferenceInterface</strong>.feed(<strong><em>INPUT_NODE</em></strong>, <strong>floatValues</strong>, 1, bitmap.getWidth(), bitmap.getHeight(), 3);<br>    <strong>inferenceInterface</strong>.feed(<strong><em>STYLE_NODE</em></strong>, <strong>styleVals</strong>, <strong><em>NUM_STYLES</em></strong>);<br><br>    <em>// Execute the output node&#39;s dependency sub-graph.<br>    </em><strong>inferenceInterface</strong>.run(<strong>new </strong>String[] {<strong><em>OUTPUT_NODE</em></strong>}, <strong>false</strong>);<br><br>    <em>// Copy the data from TensorFlow back into our array.<br>    </em><strong>inferenceInterface</strong>.fetch(<strong><em>OUTPUT_NODE</em></strong>, <strong>floatValues</strong>);<br><br>    <strong>for </strong>(<strong>int </strong>i = 0; i &lt; <strong>intValues</strong>.<strong>length</strong>; ++i) {<br>        <strong>intValues</strong>[i] =<br>                0xFF000000<br>                        | (((<strong>int</strong>) (<strong>floatValues</strong>[i * 3] * 255)) &lt;&lt; 16)<br>                        | (((<strong>int</strong>) (<strong>floatValues</strong>[i * 3 + 1] * 255)) &lt;&lt; 8)<br>                        | ((<strong>int</strong>) (<strong>floatValues</strong>[i * 3 + 2] * 255));<br>    }<br><br>    bitmap.setPixels(<strong>intValues</strong>, 0, bitmap.getWidth(), 0, 0, bitmap.getWidth(), bitmap.getHeight());<br><br>    <strong>cameraImageView</strong>.setImageBitmap(bitmap);<br>}</pre><p>Once done, match the code once with the repo and build the project on a device.</p><h3>Yay! All Done!!</h3><p>Congratulations! We have successfully deployed a tensorflow graph for the <strong>Artistic Style Transfer.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*vxNSUAZ1vDPEG-bJLbZqvg.gif" /></figure><p>GitHub repository for this project can be found here:</p><p><a href="https://github.com/ajeet-repos/Artistic-Style-Transfer-Using-Tensorflow-on-Android">ajeet-repos/Artistic-Style-Transfer-Using-Tensorflow-on-Android</a></p><h3>What from here..</h3><p>You can improve upon the project to do more sensible cropping keeping the aspect ration same.</p><p>You can also try preparing a tensorflow network for mobile deployment like freezing the graph etc. apart from experimenting with numerous other tensorflow examples.</p><p>If you like this article make sure to give it a 👏. And if you would like to support me, please consider buying me a coffee :)</p><figure><a href="https://www.buymeacoffee.com/ajeet"><img alt="" src="https://cdn-images-1.medium.com/max/170/1*lHomguUE0eH9Y7xHHH82hw.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b2d5089dacb0" width="1" height="1" alt=""><hr><p><a href="https://digitalcurry.in/tensorflow-android-how-to-integrate-a-pre-trained-tensorflow-model-in-an-android-app-b2d5089dacb0">[Tensorflow Android] Quickly Create Image Editing App Like Prisma on Android</a> was originally published in <a href="https://digitalcurry.in/">Digital Curry</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>