<?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 Atelier Flutter on Medium]]></title>
        <description><![CDATA[Stories by Atelier Flutter on Medium]]></description>
        <link>https://medium.com/@lenakendari?source=rss-932b58a7a66a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*q3ozpS-DqrpFcAhXB_JxLg.jpeg</url>
            <title>Stories by Atelier Flutter on Medium</title>
            <link>https://medium.com/@lenakendari?source=rss-932b58a7a66a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 22:34:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@lenakendari/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[Episode 24: Editing and Deleting Saved Products in Flutter]]></title>
            <link>https://medium.com/@lenakendari/episode-24-editing-and-deleting-saved-products-in-flutter-c0c4eedb9da8?source=rss-932b58a7a66a------2</link>
            <guid isPermaLink="false">https://medium.com/p/c0c4eedb9da8</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[localstorage]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Atelier Flutter]]></dc:creator>
            <pubDate>Fri, 24 Jul 2026 14:45:03 GMT</pubDate>
            <atom:updated>2026-07-24T14:45:03.522Z</atom:updated>
            <content:encoded><![CDATA[<p>I add edit and delete controls so locally saved products can be updated or removed without affecting the built-in catalog.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t6sF6Ba-3zpkqcNzme3sLw.png" /></figure><p>At the end of Episode 23, the catalog could finally remember products created by the user.</p><p>Names, prices, descriptions, custom categories, and selected images were saved locally and restored when the application started again. Refreshing Chrome no longer returned the catalog to its original state.</p><p>Persistence solved one problem, but it also exposed the next one.</p><p>A saved product could remain in the catalog, but the user had no way to correct its name, replace its image, update its price, or remove it completely.</p><p>In this episode, I am adding edit and delete controls for locally created products.</p><p>The original twenty products will remain protected. Only products created through the Add Product form will be editable and removable.</p><p>Every change must also update local storage so the edited catalog remains correct after a refresh or restart.</p><p>The saved catalog can now survive a refresh, but it is still one-way.</p><p>A user can create a product and keep it locally, yet there is no way to correct a mistake or remove an item that is no longer needed. The catalog remembers everything, including errors.</p><p>Episode 24 will turn those saved products into manageable records.</p><p>Locally created products will receive Edit and Delete controls. Editing will reopen the existing product data inside a form, while deleting will require confirmation before the product is removed.</p><p>The original twenty products will remain protected. They can still be viewed, favorited, and added to the cart, but they will not display editing or deletion controls.</p><p>After every edit or deletion, the updated user-created catalog will be written back to local storage so the result remains correct after a refresh.</p><p>Before adding any controls, I need to inspect how products currently move through the application.</p><p>The Add Product page may be reusable as an editing form, but that depends on its constructor, text controllers, image state, and save behavior. I also need to locate the product detail page because that is the safest place to expose management controls without crowding every catalog card.</p><pre>cd ~/offline_product_catalog<br><br>printf &#39;\n=== EPISODE 24 CODE LOCATIONS ===\n&#39;<br><br>grep -nE \<br>&quot;^class Product\b|^class AddProductPage\b|^class _AddProductPageState\b|_openAddProductPage|ProductDetail|_saveUserProducts|_favoriteProductNames|_cartItems|ProductCard&quot; \<br>lib/main.dart<br><br>printf &#39;\n=== ADD PRODUCT PAGE CONSTRUCTOR ===\n&#39;<br><br>add_page_line=$(grep -nE &#39;^class AddProductPage\b&#39; lib/main.dart | head -n 1 | cut -d: -f1)<br><br>if [ -n &quot;$add_page_line&quot; ]; then<br>  start=&quot;$add_page_line&quot;<br>  end=$((add_page_line + 90))<br>  nl -ba lib/main.dart | sed -n &quot;${start},${end}p&quot;<br>else<br>  printf &#39;AddProductPage was not found.\n&#39;<br>fi<br><br>printf &#39;\n=== PRODUCT DETAIL LOCATIONS ===\n&#39;<br><br>grep -nE \<br>&quot;ProductDetail|Navigator.push|showDialog|IconButton|PopupMenuButton&quot; \<br>lib/main.dart</pre><p>This inspection reveals where Episode 24 should connect.</p><p>The existing product form can be extended with an optional product argument. When that argument is absent, the page will continue creating a new product. When it is present, the form will preload the saved values and return an updated Product object.</p><p>The product detail page will then provide the Edit and Delete actions, but only when the selected product was created by the user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/665/1*QNxsnc-5NZBxyGKI1e7mOQ.png" /><figcaption>Inspecting the existing product form and detail page before adding edit and delete controls.</figcaption></figure><p>The current application already has working product creation and local persistence.</p><p>Episode 24 will modify the same form, product detail flow, favorites, cart references, and saved catalog. Before connecting those parts, I am preserving the completed Episode 23 version as a safe recovery point.</p><pre>cd ~/offline_product_catalog<br><br>backup_file=&quot;lib/main.dart.episode23_backup_$(date +%Y%m%d_%H%M%S)&quot;<br>cp lib/main.dart &quot;$backup_file&quot;<br><br>printf &#39;\n=== EPISODE 23 BACKUP CREATED ===\n&#39;<br>printf &#39;%s\n&#39; &quot;$backup_file&quot;<br><br>printf &#39;\n=== VERIFY BACKUP ===\n&#39;<br>ls -lh &quot;$backup_file&quot;</pre><p>The completed persistence implementation is now protected.</p><p>If the editing flow affects product creation or local restoration unexpectedly, I can return to this exact Episode 23 state without rebuilding the previous work.</p><pre>cd ~/offline_product_catalog<br><br>printf &#39;\n=== ADD PRODUCT PAGE LOCATION ===\n&#39;<br>grep -nE \<br>&quot;^class AddProductPage|^class _AddProductPageState&quot; \<br>lib/main.dart<br><br>printf &#39;\n=== FORM CONTROLLERS AND IMAGE STATE ===\n&#39;<br>grep -nE \<br>&quot;TextEditingController|ImagePicker|XFile|imageBytes|selectedCategory|newCategory|dispose\\(&quot; \<br>lib/main.dart<br><br>printf &#39;\n=== FORM BUILD AND SAVE LOCATIONS ===\n&#39;<br>grep -nE \<br>&quot;Widget build\\(|Form\\(|TextFormField|DropdownButtonFormField|Choose Image|Take Photo|Save Product|Navigator.pop&quot; \<br>lib/main.dart</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/665/1*uyggf8xK8TMFu5p_vrDaJw.png" /><figcaption>Reviewing the existing product form before extending it into reusable add and edit modes.</figcaption></figure><p>Creating a second page only for editing would duplicate most of the existing form.</p><p>Instead, I will extend AddProductPage so it can operate in two modes. Without an existing product, it creates a new item. With a product argument, it preloads the current values and returns an updated item.</p><p>This keeps image selection, validation, category handling, and form layout in one place.</p><p>The form structure has now been reviewed, but I should not replace it by guessing its exact layout.</p><p>Before changing AddProductPage, I will extract the current constructor, state fields, initState method, image picker logic, and save method. The edit patch will then be attached to the code that actually exists in the project.</p><pre>cd ~/offline_product_catalog<br><br>python3 &lt;&lt;&#39;PY&#39;<br>from pathlib import Path<br><br>path = Path(&quot;lib/main.dart&quot;)<br>lines = path.read_text(encoding=&quot;utf-8&quot;).splitlines()<br><br>targets = [<br>    &quot;class AddProductPage&quot;,<br>    &quot;class _AddProductPageState&quot;,<br>    &quot;void initState()&quot;,<br>    &quot;Future&lt;void&gt; _pickImage&quot;,<br>    &quot;Future&lt;void&gt; _takePhoto&quot;,<br>    &quot;void _saveProduct&quot;,<br>    &quot;Future&lt;void&gt; _saveProduct&quot;,<br>    &quot;Save Product&quot;,<br>]<br><br>print(&quot;\n=== ADD AND EDIT FORM TARGETS ===&quot;)<br><br>for target in targets:<br>    matches = [<br>        index<br>        for index, line in enumerate(lines, start=1)<br>        if target in line<br>    ]<br><br>    if not matches:<br>        print(f&quot;\n--- {target}: NOT FOUND ---&quot;)<br>        continue<br><br>    for match in matches:<br>        start = max(1, match - 8)<br>        end = min(len(lines), match + 45)<br><br>        print(f&quot;\n--- {target}: lines {start}-{end} ---&quot;)<br><br>        for line_number in range(start, end + 1):<br>            print(f&quot;{line_number:5}  {lines[line_number - 1]}&quot;)<br>PY</pre><pre>printf &#39;\n=== ADD PRODUCT NAVIGATION ===\n&#39;<br><br>grep -nE \<br>&quot;AddProductPage\\(|_openAddProductPage|Navigator.push.*AddProduct|Product result|Product\\? result&quot; \<br>lib/main.dart</pre><pre>printf &#39;\n=== PRODUCT DETAIL STRUCTURE ===\n&#39;<br><br>grep -nE \<br>&quot;class .*Product.*Detail|ProductDetailPage|product: product|Add to Cart|Favorite|Scaffold\\(&quot; \<br>lib/main.dart</pre><p>The extracted code provides the exact anchors needed for a safe edit-mode patch.</p><p>The next change will keep the current Add Product behavior intact while adding an optional existing product. When that product is present, the form will preload its values, display its current image, and change its title and submit button to editing language.</p><p>The existing form already contains everything needed to update a product.</p><p>Instead of creating a second page with the same controllers, validation, category controls, and image picker, I will extend AddProductPage with an optional productToEdit argument.</p><p>When no product is supplied, the page will continue working as the original Add Product form. When an existing product is supplied, the fields and image will be preloaded and the page will switch to Edit Product mode.</p><pre>cd ~/offline_product_catalog<br><br>cp lib/main.dart \<br>&quot;lib/main.dart.episode24_form_backup_$(date +%Y%m%d_%H%M%S)&quot;<br><br>python3 &lt;&lt;&#39;PY&#39;<br>from pathlib import Path<br><br>path = Path(&quot;lib/main.dart&quot;)<br>text = path.read_text(encoding=&quot;utf-8&quot;)<br><br>if &quot;bool get _isEditing&quot; in text:<br>    raise SystemExit(<br>        &quot;Edit mode already exists. The patch was not applied again.&quot;<br>    )<br><br><br>def replace_once(old: str, new: str, label: str) -&gt; None:<br>    global text<br><br>    count = text.count(old)<br><br>    if count != 1:<br>        raise SystemExit(<br>            f&quot;{label}: expected exactly one match, but found {count}.&quot;<br>        )<br><br>    text = text.replace(old, new, 1)<br><br><br># 1. Allow AddProductPage to receive an existing product.<br>replace_once(<br>    &quot;&quot;&quot;  const AddProductPage({<br>    super.key,<br>    required this.categories,<br>    required this.existingProductNames,<br>  });<br><br>  final List&lt;String&gt; categories;<br>  final Set&lt;String&gt; existingProductNames;&quot;&quot;&quot;,<br>    &quot;&quot;&quot;  const AddProductPage({<br>    super.key,<br>    required this.categories,<br>    required this.existingProductNames,<br>    this.productToEdit,<br>  });<br><br>  final List&lt;String&gt; categories;<br>  final Set&lt;String&gt; existingProductNames;<br>  final Product? productToEdit;&quot;&quot;&quot;,<br>    &quot;AddProductPage constructor&quot;,<br>)<br><br><br># 2. Add an edit-mode helper to the form state.<br>replace_once(<br>    &quot;&quot;&quot;class _AddProductPageState extends State&lt;AddProductPage&gt; {<br>  final GlobalKey&lt;FormState&gt; _formKey = GlobalKey&lt;FormState&gt;();&quot;&quot;&quot;,<br>    &quot;&quot;&quot;class _AddProductPageState extends State&lt;AddProductPage&gt; {<br>  final GlobalKey&lt;FormState&gt; _formKey = GlobalKey&lt;FormState&gt;();<br><br>  bool get _isEditing =&gt; widget.productToEdit != null;&quot;&quot;&quot;,<br>    &quot;Edit mode helper&quot;,<br>)<br><br><br># 3. Prefill controllers, category, and image during editing.<br>replace_once(<br>    &quot;&quot;&quot;  @override<br>  void initState() {<br>    super.initState();<br><br>    if (widget.categories.isNotEmpty) {<br>      _selectedCategory = widget.categories.first;<br>    }<br>  }&quot;&quot;&quot;,<br>    &quot;&quot;&quot;  @override<br>  void initState() {<br>    super.initState();<br><br>    if (widget.categories.isNotEmpty) {<br>      _selectedCategory = widget.categories.first;<br>    }<br><br>    final product = widget.productToEdit;<br><br>    if (product != null) {<br>      _nameController.text = product.name;<br>      _priceController.text = product.price.replaceFirst(r&#39;$&#39;, &#39;&#39;);<br>      _descriptionController.text = product.description;<br>      _selectedCategory = product.category;<br>      _selectedImageBytes = product.imageBytes;<br>    }<br>  }&quot;&quot;&quot;,<br>    &quot;Edit form initial values&quot;,<br>)<br><br><br># 4. Change the page title according to the active mode.<br>replace_once(<br>    &quot;&quot;&quot;        appBar: AppBar(<br>          backgroundColor: Theme.of(context).colorScheme.inversePrimary,<br>          title: const Text(&#39;Add Product&#39;),<br>        ),&quot;&quot;&quot;,<br>    &quot;&quot;&quot;        appBar: AppBar(<br>          backgroundColor: Theme.of(context).colorScheme.inversePrimary,<br>          title: Text(_isEditing ? &#39;Edit Product&#39; : &#39;Add Product&#39;),<br>        ),&quot;&quot;&quot;,<br>    &quot;Dynamic form title&quot;,<br>)<br><br><br># 5. Change the submit button label according to the active mode.<br>replace_once(<br>    &quot;&quot;&quot;                  FilledButton.icon(<br>                    onPressed: _saveProduct,<br>                    icon: const Icon(Icons.save_outlined),<br>                    label: const Text(&#39;Save Product&#39;),<br>                  ),&quot;&quot;&quot;,<br>    &quot;&quot;&quot;                  FilledButton.icon(<br>                    onPressed: _saveProduct,<br>                    icon: const Icon(Icons.save_outlined),<br>                    label: Text(<br>                      _isEditing ? &#39;Save Changes&#39; : &#39;Save Product&#39;,<br>                    ),<br>                  ),&quot;&quot;&quot;,<br>    &quot;Dynamic submit button&quot;,<br>)<br><br><br>required_markers = [<br>    &quot;final Product? productToEdit;&quot;,<br>    &quot;bool get _isEditing =&gt; widget.productToEdit != null;&quot;,<br>    &quot;final product = widget.productToEdit;&quot;,<br>    &quot;_nameController.text = product.name;&quot;,<br>    &quot;_selectedImageBytes = product.imageBytes;&quot;,<br>    &quot;&#39;Edit Product&#39; : &#39;Add Product&#39;&quot;,<br>    &quot;&#39;Save Changes&#39; : &#39;Save Product&#39;&quot;,<br>]<br><br>for marker in required_markers:<br>    if marker not in text:<br>        raise SystemExit(<br>            f&quot;Required edit-mode marker was not created: {marker}&quot;<br>        )<br><br><br>path.write_text(text, encoding=&quot;utf-8&quot;)<br><br>print(&quot;Episode 24 form edit mode applied successfully.&quot;)<br>print(&quot;Optional productToEdit argument added.&quot;)<br>print(&quot;Existing values are preloaded during editing.&quot;)<br>print(&quot;Existing image bytes are preserved.&quot;)<br>print(&quot;Dynamic page title added.&quot;)<br>print(&quot;Dynamic submit button added.&quot;)<br>PY<br><br>printf &#39;\n=== FORMAT EDIT MODE ===\n&#39;<br>dart format lib/main.dart<br><br>printf &#39;\n=== VERIFY EDIT MODE ===\n&#39;<br>grep -nE \<br>&quot;productToEdit|_isEditing|Edit Product|Save Changes|_selectedImageBytes = product.imageBytes&quot; \<br>lib/main.dart</pre><p>AddProductPage can now operate in two modes.</p><p>The normal Add Product flow remains unchanged. When productToEdit contains an existing product, the form copies its name, price, description, category, and image bytes into the current form state.</p><p>The page title changes to Edit Product, and the submit button changes to Save Changes. The same validation and image-selection flow can therefore serve both product creation and product editing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/665/1*T_i4yiUTQ3J2cIQNvHVbMw.png" /><figcaption>Extending the existing product form with prefilled values and a reusable edit mode.</figcaption></figure><p>The form can now preload an existing product, but the editing pipeline is not complete yet.</p><p>I still need to connect the form to the product detail page, replace the correct item inside the editable catalog, update any favorite and cart references, and save the revised catalog locally.</p><p>Before applying that patch, I am extracting the exact validation and navigation blocks. This prevents the edit flow from accidentally rejecting the product’s original name or leaving an outdated product inside the cart.</p><pre>cd ~/offline_product_catalog<br><br>python3 &lt;&lt;&#39;PY&#39;<br>from pathlib import Path<br><br>path = Path(&quot;lib/main.dart&quot;)<br>lines = path.read_text(encoding=&quot;utf-8&quot;).splitlines()<br><br>required_markers = [<br>    &quot;final Product? productToEdit;&quot;,<br>    &quot;bool get _isEditing&quot;,<br>    &quot;&#39;Save Changes&#39;&quot;,<br>]<br><br>missing = [<br>    marker<br>    for marker in required_markers<br>    if not any(marker in line for line in lines)<br>]<br><br>if missing:<br>    print(&quot;\n=== EDIT MODE CHECK FAILED ===&quot;)<br>    for marker in missing:<br>        print(f&quot;Missing: {marker}&quot;)<br><br>    raise SystemExit(<br>        &quot;\nThe previous edit-mode patch is not complete.&quot;<br>    )<br><br>print(&quot;\n=== EDIT MODE CHECK ===&quot;)<br>print(&quot;The reusable Add and Edit form is present.&quot;)<br><br><br>def show_matches(<br>    title: str,<br>    needle: str,<br>    before: int,<br>    after: int,<br>) -&gt; None:<br>    matches = [<br>        index<br>        for index, line in enumerate(lines)<br>        if needle in line<br>    ]<br><br>    print(f&quot;\n=== {title} ===&quot;)<br><br>    if not matches:<br>        print(f&quot;Not found: {needle}&quot;)<br>        return<br><br>    for match in matches:<br>        start = max(0, match - before)<br>        end = min(len(lines), match + after + 1)<br><br>        print(<br>            f&quot;\n--- lines {start + 1}-{end} &quot;<br>            f&quot;for {needle!r} ---&quot;<br>        )<br><br>        for index in range(start, end):<br>            print(f&quot;{index + 1:5}  {lines[index]}&quot;)<br><br><br>def show_class(title: str, class_name: str) -&gt; None:<br>    start = next(<br>        (<br>            index<br>            for index, line in enumerate(lines)<br>            if line.startswith(f&quot;class {class_name}&quot;)<br>        ),<br>        None,<br>    )<br><br>    print(f&quot;\n=== {title} ===&quot;)<br><br>    if start is None:<br>        print(f&quot;Class not found: {class_name}&quot;)<br>        return<br><br>    end = len(lines)<br><br>    for index in range(start + 1, len(lines)):<br>        if lines[index].startswith(&quot;class &quot;):<br>            end = index<br>            break<br><br>    for index in range(start, end):<br>        print(f&quot;{index + 1:5}  {lines[index]}&quot;)<br><br><br>show_matches(<br>    &quot;PRODUCT NAME VALIDATION&quot;,<br>    &quot;existingProductNames&quot;,<br>    before=12,<br>    after=45,<br>)<br><br>show_class(<br>    &quot;COMPLETE PRODUCT DETAIL PAGE&quot;,<br>    &quot;ProductDetailPage&quot;,<br>)<br><br>show_matches(<br>    &quot;ADD PRODUCT NAVIGATION METHOD&quot;,<br>    &quot;Future&lt;void&gt; _openAddProductPage&quot;,<br>    before=8,<br>    after=100,<br>)<br><br>show_matches(<br>    &quot;PRODUCT DETAIL NAVIGATION&quot;,<br>    &quot;builder: (context) =&gt; ProductDetailPage(&quot;,<br>    before=30,<br>    after=45,<br>)<br><br>show_matches(<br>    &quot;LOCAL SAVE METHOD&quot;,<br>    &quot;Future&lt;void&gt; _saveUserProducts&quot;,<br>    before=5,<br>    after=45,<br>)<br>PY</pre><p>The remaining connection points are now visible.</p><p>Editing cannot stop at returning a new Product object from the form. The application must replace the original object, preserve its favorite status, move its cart quantity to the updated product, and write the revised user-created catalog back to local storage.</p><p>The name validator also needs to ignore the current product’s original name while editing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/665/1*6wf8fjJYaZRMTd12XUDVvg.png" /><figcaption>Tracing product validation, detail navigation, favorites, cart state, and local saving before connecting the edit action.</figcaption></figure><p>The reusable form is ready, but editing still needs a connection to the main catalog.</p><p>I will add an Edit button to the product detail page. The button will only appear for products created by the user because the original twenty products must remain protected.</p><p>After the form returns an updated Product object, the application will replace the original product, preserve its favorite status, move its cart quantity, and save the revised catalog locally.</p><pre>cd ~/offline_product_catalog<br><br>cp lib/main.dart \<br>&quot;lib/main.dart.episode24_edit_connection_backup_$(date +%Y%m%d_%H%M%S)&quot;<br><br>python3 &lt;&lt;&#39;PY&#39;<br>from pathlib import Path<br><br>path = Path(&quot;lib/main.dart&quot;)<br>text = path.read_text(encoding=&quot;utf-8&quot;)<br><br>if &quot;Future&lt;Product?&gt; _editProduct&quot; in text:<br>    raise SystemExit(<br>        &quot;The Edit Product connection already exists. &quot;<br>        &quot;The patch was not applied again.&quot;<br>    )<br><br><br>def replace_once(old: str, new: str, label: str) -&gt; None:<br>    global text<br><br>    count = text.count(old)<br><br>    if count != 1:<br>        raise SystemExit(<br>            f&quot;{label}: expected exactly one match, but found {count}.&quot;<br>        )<br><br>    text = text.replace(old, new, 1)<br><br><br>def find_matching_parenthesis(source: str, opening: int) -&gt; int:<br>    depth = 0<br>    quote = None<br>    escaped = False<br><br>    for index in range(opening, len(source)):<br>        character = source[index]<br><br>        if quote is not None:<br>            if escaped:<br>                escaped = False<br>            elif character == &quot;\\&quot;:<br>                escaped = True<br>            elif character == quote:<br>                quote = None<br><br>            continue<br><br>        if character in (&quot;&#39;&quot;, &#39;&quot;&#39;):<br>            quote = character<br>            continue<br><br>        if character == &quot;(&quot;:<br>            depth += 1<br>        elif character == &quot;)&quot;:<br>            depth -= 1<br><br>            if depth == 0:<br>                return index<br><br>    raise SystemExit(&quot;A matching parenthesis could not be found.&quot;)<br><br><br>required_form_markers = [<br>    &quot;final Product? productToEdit;&quot;,<br>    &quot;bool get _isEditing&quot;,<br>    &quot;&#39;Save Changes&#39;&quot;,<br>]<br><br>for marker in required_form_markers:<br>    if marker not in text:<br>        raise SystemExit(<br>            f&quot;The previous edit-form patch is missing: {marker}&quot;<br>        )<br><br><br># ---------------------------------------------------------<br># 1. Extend ProductDetailPage with an Edit callback.<br># ---------------------------------------------------------<br><br>widget_start = text.find(<br>    &quot;class ProductDetailPage extends StatefulWidget&quot;<br>)<br><br>state_start = text.find(<br>    &quot;class _ProductDetailPageState&quot;,<br>    widget_start,<br>)<br><br>if widget_start == -1 or state_start == -1:<br>    raise SystemExit(&quot;ProductDetailPage structure was not found.&quot;)<br><br>widget_block = text[widget_start:state_start]<br><br>if &quot;required this.onEdit,&quot; not in widget_block:<br>    constructor_anchor = &quot;    required this.onAddToCart,\n&quot;<br><br>    if constructor_anchor not in widget_block:<br>        raise SystemExit(<br>            &quot;ProductDetailPage constructor anchor was not found.&quot;<br>        )<br><br>    widget_block = widget_block.replace(<br>        constructor_anchor,<br>        constructor_anchor + &quot;    required this.onEdit,\n&quot;,<br>        1,<br>    )<br><br>if &quot;Future&lt;Product?&gt; Function(Product product) onEdit;&quot; not in widget_block:<br>    field_anchor = &quot;  final VoidCallback onAddToCart;\n&quot;<br><br>    if field_anchor not in widget_block:<br>        raise SystemExit(<br>            &quot;ProductDetailPage Add to Cart field was not found.&quot;<br>        )<br><br>    widget_block = widget_block.replace(<br>        field_anchor,<br>        field_anchor<br>        + &quot;  final Future&lt;Product?&gt; Function(Product product) onEdit;\n&quot;,<br>        1,<br>    )<br><br>text = text[:widget_start] + widget_block + text[state_start:]<br><br><br># ---------------------------------------------------------<br># 2. Let ProductDetailPage hold the updated product.<br># ---------------------------------------------------------<br><br>state_start = text.find(&quot;class _ProductDetailPageState&quot;)<br>next_class = text.find(&quot;\nclass &quot;, state_start + 1)<br><br>if next_class == -1:<br>    next_class = len(text)<br><br>state_block = text[state_start:next_class]<br><br>replace_targets = [<br>    (<br>        &quot;  late bool _favorite;&quot;,<br>        &quot;&quot;&quot;  late Product _product;<br>  late bool _favorite;&quot;&quot;&quot;,<br>        &quot;Detail page product state&quot;,<br>    ),<br>    (<br>        &quot;  Product get product =&gt; widget.product;&quot;,<br>        &quot;  Product get product =&gt; _product;&quot;,<br>        &quot;Dynamic product getter&quot;,<br>    ),<br>    (<br>        &quot;&quot;&quot;  void initState() {<br>    super.initState();<br>    _favorite = widget.isFavorite;<br>  }&quot;&quot;&quot;,<br>        &quot;&quot;&quot;  void initState() {<br>    super.initState();<br>    _product = widget.product;<br>    _favorite = widget.isFavorite;<br>  }&quot;&quot;&quot;,<br>        &quot;Detail page initialization&quot;,<br>    ),<br>]<br><br>for old, new, label in replace_targets:<br>    count = state_block.count(old)<br><br>    if count != 1:<br>        raise SystemExit(<br>            f&quot;{label}: expected exactly one match, but found {count}.&quot;<br>        )<br><br>    state_block = state_block.replace(old, new, 1)<br><br><br># ---------------------------------------------------------<br># 3. Add the Edit handler inside ProductDetailPage.<br># ---------------------------------------------------------<br><br>edit_handler = &quot;&quot;&quot;<br>  Future&lt;void&gt; _handleEdit() async {<br>    final updatedProduct = await widget.onEdit(product);<br><br>    if (!mounted || updatedProduct == null) {<br>      return;<br>    }<br><br>    setState(() {<br>      _product = updatedProduct;<br>    });<br><br>    ScaffoldMessenger.of(context)<br>      ..hideCurrentSnackBar()<br>      ..showSnackBar(<br>        SnackBar(<br>          content: Text(<br>            &#39;${updatedProduct.name} was updated successfully.&#39;,<br>          ),<br>        ),<br>      );<br>  }<br><br>&quot;&quot;&quot;<br><br>build_anchor = &quot;  @override\n  Widget build(BuildContext context) {&quot;<br><br>if build_anchor not in state_block:<br>    raise SystemExit(<br>        &quot;ProductDetailPage build method was not found.&quot;<br>    )<br><br>state_block = state_block.replace(<br>    build_anchor,<br>    edit_handler + build_anchor,<br>    1,<br>)<br><br><br># ---------------------------------------------------------<br># 4. Show Edit only for user-created products.<br># ---------------------------------------------------------<br><br>actions_anchor = &quot;&quot;&quot;          actions: [<br>            IconButton(&quot;&quot;&quot;<br><br>actions_replacement = &quot;&quot;&quot;          actions: [<br>            if (product.imageBytes != null)<br>              IconButton(<br>                tooltip: &#39;Edit product&#39;,<br>                onPressed: _handleEdit,<br>                icon: const Icon(Icons.edit_outlined),<br>              ),<br>            IconButton(&quot;&quot;&quot;<br><br>if actions_anchor not in state_block:<br>    raise SystemExit(<br>        &quot;ProductDetailPage AppBar actions were not found.&quot;<br>    )<br><br>state_block = state_block.replace(<br>    actions_anchor,<br>    actions_replacement,<br>    1,<br>)<br><br>text = text[:state_start] + state_block + text[next_class:]<br><br><br># ---------------------------------------------------------<br># 5. Add the parent method that replaces a saved product.<br># ---------------------------------------------------------<br><br>edit_method = r&#39;&#39;&#39;<br>  Future&lt;Product?&gt; _editProduct(Product product) async {<br>    if (product.imageBytes == null) {<br>      return null;<br>    }<br><br>    final categories = _products<br>        .map((item) =&gt; item.category)<br>        .toSet()<br>        .toList()<br>      ..sort();<br><br>    final existingProductNames = _products<br>        .where((item) =&gt; !identical(item, product))<br>        .map((item) =&gt; item.name.trim().toLowerCase())<br>        .toSet();<br><br>    final updatedProduct = await Navigator.of(context).push&lt;Product&gt;(<br>      MaterialPageRoute(<br>        builder: (context) =&gt; AddProductPage(<br>          categories: categories,<br>          existingProductNames: existingProductNames,<br>          productToEdit: product,<br>        ),<br>      ),<br>    );<br><br>    if (!mounted || updatedProduct == null) {<br>      return null;<br>    }<br><br>    final productIndex = _products.indexOf(product);<br><br>    if (productIndex == -1) {<br>      return null;<br>    }<br><br>    final wasFavorite = _favoriteProductNames.contains(product.name);<br>    final cartQuantity = _cartItems[product];<br>    final previousSelectedCategory = _selectedCategory;<br><br>    setState(() {<br>      _products[productIndex] = updatedProduct;<br><br>      if (wasFavorite) {<br>        _favoriteProductNames<br>          ..remove(product.name)<br>          ..add(updatedProduct.name);<br>      }<br><br>      if (cartQuantity != null) {<br>        _cartItems<br>          ..remove(product)<br>          ..[updatedProduct] = cartQuantity;<br>      }<br><br>      _selectedCategory = &#39;All&#39;;<br>    });<br><br>    try {<br>      await _saveUserProducts();<br>    } catch (_) {<br>      if (!mounted) {<br>        return null;<br>      }<br><br>      setState(() {<br>        _products[productIndex] = product;<br><br>        if (wasFavorite) {<br>          _favoriteProductNames<br>            ..remove(updatedProduct.name)<br>            ..add(product.name);<br>        }<br><br>        if (cartQuantity != null) {<br>          _cartItems<br>            ..remove(updatedProduct)<br>            ..[product] = cartQuantity;<br>        }<br><br>        _selectedCategory = previousSelectedCategory;<br>      });<br><br>      ScaffoldMessenger.of(context)<br>        ..hideCurrentSnackBar()<br>        ..showSnackBar(<br>          const SnackBar(<br>            content: Text(<br>              &#39;The changes could not be saved locally.&#39;,<br>            ),<br>          ),<br>        );<br><br>      return null;<br>    }<br><br>    return updatedProduct;<br>  }<br><br>&#39;&#39;&#39;<br><br>navigation_method_anchor = (<br>    &quot;  Future&lt;void&gt; _openAddProductPage() async {&quot;<br>)<br><br>if navigation_method_anchor not in text:<br>    raise SystemExit(<br>        &quot;_openAddProductPage method was not found.&quot;<br>    )<br><br>text = text.replace(<br>    navigation_method_anchor,<br>    edit_method + navigation_method_anchor,<br>    1,<br>)<br><br><br># ---------------------------------------------------------<br># 6. Connect the Edit callback to ProductDetailPage.<br># ---------------------------------------------------------<br><br>call_anchor = &quot;builder: (context) =&gt; ProductDetailPage(&quot;<br>call_start = text.find(call_anchor)<br><br>if call_start == -1:<br>    raise SystemExit(<br>        &quot;ProductDetailPage navigation call was not found.&quot;<br>    )<br><br>opening_parenthesis = text.find(<br>    &quot;(&quot;,<br>    call_start + call_anchor.index(&quot;ProductDetailPage&quot;),<br>)<br><br>closing_parenthesis = find_matching_parenthesis(<br>    text,<br>    opening_parenthesis,<br>)<br><br>call_content = text[opening_parenthesis + 1:closing_parenthesis]<br><br>if &quot;onEdit:&quot; not in call_content:<br>    content_before_close = text[:closing_parenthesis]<br>    trimmed_before_close = content_before_close.rstrip()<br><br>    line_start = text.rfind(<br>        &quot;\n&quot;,<br>        0,<br>        closing_parenthesis,<br>    ) + 1<br><br>    closing_indent = text[line_start:closing_parenthesis]<br>    argument_indent = closing_indent + &quot;  &quot;<br><br>    separator = &quot;&quot; if trimmed_before_close.endswith(&quot;,&quot;) else &quot;,&quot;<br><br>    insertion = (<br>        separator<br>        + &quot;\n&quot;<br>        + argument_indent<br>        + &quot;onEdit: _editProduct,&quot;<br>    )<br><br>    text = (<br>        text[:closing_parenthesis]<br>        + insertion<br>        + text[closing_parenthesis:]<br>    )<br><br><br># ---------------------------------------------------------<br># 7. Verify the complete Edit Product connection.<br># ---------------------------------------------------------<br><br>required_markers = [<br>    &quot;required this.onEdit,&quot;,<br>    &quot;Future&lt;Product?&gt; Function(Product product) onEdit;&quot;,<br>    &quot;late Product _product;&quot;,<br>    &quot;Product get product =&gt; _product;&quot;,<br>    &quot;Future&lt;void&gt; _handleEdit() async&quot;,<br>    &quot;tooltip: &#39;Edit product&#39;&quot;,<br>    &quot;Future&lt;Product?&gt; _editProduct(Product product) async&quot;,<br>    &quot;productToEdit: product,&quot;,<br>    &quot;onEdit: _editProduct,&quot;,<br>    &quot;_products[productIndex] = updatedProduct;&quot;,<br>    &quot;_cartItems&quot;,<br>    &quot;await _saveUserProducts();&quot;,<br>]<br><br>for marker in required_markers:<br>    if marker not in text:<br>        raise SystemExit(<br>            f&quot;Required Edit Product marker was not created: {marker}&quot;<br>        )<br><br><br>path.write_text(text, encoding=&quot;utf-8&quot;)<br><br>print(&quot;Episode 24 Edit Product connection applied successfully.&quot;)<br>print(&quot;Edit action added to ProductDetailPage.&quot;)<br>print(&quot;Built-in products remain protected.&quot;)<br>print(&quot;Edited values replace the original product.&quot;)<br>print(&quot;Favorite state follows the updated product.&quot;)<br>print(&quot;Cart quantity follows the updated product.&quot;)<br>print(&quot;Local storage is updated after editing.&quot;)<br>PY<br><br>printf &#39;\n=== FORMAT EDIT CONNECTION ===\n&#39;<br>dart format lib/main.dart<br><br>printf &#39;\n=== VERIFY EDIT CONNECTION ===\n&#39;<br>grep -nE \<br>&quot;onEdit|_handleEdit|_editProduct|Edit product|productToEdit|updatedProduct&quot; \<br>lib/main.dart</pre><p>The Edit action is now connected from the product detail page to the editable catalog.</p><p>Only user-created products display the Edit button. Selecting it opens the existing form with the product’s current information and image already loaded.</p><p>When Save Changes is pressed, the original product is replaced instead of adding a second copy. Favorite status and cart quantity are transferred to the updated product, and the revised catalog is written back to local storage</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/665/1*5mXIucsw9KLBmcuirkHmew.png" /><figcaption>Showing the Edit action only for products created inside the application.</figcaption></figure><p>The Edit Product connection now touches several parts of the application.</p><p>It updates the product detail page, replaces an item inside the editable catalog, transfers favorite and cart state, and writes the revised product list back to local storage.</p><p>Before opening the application, I will format the updated Dart file and let Flutter inspect the complete edit pipeline.</p><pre>cd ~/offline_product_catalog<br><br>printf &#39;\n=== FORMAT EPISODE 24 EDIT FLOW ===\n&#39;<br>dart format lib/main.dart<br><br>printf &#39;\n=== ANALYZE EPISODE 24 EDIT FLOW ===\n&#39;<br>flutter analyze</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/665/1*qZuvMt472ZAIa_INOv91qQ.png" /></figure><p>Flutter analysis completes without reporting any issues.</p><p>The application is now ready for a practical test. The test must confirm that built-in products remain protected, user-created products can be edited, and editing replaces the original item instead of creating a duplicate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/665/1*iQhujI1Ydd2j6h6pryTRAw.png" /><figcaption>Built-in products remain protected and do not expose catalog management controls.</figcaption></figure><p>The user-created product has now been added again using the browser’s regular local storage.</p><p>Before continuing with Edit Product, I need to confirm that the catalog can still restore this product after a complete browser refresh. This checkpoint protects the next feature from being built on temporary data.</p><p>Refreshing the browser now restores Portable Fan from local storage.</p><p>Its image, name, price, category, and description return with the catalog, confirming that the product is no longer limited to one running session.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/578/1*avThB6pRGkXC2V_ff4_Nuw.png" /><figcaption>Portable Fan remains available after the browser reloads the locally saved catalog.</figcaption></figure><p>The locally saved product is stable again, so I can return to the editing feature.</p><p>Before reopening the application, I need to confirm that every part of the Edit Product connection is present in the current source code. This avoids testing an older build or a partially applied patch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/659/1*l5pIs1VPSYiz43VmMoy1FQ.png" /></figure><p>The product form can now operate in editing mode, but the catalog still needs a way to open it.</p><p>I will add an Edit action to the product detail page. This action will only appear for products created inside the application.</p><p>After the edited Product object returns from the form, the application will replace the original item, preserve its favorite status and cart quantity, then save the updated catalog locally.</p><pre>cd ~/offline_product_catalog<br><br>backup_file=&quot;lib/main.dart.before_edit_connection_$(date +%Y%m%d_%H%M%S)&quot;<br>cp lib/main.dart &quot;$backup_file&quot;<br><br>printf &#39;\n=== BACKUP CREATED ===\n&#39;<br>printf &#39;%s\n&#39; &quot;$backup_file&quot;<br><br>python3 &lt;&lt;&#39;PY&#39;<br>from pathlib import Path<br><br>path = Path(&quot;lib/main.dart&quot;)<br>text = path.read_text(encoding=&quot;utf-8&quot;)<br><br><br>def replace_once(old: str, new: str, label: str) -&gt; None:<br>    global text<br><br>    count = text.count(old)<br><br>    if count != 1:<br>        raise SystemExit(<br>            f&quot;\nPATCH STOPPED: {label}\n&quot;<br>            f&quot;Expected 1 matching block, found {count}.\n&quot;<br>            &quot;main.dart was not changed.&quot;<br>        )<br><br>    text = text.replace(old, new, 1)<br><br><br>def find_matching_parenthesis(source: str, opening: int) -&gt; int:<br>    depth = 0<br>    quote = None<br>    escaped = False<br><br>    for index in range(opening, len(source)):<br>        character = source[index]<br><br>        if quote is not None:<br>            if escaped:<br>                escaped = False<br>            elif character == &quot;\\&quot;:<br>                escaped = True<br>            elif character == quote:<br>                quote = None<br><br>            continue<br><br>        if character in (&quot;&#39;&quot;, &#39;&quot;&#39;):<br>            quote = character<br>            continue<br><br>        if character == &quot;(&quot;:<br>            depth += 1<br>        elif character == &quot;)&quot;:<br>            depth -= 1<br><br>            if depth == 0:<br>                return index<br><br>    raise SystemExit(&quot;Matching parenthesis was not found.&quot;)<br><br><br># Confirm that the previous form patch exists.<br>required_form_markers = [<br>    &quot;final Product? productToEdit;&quot;,<br>    &quot;bool get _isEditing&quot;,<br>    &quot;&#39;Save Changes&#39;&quot;,<br>]<br><br>missing = [<br>    marker<br>    for marker in required_form_markers<br>    if marker not in text<br>]<br><br>if missing:<br>    print(&quot;\nEDIT FORM IS NOT COMPLETE&quot;)<br><br>    for marker in missing:<br>        print(f&quot;Missing: {marker}&quot;)<br><br>    raise SystemExit(<br>        &quot;\nRun the previous Edit Form patch before this patch.&quot;<br>    )<br><br><br>if &quot;Future&lt;Product?&gt; _editProduct&quot; in text:<br>    raise SystemExit(<br>        &quot;\nThe Edit Product connection already exists. &quot;<br>        &quot;The patch was not applied twice.&quot;<br>    )<br><br><br># 1. Add the Edit callback to ProductDetailPage.<br>replace_once(<br>    &quot;&quot;&quot;    required this.onToggleFavorite,<br>    required this.onAddToCart,<br>  });&quot;&quot;&quot;,<br>    &quot;&quot;&quot;    required this.onToggleFavorite,<br>    required this.onAddToCart,<br>    required this.onEdit,<br>  });&quot;&quot;&quot;,<br>    &quot;ProductDetailPage constructor&quot;,<br>)<br><br><br>replace_once(<br>    &quot;&quot;&quot;  final VoidCallback onToggleFavorite;<br>  final VoidCallback onAddToCart;&quot;&quot;&quot;,<br>    &quot;&quot;&quot;  final VoidCallback onToggleFavorite;<br>  final VoidCallback onAddToCart;<br>  final Future&lt;Product?&gt; Function(Product product) onEdit;&quot;&quot;&quot;,<br>    &quot;ProductDetailPage callback fields&quot;,<br>)<br><br><br># 2. Add the Edit handler inside the detail page.<br>replace_once(<br>    &quot;&quot;&quot;  void _handleToggleFavorite() {<br>    widget.onToggleFavorite();<br><br>    setState(() {<br>      _favorite = !_favorite;<br>    });<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {&quot;&quot;&quot;,<br>    &quot;&quot;&quot;  void _handleToggleFavorite() {<br>    widget.onToggleFavorite();<br><br>    setState(() {<br>      _favorite = !_favorite;<br>    });<br>  }<br><br>  Future&lt;void&gt; _handleEdit() async {<br>    final updatedProduct = await widget.onEdit(product);<br><br>    if (!mounted || updatedProduct == null) {<br>      return;<br>    }<br><br>    Navigator.of(context).pop();<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {&quot;&quot;&quot;,<br>    &quot;ProductDetailPage edit handler&quot;,<br>)<br><br><br># 3. Add the Edit icon before the Favorite icon.<br>replace_once(<br>    &quot;&quot;&quot;          actions: [<br>            IconButton(<br>              tooltip: isFavorite ? &#39;Remove from favorites&#39; : &#39;Add to favorites&#39;,&quot;&quot;&quot;,<br>    &quot;&quot;&quot;          actions: [<br>            if (product.imageBytes != null)<br>              IconButton(<br>                tooltip: &#39;Edit product&#39;,<br>                onPressed: _handleEdit,<br>                icon: const Icon(Icons.edit_outlined),<br>              ),<br>            IconButton(<br>              tooltip: isFavorite ? &#39;Remove from favorites&#39; : &#39;Add to favorites&#39;,&quot;&quot;&quot;,<br>    &quot;ProductDetailPage Edit icon&quot;,<br>)<br><br><br># 4. Add the parent method that replaces the original product.<br>edit_method = r&#39;&#39;&#39;<br>  Future&lt;Product?&gt; _editProduct(Product product) async {<br>    if (product.imageBytes == null) {<br>      return null;<br>    }<br><br>    final categories = _products<br>        .map((item) =&gt; item.category)<br>        .toSet()<br>        .toList()<br>      ..sort();<br><br>    final existingProductNames = _products<br>        .where((item) =&gt; !identical(item, product))<br>        .map((item) =&gt; item.name.trim().toLowerCase())<br>        .toSet();<br><br>    final updatedProduct = await Navigator.of(context).push&lt;Product&gt;(<br>      MaterialPageRoute(<br>        builder: (context) =&gt; AddProductPage(<br>          categories: categories,<br>          existingProductNames: existingProductNames,<br>          productToEdit: product,<br>        ),<br>      ),<br>    );<br><br>    if (!mounted || updatedProduct == null) {<br>      return null;<br>    }<br><br>    final productIndex = _products.indexOf(product);<br><br>    if (productIndex == -1) {<br>      return null;<br>    }<br><br>    final wasFavorite = _favoriteProductNames.contains(product.name);<br>    final cartQuantity = _cartItems[product];<br><br>    setState(() {<br>      _products[productIndex] = updatedProduct;<br><br>      if (wasFavorite) {<br>        _favoriteProductNames<br>          ..remove(product.name)<br>          ..add(updatedProduct.name);<br>      }<br><br>      if (cartQuantity != null) {<br>        _cartItems<br>          ..remove(product)<br>          ..[updatedProduct] = cartQuantity;<br>      }<br><br>      _selectedCategory = &#39;All&#39;;<br>    });<br><br>    try {<br>      await _saveUserProducts();<br>    } catch (_) {<br>      if (!mounted) {<br>        return null;<br>      }<br><br>      setState(() {<br>        _products[productIndex] = product;<br><br>        if (wasFavorite) {<br>          _favoriteProductNames<br>            ..remove(updatedProduct.name)<br>            ..add(product.name);<br>        }<br><br>        if (cartQuantity != null) {<br>          _cartItems<br>            ..remove(updatedProduct)<br>            ..[product] = cartQuantity;<br>        }<br>      });<br><br>      ScaffoldMessenger.of(context)<br>        ..hideCurrentSnackBar()<br>        ..showSnackBar(<br>          const SnackBar(<br>            content: Text(<br>              &#39;The edited product could not be saved locally.&#39;,<br>            ),<br>          ),<br>        );<br><br>      return null;<br>    }<br><br>    return updatedProduct;<br>  }<br><br>&#39;&#39;&#39;<br><br>navigation_anchor = &quot;  Future&lt;void&gt; _openAddProductPage() async {&quot;<br><br>if navigation_anchor not in text:<br>    raise SystemExit(<br>        &quot;\n_openAddProductPage was not found. &quot;<br>        &quot;main.dart was not changed.&quot;<br>    )<br><br>text = text.replace(<br>    navigation_anchor,<br>    edit_method + navigation_anchor,<br>    1,<br>)<br><br><br># 5. Connect the callback to the ProductDetailPage call.<br>call_marker = &quot;builder: (context) =&gt; ProductDetailPage(&quot;<br>call_start = text.find(call_marker)<br><br>if call_start == -1:<br>    raise SystemExit(<br>        &quot;\nThe ProductDetailPage navigation call was not found.&quot;<br>    )<br><br>product_call_start = text.find(<br>    &quot;ProductDetailPage(&quot;,<br>    call_start,<br>)<br><br>opening_parenthesis = text.find(<br>    &quot;(&quot;,<br>    product_call_start,<br>)<br><br>closing_parenthesis = find_matching_parenthesis(<br>    text,<br>    opening_parenthesis,<br>)<br><br>call_text = text[opening_parenthesis:closing_parenthesis]<br><br>if &quot;onEdit:&quot; not in call_text:<br>    line_start = text.rfind(<br>        &quot;\n&quot;,<br>        0,<br>        closing_parenthesis,<br>    ) + 1<br><br>    closing_indent = text[line_start:closing_parenthesis]<br>    argument_indent = closing_indent + &quot;  &quot;<br><br>    text = (<br>        text[:closing_parenthesis]<br>        + &quot;\n&quot;<br>        + argument_indent<br>        + &quot;onEdit: _editProduct,&quot;<br>        + text[closing_parenthesis:]<br>    )<br><br><br># 6. Verify the complete connection.<br>required_markers = [<br>    &quot;required this.onEdit,&quot;,<br>    &quot;Future&lt;Product?&gt; Function(Product product) onEdit;&quot;,<br>    &quot;Future&lt;void&gt; _handleEdit() async&quot;,<br>    &quot;tooltip: &#39;Edit product&#39;&quot;,<br>    &quot;Future&lt;Product?&gt; _editProduct(Product product) async&quot;,<br>    &quot;productToEdit: product,&quot;,<br>    &quot;_products[productIndex] = updatedProduct;&quot;,<br>    &quot;onEdit: _editProduct,&quot;,<br>    &quot;await _saveUserProducts();&quot;,<br>]<br><br>missing = [<br>    marker<br>    for marker in required_markers<br>    if marker not in text<br>]<br><br>if missing:<br>    print(&quot;\nEDIT CONNECTION VERIFICATION FAILED&quot;)<br><br>    for marker in missing:<br>        print(f&quot;Missing: {marker}&quot;)<br><br>    raise SystemExit(<br>        &quot;\nThe updated file was not written.&quot;<br>    )<br><br><br>path.write_text(text, encoding=&quot;utf-8&quot;)<br><br>print(&quot;\nEPISODE 24 EDIT CONNECTION APPLIED&quot;)<br>print(&quot;✓ Edit callback added to ProductDetailPage&quot;)<br>print(&quot;✓ Edit icon added for user-created products&quot;)<br>print(&quot;✓ Existing product opens in the form&quot;)<br>print(&quot;✓ Original catalog item is replaced&quot;)<br>print(&quot;✓ Favorite status is preserved&quot;)<br>print(&quot;✓ Cart quantity is preserved&quot;)<br>print(&quot;✓ Updated catalog is saved locally&quot;)<br>PY<br><br>printf &#39;\n=== FORMAT MAIN.DART ===\n&#39;<br>dart format lib/main.dart<br><br>printf &#39;\n=== VERIFY EDIT CONNECTION ===\n&#39;<br>grep -nE \<br>&quot;required this.onEdit|onEdit: _editProduct|_handleEdit|tooltip: &#39;Edit product&#39;|Future&lt;Product\\?&gt; _editProduct|productToEdit: product|_products\\[productIndex\\] = updatedProduct&quot; \<br>lib/main.dart</pre><p>The Edit Product connection is now part of the source code.</p><p>Before testing it in the browser, I will verify the new callback, format the Dart file, and run Flutter analysis. This confirms that the product detail page, editing form, catalog state, and local storage compile as one complete flow.</p><pre>cd ~/offline_product_catalog<br><br>printf &#39;\n=== FINAL EDIT CONNECTION CHECK ===\n&#39;<br><br>grep -nE \<br>&quot;productToEdit|_isEditing|required this.onEdit|onEdit: _editProduct|_handleEdit|tooltip: &#39;Edit product&#39;|Future&lt;Product\\?&gt; _editProduct|_products\\[productIndex\\] = updatedProduct&quot; \<br>lib/main.dart</pre><pre>printf &#39;\n=== FORMAT EPISODE 24 ===\n&#39;<br>dart format lib/main.dart<br><br>printf &#39;\n=== FLUTTER ANALYZE ===\n&#39;<br>flutter analyze</pre><p>Flutter analysis confirms that the reusable form and product-detail editing flow compile without issues.</p><p>The application is now ready to show the Edit action for locally created products.</p><p>The catalog grid is already responsible for search, category filtering, favorites, product browsing, and shopping actions.</p><p>Adding Edit and Delete buttons to every product card would make the interface crowded and could encourage accidental changes. Product management therefore belongs on the detail page, where the user has already selected a specific item.</p><p>Built-in products continue to behave like normal catalog entries. They can be viewed, favorited, and added to the cart, but they do not expose management controls.</p><p>Products created inside the application receive additional Edit and Delete actions because they belong to the locally managed catalog.</p><p>The original twenty products must remain protected.</p><p>They are part of the application’s starter catalog and use images bundled with the project. Allowing those products to be edited or deleted would change the fixed foundation used throughout this series.</p><p>User-created products are different. They contain locally selected image data and are stored separately through the persistence layer introduced in Episode 23.</p><p>That distinction gives the application a simple management rule: bundled products are read-only, while locally created products can be changed.</p><p>Creating a separate page for editing would duplicate most of the existing Add Product form.</p><p>Both actions need the same fields, image picker, category controls, validation, and Product object. The main difference is the starting state.</p><p>In Add mode, the form begins empty and returns a new product.</p><p>In Edit mode, the same form receives an existing product, copies its current values into the controllers, preserves its selected image, and returns an updated product when Save Changes is pressed.</p><p>This keeps product creation and product editing inside one reusable page instead of maintaining two nearly identical forms.</p><p>When editing begins, the form reads the existing product before the interface is displayed.</p><p>The product name, numeric price, description, category, and image bytes are copied into the current form state. This allows the user to change only the information that needs correction.</p><p>A product image does not need to be selected again unless the user wants to replace it.</p><p>The form also changes its language according to the active mode.</p><p>A new product opens a page titled Add Product with a Save Product button. An existing product opens the same page as Edit Product with a Save Changes button.</p><p>The layout remains familiar, while the title and action clearly explain what will happen.</p><p>Saving an edited form should not add another item to the catalog.</p><p>The application first locates the original product inside the editable product list. It then replaces that exact entry with the updated Product object returned by the form.</p><p>This keeps the total product count unchanged. Portable Fan becomes Rechargeable Desk Fan instead of leaving both versions in the catalog.</p><p>The edited product therefore keeps the same position in the catalog while its name, price, description, category, or image can change.</p><p>Replacing a Product object also affects other parts of the application.</p><p>The Favorites page currently tracks products by name, while the shopping cart uses Product objects as map keys. If the original product were replaced without updating those references, Favorites could lose the item and the cart could continue displaying the outdated version.</p><p>Before replacing the product, the application records its favorite status and cart quantity.</p><p>After the updated product is inserted, the favorite name and cart entry are transferred to the new Product object.</p><p>The interface update is only the first half of the edit operation.</p><p>After the original product is replaced, the application serializes the updated user-created catalog and writes it back to local storage.</p><p>This ensures that refreshing or reopening the application restores the edited version instead of bringing back the old product.</p><p>The catalog can now move beyond simple product creation.</p><p>A locally created product can reopen inside the same form with its current name, price, description, category, and image already loaded. The user can correct only the information that needs to change without rebuilding the product from the beginning.</p><p>Saving the form replaces the original catalog entry instead of creating a duplicate. The product count remains stable, while its favorite status and cart quantity move to the updated Product object.</p><p>The revised user-created catalog is then written back to local storage so the edited version can return after the application is refreshed or reopened.</p><p>This gives locally created products a proper lifecycle. They can be created, preserved, reopened, corrected, and saved again without affecting the original twenty products bundled with the application.</p><p>Editing solves incorrect or outdated product information, but a locally managed catalog also needs a safe way to remove products that are no longer required.</p><p>The next part of Episode 24 will add Delete Product with a confirmation dialog. Deleting an item must remove it from the catalog, clear its favorite and cart references, update local storage, and prevent the product from returning after a refresh.</p><p>Locally created products can now be reopened, corrected, and saved without changing the protected built-in catalog.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c0c4eedb9da8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Episode 23: Saving the Product Catalog Locally in Flutter]]></title>
            <link>https://medium.com/@lenakendari/episode-23-saving-the-product-catalog-locally-in-flutter-9a7c358574c8?source=rss-932b58a7a66a------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a7c358574c8</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Atelier Flutter]]></dc:creator>
            <pubDate>Fri, 24 Jul 2026 13:13:19 GMT</pubDate>
            <atom:updated>2026-07-24T13:13:19.445Z</atom:updated>
            <content:encoded><![CDATA[<p>I add local persistence so user-created products, custom categories, prices, descriptions, and selected images survive an app restart.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z-jrRYXv_aWYK2DXyeIXhA.png" /></figure><p>At the end of Episode 22, the catalog could finally grow from inside the application.</p><p>A user could choose a product image, enter a name, price, description, and category, then save the new item directly into the catalog. The product immediately worked with search, category filters, product details, favorites, and the shopping cart.</p><p>The problem was that the new data only lived in memory.</p><p>Refreshing Chrome or restarting the application returned the catalog to its original twenty products. The newly added image, custom category, price, and description disappeared with the running session.</p><p>In this episode, I am making that catalog persistent.</p><p>The application will save user-created products locally, restore them when it starts, and rebuild the editable catalog without requiring a server or internet connection.</p><p>The original products will remain bundled with the app, while products created by the user will be stored separately and merged back into the catalog during startup.</p><p>The goal is simple: when a product is added today, it should still be there the next time the application opens.</p><p>The catalog now needs a storage format that can preserve every part of a user-created product.</p><p>Text fields such as the name, price, description, and category are straightforward. The selected image needs more attention because it currently exists as image bytes in memory.</p><p>Before adding a storage package, I need to inspect the latest Product model, the editable product state, and the exact method that adds a new product to the catalog.</p><pre>cd ~/offline_product_catalog<br><br>printf &#39;\n=== CURRENT DEPENDENCIES ===\n&#39;<br>sed -n &#39;/^dependencies:/,/^dev_dependencies:/p&#39; pubspec.yaml<br><br>printf &#39;\n=== LOCAL STORAGE PACKAGE CHECK ===\n&#39;<br>grep -nE \<br>&quot;shared_preferences|hive|isar|sqflite|sembast|path_provider&quot; \<br>pubspec.yaml || true<br><br>printf &#39;\n=== PRODUCT MODEL ===\n&#39;<br>product_line=$(grep -nE &#39;^class Product\b&#39; lib/main.dart | head -n 1 | cut -d: -f1)<br><br>if [ -n &quot;$product_line&quot; ]; then<br>  start=$((product_line - 2))<br>  end=$((product_line + 45))<br><br>  if [ &quot;$start&quot; -lt 1 ]; then<br>    start=1<br>  fi<br><br>  nl -ba lib/main.dart | sed -n &quot;${start},${end}p&quot;<br>else<br>  printf &#39;Product class was not found.\n&#39;<br>fi<br><br>printf &#39;\n=== EDITABLE PRODUCT STATE ===\n&#39;<br>grep -nE \<br>&quot;initialProducts|late final List&lt;Product&gt; _products|void initState|_products =|_products.add|_openAddProductPage&quot; \<br>lib/main.dart</pre><p>This inspection shows what the application must serialize and restore.</p><p>The built-in products already belong to the compiled application, so they do not need to be saved again. Local storage only needs to preserve products created through the Add Product form.</p><p>When the app starts, it can rebuild the catalog by combining the original products with the saved user-created products.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/669/1*Qceto_dxcTYNSjCzJ1aooQ.png" /><figcaption>Reviewing the editable product model and current dependencies before choosing a local persistence strategy.</figcaption></figure><pre>cd ~/offline_product_catalog<br><br>printf &#39;\n=== AVAILABLE DEVICES ===\n&#39;<br>flutter devices<br>flutter run -d chrome</pre><p>Flutter launched the current catalog in Chrome.</p><p>At this point, the application is still using memory-only product state. I will confirm that behavior before adding any local storage code.</p><p>The test confirmed the current limitation.</p><p>The new product appeared correctly during the running session, but refreshing Chrome restored the original twenty-product catalog. The product data and selected image were not loaded again because nothing had been written to local storage yet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/665/1*VAnoxw1Z1Ypj38aQI9oP-Q.png" /><figcaption>A user-created product working correctly during the current application session.</figcaption></figure><p>The current limitation is now visible.</p><p>A user-created product works during the active session, but refreshing Chrome removes it and restores the original catalog. The form is working, the image is displayed correctly, and the product can use the existing shopping features, but none of that data survives a restart.</p><p>The next step is to add local persistence.</p><p>In this episode, I will save only the products created by the user. The original twenty products will remain bundled with the application, while locally saved products will be loaded and merged into the catalog when the app starts.</p><p>Each saved product must preserve its name, price, description, category, and selected image. The image bytes will be converted into a text format before storage, then restored when the catalog is loaded again.</p><p>The final test will be simple: add a product, refresh Chrome, and confirm that the product is still there.</p><p>Choosing a Local Storage Strategy</p><p>The catalog does not need a full database yet.</p><p>Episode 23 only needs to save a small collection of user-created products and restore them when the application starts. Each product can be converted into JSON, and the complete list can be stored as one string value.</p><p>For this stage, I will use Flutter’s shared_preferences plugin. On the web, it stores data through the browser’s local storage, while the same plugin also supports the other Flutter platforms.</p><p>A database would provide more advanced querying and record management, but it would add more structure than this episode currently needs.</p><p>The catalog only needs one local list that can be saved and restored. Editing, deleting, and larger data-management concerns can be introduced after persistence is working.</p><p>The storage plan is now clear. Before changing the Product model or startup flow, I will add the shared_preferences plugin to the project and let Flutter select a compatible package version.</p><pre>cd ~/offline_product_catalog<br><br>printf &#39;\n=== ADD LOCAL STORAGE DEPENDENCY ===\n&#39;<br><br>if grep -qE &#39;^[[:space:]]+shared_preferences:&#39; pubspec.yaml; then<br>  printf &#39;shared_preferences is already listed in pubspec.yaml.\n&#39;<br>else<br>  flutter pub add shared_preferences<br>fi<br><br>printf &#39;\n=== VERIFY DEPENDENCIES ===\n&#39;<br>grep -n -A 14 -B 2 &#39;^dependencies:&#39; pubspec.yaml<br><br>printf &#39;\n=== PACKAGE STATUS ===\n&#39;<br>flutter pub get</pre><p>The local storage plugin is now part of the project.</p><p>No catalog data is being saved yet. This step only prepares the application for the serialization and startup logic that will follow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/665/1*GitTc_yN4uWqyvA8ErLzFw.png" /><figcaption>Adding lightweight local storage before serializing the user-created catalog.</figcaption></figure><p>The local storage dependency is ready, but the application code has not started saving anything yet.</p><p>Persistence will affect the Product model, the Add Product flow, the application startup process, and the catalog loading state. Before changing those connected sections, I am preserving the complete Episode 22 implementation as a recovery point.</p><pre>cd ~/offline_product_catalog<br><br>backup_file=&quot;lib/main.dart.episode22_backup_$(date +%Y%m%d_%H%M%S)&quot;<br>cp lib/main.dart &quot;$backup_file&quot;<br><br>printf &#39;\n=== EPISODE 22 BACKUP CREATED ===\n&#39;<br>printf &#39;%s\n&#39; &quot;$backup_file&quot;<br><br>printf &#39;\n=== STORAGE DEPENDENCY ===\n&#39;<br>grep -n &quot;shared_preferences&quot; pubspec.yaml || true<br><br>printf &#39;\n=== CURRENT IMPORTS ===\n&#39;<br>nl -ba lib/main.dart | sed -n &#39;1,16p&#39;<br><br>printf &#39;\n=== PRODUCT SERIALIZATION TARGETS ===\n&#39;<br>grep -nE \<br>&quot;^class Product\b|imageBytes|imagePath|priceValue|^const initialProducts&quot; \<br>lib/main.dart<br><br>printf &#39;\n=== STARTUP AND EDITABLE STATE ===\n&#39;<br>grep -nE \<br>&quot;^class _MyHomePageState|late final List&lt;Product&gt; _products|void initState|_products = List|_openAddProductPage|_products.add&quot; \<br>lib/main.dart</pre><p>The backup preserves the complete in-memory catalog before persistence changes begin.</p><p>The inspection also confirms the exact locations where the storage flow needs to connect. The Product model needs JSON conversion, the home page startup needs to restore saved products, and the Add Product method needs to write the updated user-created catalog after a product is added.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/665/1*XBIFhT89gGoRyM1W557p6Q.png" /><figcaption>Creating a clean Episode 22 backup and locating the exact startup and product state needed for local persistence.</figcaption></figure><p>The storage package is ready, and the current catalog structure has been preserved in a backup.</p><p>For the persistence layer, I will use the newer SharedPreferencesAsync API. It reads and writes directly through the platform storage instead of relying on the older cached SharedPreferences API.</p><p>The application will serialize only user-created products into JSON. Their selected image bytes will be converted to Base64 text before storage and decoded back into image bytes during startup.</p><pre>cd ~/offline_product_catalog<br><br>python3 &lt;&lt;&#39;PY&#39;<br>from pathlib import Path<br><br>path = Path(&quot;lib/main.dart&quot;)<br>text = path.read_text(encoding=&quot;utf-8&quot;)<br><br>if &quot;_userProductsStorageKey&quot; in text:<br>    raise SystemExit(<br>        &quot;Local persistence already exists. The patch was not applied again.&quot;<br>    )<br><br><br>def replace_once(old: str, new: str, label: str) -&gt; None:<br>    global text<br><br>    count = text.count(old)<br><br>    if count != 1:<br>        raise SystemExit(<br>            f&quot;{label}: expected exactly one match, but found {count}.&quot;<br>        )<br><br>    text = text.replace(old, new, 1)<br><br><br># 1. Add JSON conversion and local storage imports.<br>replace_once(<br>    &quot;import &#39;package:flutter/material.dart&#39;;&quot;,<br>    &quot;&quot;&quot;import &#39;dart:convert&#39;;<br><br>import &#39;package:flutter/material.dart&#39;;&quot;&quot;&quot;,<br>    &quot;JSON import&quot;,<br>)<br><br>replace_once(<br>    &quot;import &#39;package:image_picker/image_picker.dart&#39;;&quot;,<br>    &quot;&quot;&quot;import &#39;package:image_picker/image_picker.dart&#39;;<br>import &#39;package:shared_preferences/shared_preferences.dart&#39;;&quot;&quot;&quot;,<br>    &quot;Shared preferences import&quot;,<br>)<br><br><br># 2. Add Product serialization after the numeric price getter.<br>price_getter = &quot;&quot;&quot;  double get priceValue {<br>    return double.parse(price.replaceFirst(r&#39;$&#39;, &#39;&#39;));<br>  }&quot;&quot;&quot;<br><br>serialization = &quot;&quot;&quot;  double get priceValue {<br>    return double.parse(price.replaceFirst(r&#39;$&#39;, &#39;&#39;));<br>  }<br><br>  Map&lt;String, dynamic&gt; toJson() {<br>    return {<br>      &#39;name&#39;: name,<br>      &#39;description&#39;: description,<br>      &#39;price&#39;: price,<br>      &#39;category&#39;: category,<br>      &#39;imageBase64&#39;: imageBytes == null<br>          ? null<br>          : base64Encode(imageBytes!),<br>    };<br>  }<br><br>  factory Product.fromJson(Map&lt;String, dynamic&gt; json) {<br>    final encodedImage = json[&#39;imageBase64&#39;] as String?;<br><br>    return Product(<br>      name: json[&#39;name&#39;] as String,<br>      description: json[&#39;description&#39;] as String,<br>      price: json[&#39;price&#39;] as String,<br>      icon: Icons.inventory_2_outlined,<br>      category: json[&#39;category&#39;] as String,<br>      imageBytes: encodedImage == null || encodedImage.isEmpty<br>          ? null<br>          : base64Decode(encodedImage),<br>    );<br>  }&quot;&quot;&quot;<br><br>replace_once(<br>    price_getter,<br>    serialization,<br>    &quot;Product JSON serialization&quot;,<br>)<br><br><br># 3. Add persistence fields beside the editable product list.<br>replace_once(<br>    &quot;&quot;&quot;  late final List&lt;Product&gt; _products;<br><br>  final Set&lt;String&gt; _favoriteProductNames = {};&quot;&quot;&quot;,<br>    &quot;&quot;&quot;  static const String _userProductsStorageKey =<br>      &#39;offline_catalog_user_products_v1&#39;;<br><br>  final SharedPreferencesAsync _preferences =<br>      SharedPreferencesAsync();<br><br>  late final List&lt;Product&gt; _products;<br>  bool _isCatalogLoading = true;<br><br>  final Set&lt;String&gt; _favoriteProductNames = {};&quot;&quot;&quot;,<br>    &quot;Persistence state&quot;,<br>)<br><br><br># 4. Start restoring products when the home page is created.<br>replace_once(<br>    &quot;&quot;&quot;  @override<br>  void initState() {<br>    super.initState();<br>    _products = List&lt;Product&gt;.of(initialProducts);<br>  }&quot;&quot;&quot;,<br>    &quot;&quot;&quot;  @override<br>  void initState() {<br>    super.initState();<br>    _products = List&lt;Product&gt;.of(initialProducts);<br>    _loadSavedProducts();<br>  }&quot;&quot;&quot;,<br>    &quot;Startup loading&quot;,<br>)<br><br><br># 5. Add save and restore methods before the favorite helpers.<br>persistence_methods = r&#39;&#39;&#39;<br>  Future&lt;void&gt; _loadSavedProducts() async {<br>    try {<br>      final storedCatalog = await _preferences.getString(<br>        _userProductsStorageKey,<br>      );<br><br>      if (storedCatalog == null || storedCatalog.trim().isEmpty) {<br>        if (!mounted) {<br>          return;<br>        }<br><br>        setState(() {<br>          _isCatalogLoading = false;<br>        });<br><br>        return;<br>      }<br><br>      final decodedCatalog = jsonDecode(storedCatalog);<br><br>      if (decodedCatalog is! List&lt;dynamic&gt;) {<br>        throw const FormatException(<br>          &#39;The saved product catalog is not a JSON list.&#39;,<br>        );<br>      }<br><br>      final restoredProducts = decodedCatalog.map((item) {<br>        if (item is! Map&lt;String, dynamic&gt;) {<br>          throw const FormatException(<br>            &#39;A saved product has an invalid structure.&#39;,<br>          );<br>        }<br><br>        return Product.fromJson(item);<br>      }).toList();<br><br>      if (!mounted) {<br>        return;<br>      }<br><br>      setState(() {<br>        final existingNames = _products<br>            .map((product) =&gt; product.name.trim().toLowerCase())<br>            .toSet();<br><br>        for (final product in restoredProducts) {<br>          final normalizedName = product.name.trim().toLowerCase();<br><br>          if (existingNames.add(normalizedName)) {<br>            _products.add(product);<br>          }<br>        }<br><br>        _isCatalogLoading = false;<br>      });<br>    } catch (_) {<br>      if (!mounted) {<br>        return;<br>      }<br><br>      setState(() {<br>        _isCatalogLoading = false;<br>      });<br><br>      WidgetsBinding.instance.addPostFrameCallback((_) {<br>        if (!mounted) {<br>          return;<br>        }<br><br>        ScaffoldMessenger.of(context)<br>          ..hideCurrentSnackBar()<br>          ..showSnackBar(<br>            const SnackBar(<br>              content: Text(<br>                &#39;The saved catalog could not be restored. &#39;<br>                &#39;The built-in products are still available.&#39;,<br>              ),<br>            ),<br>          );<br>      });<br>    }<br>  }<br><br>  Future&lt;void&gt; _saveUserProducts() async {<br>    final userProducts = _products<br>        .where((product) =&gt; product.imageBytes != null)<br>        .map((product) =&gt; product.toJson())<br>        .toList();<br><br>    final encodedCatalog = jsonEncode(userProducts);<br><br>    await _preferences.setString(<br>      _userProductsStorageKey,<br>      encodedCatalog,<br>    );<br>  }<br><br>&#39;&#39;&#39;<br><br>replace_once(<br>    &quot;&quot;&quot;  bool _isFavorite(Product product) {&quot;&quot;&quot;,<br>    persistence_methods + &quot;  bool _isFavorite(Product product) {&quot;,<br>    &quot;Persistence methods&quot;,<br>)<br><br><br># 6. Save the editable catalog after a new product is added.<br>replace_once(<br>    &quot;&quot;&quot;    setState(() {<br>      _products.add(product);<br>      _selectedCategory = &#39;All&#39;;<br>      _selectedTab = 0;<br>    });<br><br>    ScaffoldMessenger.of(context)&quot;&quot;&quot;,<br>    &quot;&quot;&quot;    setState(() {<br>      _products.add(product);<br>      _selectedCategory = &#39;All&#39;;<br>      _selectedTab = 0;<br>    });<br><br>    try {<br>      await _saveUserProducts();<br>    } catch (_) {<br>      if (!mounted) {<br>        return;<br>      }<br><br>      ScaffoldMessenger.of(context)<br>        ..hideCurrentSnackBar()<br>        ..showSnackBar(<br>          const SnackBar(<br>            content: Text(<br>              &#39;The product was added, but it could not be saved locally.&#39;,<br>            ),<br>          ),<br>        );<br><br>      return;<br>    }<br><br>    if (!mounted) {<br>      return;<br>    }<br><br>    ScaffoldMessenger.of(context)&quot;&quot;&quot;,<br>    &quot;Save after Add Product&quot;,<br>)<br><br><br># 7. Show a loading state while local products are restored.<br>replace_once(<br>    &quot;&quot;&quot;      body: IndexedStack(index: _selectedTab, children: pages),&quot;&quot;&quot;,<br>    &quot;&quot;&quot;      body: _isCatalogLoading<br>          ? const Center(<br>              child: Column(<br>                mainAxisSize: MainAxisSize.min,<br>                children: [<br>                  CircularProgressIndicator(),<br>                  SizedBox(height: 16),<br>                  Text(<br>                    &#39;Loading saved catalog...&#39;,<br>                    style: TextStyle(<br>                      fontSize: 16,<br>                      fontWeight: FontWeight.w600,<br>                    ),<br>                  ),<br>                ],<br>              ),<br>            )<br>          : IndexedStack(<br>              index: _selectedTab,<br>              children: pages,<br>            ),&quot;&quot;&quot;,<br>    &quot;Catalog loading state&quot;,<br>)<br><br><br># 8. Verify the complete persistence structure before writing.<br>required_markers = [<br>    &quot;import &#39;dart:convert&#39;;&quot;,<br>    &quot;SharedPreferencesAsync&quot;,<br>    &quot;Map&lt;String, dynamic&gt; toJson()&quot;,<br>    &quot;factory Product.fromJson&quot;,<br>    &quot;_userProductsStorageKey&quot;,<br>    &quot;Future&lt;void&gt; _loadSavedProducts()&quot;,<br>    &quot;Future&lt;void&gt; _saveUserProducts()&quot;,<br>    &quot;await _saveUserProducts();&quot;,<br>    &quot;&#39;Loading saved catalog...&#39;&quot;,<br>]<br><br>for marker in required_markers:<br>    if marker not in text:<br>        raise SystemExit(<br>            f&quot;Required persistence marker was not created: {marker}&quot;<br>        )<br><br><br>path.write_text(text, encoding=&quot;utf-8&quot;)<br><br>print(&quot;Episode 23 local persistence patch applied successfully.&quot;)<br>print(&quot;Product JSON conversion added.&quot;)<br>print(&quot;Base64 image storage added.&quot;)<br>print(&quot;Startup catalog restoration added.&quot;)<br>print(&quot;Automatic saving after Add Product added.&quot;)<br>print(&quot;Updated file:&quot;, path)<br>PY<br><br>printf &#39;\n=== FORMAT PERSISTENCE CODE ===\n&#39;<br>dart format lib/main.dart</pre><p>The persistence layer now connects product creation with application startup.</p><p>A user-created product is converted into a JSON map containing its name, description, price, category, and Base64 image. The complete user-created catalog is stored as one JSON string.</p><p>When the application starts, it reads that string, rebuilds each Product object, and merges the restored products with the original catalog. Duplicate names are ignored so the built-in products are not added more than once.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/665/1*hVmE7K99Zf5HPaOb_rZUNg.png" /><figcaption>Connecting product creation to JSON, Base64 image storage, and automatic catalog restoration.</figcaption></figure><pre>cd ~/offline_product_catalog<br><br>printf &#39;\n=== EPISODE 23 LOCATIONS ===\n&#39;<br>grep -nE \<br>&quot;dart:convert|shared_preferences|Map&lt;String, dynamic&gt; toJson|factory Product.fromJson|_userProductsStorageKey|SharedPreferencesAsync|_isCatalogLoading|_loadSavedProducts|_saveUserProducts|Loading saved catalog&quot; \<br>lib/main.dart</pre><p>The terminal now shows the exact locations of the persistence code.</p><p>The Product model should contain both JSON conversion methods, while the home page state should contain the storage key, the asynchronous preferences object, the loading flag, and the save and restore methods.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/665/1*i4lrcS6v_x4C2VfMoRdCVw.png" /><figcaption>Serializing user-created products and selected images into JSON.</figcaption></figure><p>The persistence flow is now visible from beginning to end.</p><p>A new product is added to the editable catalog, serialized into JSON, and written to local storage. During the next startup, the saved JSON is decoded, rebuilt into Product objects, and merged with the original catalog before the main interface appears.</p><pre>cd ~/offline_product_catalog<br><br>printf &#39;\n=== FORMAT CHECK ===\n&#39;<br>dart format lib/main.dart<br><br>printf &#39;\n=== FLUTTER ANALYZE ===\n&#39;<br>flutter analyze</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/665/1*LBndKgcJg79VcJBN-GxqOQ.png" /><figcaption>Analyzing offline_product_catalog…<br>No issues found!</figcaption></figure><p>The analyzer is clean, so the persistence flow is ready for a full application test.</p><p>This test needs to prove more than product creation. The product must survive a browser refresh, keep its selected image, preserve its custom category, and return with the same price and description.</p><pre>cd ~/offline_product_catalog<br><br>printf &#39;\n=== AVAILABLE DEVICES ===\n&#39;<br>flutter devices<br><br>printf &#39;\n=== RUN EPISODE 23 ===\n&#39;<br>flutter run -d chrome</pre><p>The application now starts by checking local storage before showing the catalog.</p><p>If no saved products exist yet, the built-in twenty-product catalog appears normally. If local products are found, they are decoded and merged into the catalog before the main interface is displayed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/665/1*8gRw5siOVLxEXJ0o6pu1XQ.png" /></figure><p>The application now starts by checking local storage before showing the catalog.</p><p>If no saved products exist yet, the built-in twenty-product catalog appears normally. If local products are found, they are decoded and merged into the catalog before the main interface is displayed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/665/1*sto2bV0p9AcGx2HlbditRA.png" /><figcaption>The new product is added to the editable catalog and written to local storage.</figcaption></figure><p>This time, refreshing Chrome does not return the application to the original catalog.</p><p>The saved JSON is read from browser storage, the Base64 image is converted back into image bytes, and the user-created product is rebuilt before the catalog appears.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/665/1*9NQL83csAxv0vcJHGiWE0Q.png" /><figcaption>The restored product keeps its image, category, price, and description.</figcaption></figure><p>The persistence test is complete.</p><p>A product created inside the application now survives a browser refresh, keeps its selected image, preserves its custom category, and returns with the same price and description.</p><p>The catalog also remains stable after repeated refreshes. The original twenty products are loaded from the application, while only user-created products are restored from local storage.</p><pre>cd ~/offline_product_catalog<br><br>printf &#39;\n=== FINAL FORMAT ===\n&#39;<br>dart format lib/main.dart<br><br>printf &#39;\n=== FINAL ANALYZE ===\n&#39;<br>flutter analyze<br><br>printf &#39;\n=== EPISODE 23 FEATURES ===\n&#39;<br>grep -nE \<br>&quot;SharedPreferencesAsync|toJson|fromJson|base64Encode|base64Decode|_loadSavedProducts|_saveUserProducts|Loading saved catalog&quot; \<br>lib/main.dart</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/665/1*OTQ62FI8_iFhtN-KVsQPTA.png" /><figcaption>The completed persistence layer passes Flutter analysis with no issues.</figcaption></figure><p>Episode 23 started with a catalog that could accept new products but could not remember them.</p><p>The Add Product form already worked, selected images appeared correctly, and new categories immediately became part of the catalog. The missing piece was persistence.</p><p>By adding local storage, JSON serialization, Base64 image conversion, startup restoration, and a loading state, the catalog can now rebuild itself after a refresh or restart.</p><p>The original twenty products remain part of the application, while user-created products are stored separately and merged back into the catalog during startup.</p><p>This keeps the implementation simple, avoids duplicate products, and preserves the offline direction of the project.</p><p>The catalog is no longer temporary.</p><p>A product added today will still be there the next time the application opens.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a7c358574c8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Episode 22: Adding Products from Inside the Flutter App]]></title>
            <link>https://medium.com/@lenakendari/episode-22-adding-products-from-inside-the-flutter-app-be5de5de8412?source=rss-932b58a7a66a------2</link>
            <guid isPermaLink="false">https://medium.com/p/be5de5de8412</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[imagepicker]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Atelier Flutter]]></dc:creator>
            <pubDate>Tue, 21 Jul 2026 15:08:47 GMT</pubDate>
            <atom:updated>2026-07-21T15:08:47.006Z</atom:updated>
            <content:encoded><![CDATA[<p>I turn the static catalog into an editable local product manager with product photos, custom categories, prices, descriptions, and a simple Add Product form.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5IBB5Bj63OA-7EI91sYzJw.png" /></figure><p>At the end of Episode 21, the application finally had a working shopping cart. Products could be added from the catalog and detail page, quantities could change, items could be removed, and the order total updated automatically.</p><p>The shopping flow now works, but the catalog itself is still fixed. All twenty products are still written directly inside the source code, which means adding a new item requires opening `main.dart`, editing the product list, adding an asset image, and rebuilding the application.</p><p>That approach is acceptable for a static tutorial catalog, but it is not practical for an application that should be managed by someone from inside the interface.</p><p>In this episode, I am beginning to change that.</p><p>I will add a simple product form where a user can choose an image, enter a product name, price, description, and category, then save the new item directly into the catalog.</p><p>The new product should immediately work with the features already built. It should appear in search results, category filters, product details, favorites, and the shopping cart.</p><p>For now, the new data will remain in memory while the application is running. Permanent local storage will be handled in the next episode, once the product creation flow is working correctly.</p><p>The catalog now needs a different kind of state.</p><p>Until this point, the application has read its products from a fixed list near the top of `main.dart`. That worked while the catalog only contained the original twenty products, but a product created from inside the app cannot be added to a constant list.</p><p>Before changing the model or building the form, I need to inspect the current Product class, the product list, the shared home page state, and every place that still reads directly from `products`.</p><pre>cd ~/offline_product_catalog<br><br>printf &#39;\n=== PROJECT LOCATION ===\n&#39;<br>pwd<br><br>printf &#39;\n=== PRODUCT MODEL AND PRODUCT LIST ===\n&#39;<br>grep -nE \<br>&quot;^class Product|^const products|^final products|priceValue|final String imagePath|final double&quot; \<br>lib/main.dart<br><br>printf &#39;\n=== EVERY DIRECT PRODUCTS REFERENCE ===\n&#39;<br>grep -nE \<br>&quot;\bproducts\b|filteredProducts|favoriteProducts|categories =&quot; \<br>lib/main.dart<br><br>printf &#39;\n=== HOME STATE AND APP BAR ===\n&#39;<br>grep -nE \<br>&quot;^class _MyHomePageState|Widget build\(BuildContext context\)|appBar: AppBar|actions:&quot; \<br>lib/main.dart</pre><p>This search gives me a current map of the catalog after the shopping cart changes.</p><p>The important question is no longer only how a product is displayed. I need to know which parts of the application assume that the product list can never change.</p><p>Any direct dependency on the original constant list must eventually read from one shared, editable collection instead.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*hj5MbeXVgTmrpcpC_Cszag.png" /><figcaption>Mapping every fixed catalog dependency before adding products from inside the app.</figcaption></figure><p>The catalog inspection identifies the places that still depend on the original fixed product list.</p><p>Before changing that structure, I am creating a fresh backup of the working Episode 21 file. The shopping cart, favorites, product details, search, filters, and navigation already work, so this version should remain available as a clean recovery point.</p><pre>cd ~/offline_product_catalog<br><br>backup_file=&quot;lib/main.dart.episode21_backup_$(date +%Y%m%d_%H%M%S)&quot;<br>cp lib/main.dart &quot;$backup_file&quot;<br><br>printf &#39;\n=== BACKUP CREATED ===\n&#39;<br>printf &#39;%s\n&#39; &quot;$backup_file&quot;<br><br>python3 &lt;&lt;&#39;PY&#39;<br>from pathlib import Path<br>import re<br><br>path = Path(&quot;lib/main.dart&quot;)<br>lines = path.read_text(encoding=&quot;utf-8&quot;).splitlines()<br><br>sections = [<br>    (<br>        &quot;PRODUCT MODEL&quot;,<br>        r&quot;^class Product\b&quot;,<br>        3,<br>        55,<br>    ),<br>    (<br>        &quot;INITIAL PRODUCT LIST&quot;,<br>        r&quot;^(const|final)\s+products\s*=&quot;,<br>        3,<br>        40,<br>    ),<br>    (<br>        &quot;HOME PAGE STATE&quot;,<br>        r&quot;^class _MyHomePageState\b&quot;,<br>        3,<br>        190,<br>    ),<br>    (<br>        &quot;CATALOG PAGE&quot;,<br>        r&quot;Widget _buildCatalogPage\(&quot;,<br>        5,<br>        270,<br>    ),<br>    (<br>        &quot;FAVORITES PAGE&quot;,<br>        r&quot;Widget _buildFavorites&quot;,<br>        5,<br>        220,<br>    ),<br>]<br><br>for title, pattern, before, after in sections:<br>    match_index = next(<br>        (<br>            index<br>            for index, line in enumerate(lines)<br>            if re.search(pattern, line)<br>        ),<br>        None,<br>    )<br><br>    print(f&quot;\n=== {title} ===&quot;)<br><br>    if match_index is None:<br>        print(f&quot;Pattern not found: {pattern}&quot;)<br>        continue<br><br>    start = max(0, match_index - before)<br>    end = min(len(lines), match_index + after + 1)<br><br>    for index in range(start, end):<br>        print(f&quot;{index + 1:5}  {lines[index]}&quot;)<br>PY</pre><p>The backup preserves the complete Episode 21 implementation, while the inspection script prints the current catalog structure with real line numbers.</p><p>I am checking more than the Product model. The editable catalog will also affect search results, category filters, favorites, product details, and the cart. Every one of those features must eventually read from the same product collection.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*r3lKNjv-GEYIr_I7HYxWOQ.png" /><figcaption>Creating an Episode 21 backup and reviewing the fixed product model before making the catalog editable.</figcaption></figure><p>The catalog is ready to become editable, but product creation needs more than a new list.</p><p>The form must collect text values, validate the price, allow an existing category or a new one, and provide an image that can be displayed by the catalog. Before adding that flow, I need to check the current dependencies and confirm how the project is configured for local images.</p><pre>cd ~/offline_product_catalog<br><br>printf &#39;\n=== FLUTTER AND DART VERSIONS ===\n&#39;<br>flutter --version<br><br>printf &#39;\n=== CURRENT DEPENDENCIES ===\n&#39;<br>sed -n &#39;/^dependencies:/,/^dev_dependencies:/p&#39; pubspec.yaml<br><br>printf &#39;\n=== CURRENT PRODUCT ASSETS ===\n&#39;<br>grep -n -A 12 -B 3 &quot;assets:&quot; pubspec.yaml<br><br>printf &#39;\n=== IMAGE PICKER CHECK ===\n&#39;<br>grep -n &quot;image_picker&quot; pubspec.yaml || true<br><br>printf &#39;\n=== CURRENT PRODUCT MODEL ===\n&#39;<br>product_line=$(grep -nE &#39;^class Product\b&#39; lib/main.dart | head -n 1 | cut -d: -f1)<br><br>if [ -n &quot;$product_line&quot; ]; then<br>  start=$((product_line - 2))<br>  end=$((product_line + 35))<br><br>  if [ &quot;$start&quot; -lt 1 ]; then<br>    start=1<br>  fi<br><br>  nl -ba lib/main.dart | sed -n &quot;${start},${end}p&quot;<br>else<br>  printf &#39;Product class was not found.\n&#39;<br>fi<br><br>printf &#39;\n=== CURRENT HOME STATE ===\n&#39;<br>state_line=$(grep -nE &#39;^class _MyHomePageState\b&#39; lib/main.dart | head -n 1 | cut -d: -f1)<br><br>if [ -n &quot;$state_line&quot; ]; then<br>  start=$((state_line - 2))<br>  end=$((state_line + 90))<br><br>  nl -ba lib/main.dart | sed -n &quot;${start},${end}p&quot;<br>else<br>  printf &#39;_MyHomePageState was not found.\n&#39;<br>fi</pre><p>The dependency check tells me whether the project already has a way to select images. It also confirms that the original product pictures are still registered as Flutter assets.</p><p>The built-in products can continue using those asset paths. Products created from inside the application will need a second image source, because a selected file is not automatically part of the compiled asset bundle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*rjbSBFJ1M-cKj04IAlcLFA.png" /><figcaption>Checking the current Flutter dependencies and asset setup before adding product image selection.</figcaption></figure><p>The existing product images are bundled with the application as Flutter assets. A product created after the app starts needs a different path because its image does not exist inside the original asset folder.</p><p>For the Add Product form, I will use Flutter’s image picker so the user can select a product photo from the device. The selected image will be read into memory and displayed immediately in the catalog.</p><pre>cd ~/offline_product_catalog<br><br>printf &#39;\n=== IMAGE PICKER DEPENDENCY ===\n&#39;<br><br>if grep -qE &#39;^[[:space:]]+image_picker:&#39; pubspec.yaml; then<br>  printf &#39;image_picker is already listed in pubspec.yaml.\n&#39;<br>else<br>  flutter pub add image_picker<br>fi<br><br>printf &#39;\n=== VERIFY PUBSPEC ===\n&#39;<br>grep -n -A 12 -B 2 &#39;^dependencies:&#39; pubspec.yaml<br><br>printf &#39;\n=== PACKAGE STATUS ===\n&#39;<br>flutter pub get</pre><pre>if grep -qE &#39;^[[:space:]]+image_picker:&#39; pubspec.yaml</pre><p>The image picker is now part of the project.</p><p>I did not manually type a package version into `pubspec.yaml`. Using `flutter pub add` allows Flutter to select a compatible version and update the dependency files consistently.</p><p>No visible part of the application has changed yet. This step only prepares the project for the image field that will be added to the product form.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*5XI2Agw8Wlt4LXuNalvDdA.png" /><figcaption>Adding image selection support before building the new product form.</figcaption></figure><p>The image picker was added successfully, and Flutter resolved the project dependencies without errors.</p><p>The terminal also reported that several packages have newer versions outside the current dependency constraints. I am leaving those versions unchanged because they are not required for this feature, and the project already has a compatible working dependency set.</p><p>The next change is inside the Product model.</p><p>The original products still use asset paths, while products created from the form will use image bytes selected at runtime. The model therefore needs to support both image sources without breaking the twenty products that already work.</p><pre>cd ~/offline_product_catalog<br><br>printf &#39;\n=== CURRENT IMPORTS ===\n&#39;<br>nl -ba lib/main.dart | sed -n &#39;1,12p&#39;<br><br>printf &#39;\n=== CURRENT PRODUCT MODEL ===\n&#39;<br>product_line=$(grep -nE &#39;^class Product\b&#39; lib/main.dart | head -n 1 | cut -d: -f1)<br><br>start=$((product_line - 2))<br>end=$((product_line + 35))<br><br>if [ &quot;$start&quot; -lt 1 ]; then<br>  start=1<br>fi<br><br>nl -ba lib/main.dart | sed -n &quot;${start},${end}p&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*AKcRmANtl-qg0Iv88tLtOQ.png" /><figcaption>Reviewing the current imports and Product model before supporting selected product images.</figcaption></figure><p>The image picker is ready, so I can now connect the complete product creation flow.</p><p>The original twenty products will remain as the initial catalog. When the application starts, they will be copied into an editable list owned by the home page state.</p><p>Products created through the form will join that same list. Search, category filters, product details, favorites, and the shopping cart will continue reading from one shared product collection.</p><pre>cd ~/offline_product_catalog<br><br>python3 &lt;&lt;&#39;PY&#39;<br>from pathlib import Path<br>import re<br><br>path = Path(&quot;lib/main.dart&quot;)<br>text = path.read_text(encoding=&quot;utf-8&quot;)<br><br>if &quot;class AddProductPage&quot; in text:<br>    raise SystemExit(<br>        &quot;AddProductPage already exists. The patch was not applied again.&quot;<br>    )<br><br><br>def replace_once(old, new, label):<br>    global text<br><br>    count = text.count(old)<br><br>    if count != 1:<br>        raise SystemExit(<br>            f&quot;{label}: expected exactly one match, but found {count}.&quot;<br>        )<br><br>    text = text.replace(old, new, 1)<br><br><br># 1. Add the imports required by selected image bytes and form input.<br>replace_once(<br>    &quot;import &#39;package:flutter/material.dart&#39;;&quot;,<br>    &quot;&quot;&quot;import &#39;dart:typed_data&#39;;<br><br>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:flutter/services.dart&#39;;<br>import &#39;package:image_picker/image_picker.dart&#39;;&quot;&quot;&quot;,<br>    &quot;Flutter imports&quot;,<br>)<br><br><br># 2. Allow Product to use either an asset path or selected image bytes.<br>replace_once(<br>    &quot;&quot;&quot;    required this.imagePath,<br>  });&quot;&quot;&quot;,<br>    &quot;&quot;&quot;    this.imagePath,<br>    this.imageBytes,<br>  });&quot;&quot;&quot;,<br>    &quot;Product image constructor&quot;,<br>)<br><br>replace_once(<br>    &quot;&quot;&quot;  final String imagePath;&quot;&quot;&quot;,<br>    &quot;&quot;&quot;  final String? imagePath;<br>  final Uint8List? imageBytes;&quot;&quot;&quot;,<br>    &quot;Product image fields&quot;,<br>)<br><br>if &quot;double get priceValue&quot; not in text:<br>    replace_once(<br>        &quot;&quot;&quot;  final Uint8List? imageBytes;&quot;&quot;&quot;,<br>        &quot;&quot;&quot;  final Uint8List? imageBytes;<br><br>  double get priceValue {<br>    return double.parse(price.replaceFirst(r&#39;$&#39;, &#39;&#39;));<br>  }&quot;&quot;&quot;,<br>        &quot;Product numeric price&quot;,<br>    )<br><br><br># 3. Keep the original products as the initial catalog.<br>replace_once(<br>    &quot;const products = [&quot;,<br>    &quot;const initialProducts = [&quot;,<br>    &quot;Initial product list&quot;,<br>)<br><br><br># 4. Add one image widget for asset and selected images.<br>#    Add the complete Add Product page before the initial product data.<br>product_tools = r&#39;&#39;&#39;<br>class ProductImage extends StatelessWidget {<br>  const ProductImage({<br>    super.key,<br>    required this.product,<br>    this.fit = BoxFit.contain,<br>  });<br><br>  final Product product;<br>  final BoxFit fit;<br><br>  @override<br>  Widget build(BuildContext context) {<br>    final selectedImage = product.imageBytes;<br><br>    if (selectedImage != null) {<br>      return Image.memory(<br>        selectedImage,<br>        fit: fit,<br>      );<br>    }<br><br>    final assetPath = product.imagePath;<br><br>    if (assetPath != null &amp;&amp; assetPath.isNotEmpty) {<br>      return Image.asset(<br>        assetPath,<br>        fit: fit,<br>      );<br>    }<br><br>    return Center(<br>      child: Icon(<br>        product.icon,<br>        size: 64,<br>        color: Colors.black38,<br>      ),<br>    );<br>  }<br>}<br><br>class AddProductPage extends StatefulWidget {<br>  const AddProductPage({<br>    super.key,<br>    required this.categories,<br>  });<br><br>  final List&lt;String&gt; categories;<br><br>  @override<br>  State&lt;AddProductPage&gt; createState() =&gt; _AddProductPageState();<br>}<br><br>class _AddProductPageState extends State&lt;AddProductPage&gt; {<br>  final GlobalKey&lt;FormState&gt; _formKey = GlobalKey&lt;FormState&gt;();<br><br>  final TextEditingController _nameController = TextEditingController();<br>  final TextEditingController _priceController = TextEditingController();<br>  final TextEditingController _descriptionController =<br>      TextEditingController();<br>  final TextEditingController _newCategoryController =<br>      TextEditingController();<br><br>  final ImagePicker _imagePicker = ImagePicker();<br><br>  Uint8List? _selectedImageBytes;<br>  String? _selectedCategory;<br>  String? _imageError;<br>  bool _isPickingImage = false;<br><br>  @override<br>  void initState() {<br>    super.initState();<br><br>    if (widget.categories.isNotEmpty) {<br>      _selectedCategory = widget.categories.first;<br>    }<br>  }<br><br>  @override<br>  void dispose() {<br>    _nameController.dispose();<br>    _priceController.dispose();<br>    _descriptionController.dispose();<br>    _newCategoryController.dispose();<br>    super.dispose();<br>  }<br><br>  Future&lt;void&gt; _pickImage(ImageSource source) async {<br>    setState(() {<br>      _isPickingImage = true;<br>      _imageError = null;<br>    });<br><br>    try {<br>      final selectedFile = await _imagePicker.pickImage(<br>        source: source,<br>        imageQuality: 85,<br>        maxWidth: 1600,<br>      );<br><br>      if (selectedFile == null) {<br>        return;<br>      }<br><br>      final bytes = await selectedFile.readAsBytes();<br><br>      if (!mounted) {<br>        return;<br>      }<br><br>      setState(() {<br>        _selectedImageBytes = bytes;<br>      });<br>    } catch (_) {<br>      if (!mounted) {<br>        return;<br>      }<br><br>      ScaffoldMessenger.of(context)<br>        ..hideCurrentSnackBar()<br>        ..showSnackBar(<br>          const SnackBar(<br>            content: Text(<br>              &#39;The image could not be selected. Please try again.&#39;,<br>            ),<br>          ),<br>        );<br>    } finally {<br>      if (mounted) {<br>        setState(() {<br>          _isPickingImage = false;<br>        });<br>      }<br>    }<br>  }<br><br>  void _saveProduct() {<br>    final formIsValid = _formKey.currentState?.validate() ?? false;<br>    final imageIsAvailable = _selectedImageBytes != null;<br><br>    setState(() {<br>      _imageError = imageIsAvailable<br>          ? null<br>          : &#39;Choose a product image before saving.&#39;;<br>    });<br><br>    if (!formIsValid || !imageIsAvailable) {<br>      return;<br>    }<br><br>    final numericPrice = double.parse(<br>      _priceController.text.trim(),<br>    );<br><br>    final customCategory = _newCategoryController.text.trim();<br><br>    final category = customCategory.isNotEmpty<br>        ? customCategory<br>        : _selectedCategory!;<br><br>    final product = Product(<br>      name: _nameController.text.trim(),<br>      description: _descriptionController.text.trim(),<br>      price: &#39;\$${numericPrice.toStringAsFixed(2)}&#39;,<br>      icon: Icons.inventory_2_outlined,<br>      category: category,<br>      imageBytes: _selectedImageBytes,<br>    );<br><br>    Navigator.of(context).pop(product);<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(<br>        backgroundColor: Theme.of(context).colorScheme.inversePrimary,<br>        title: const Text(&#39;Add Product&#39;),<br>      ),<br>      body: SingleChildScrollView(<br>        padding: const EdgeInsets.all(20),<br>        child: Center(<br>          child: ConstrainedBox(<br>            constraints: const BoxConstraints(maxWidth: 720),<br>            child: Form(<br>              key: _formKey,<br>              child: Column(<br>                crossAxisAlignment: CrossAxisAlignment.stretch,<br>                children: [<br>                  const Text(<br>                    &#39;Create a New Product&#39;,<br>                    style: TextStyle(<br>                      fontSize: 28,<br>                      fontWeight: FontWeight.bold,<br>                    ),<br>                  ),<br>                  const SizedBox(height: 6),<br>                  const Text(<br>                    &#39;Add a photo and the basic information needed by the catalog.&#39;,<br>                    style: TextStyle(<br>                      fontSize: 16,<br>                      color: Colors.black54,<br>                    ),<br>                  ),<br>                  const SizedBox(height: 24),<br>                  Container(<br>                    height: 260,<br>                    decoration: BoxDecoration(<br>                      color: const Color(0xFFF7F5FA),<br>                      borderRadius: BorderRadius.circular(18),<br>                      border: Border.all(<br>                        color: _imageError == null<br>                            ? Colors.black12<br>                            : Theme.of(context).colorScheme.error,<br>                      ),<br>                    ),<br>                    child: _selectedImageBytes == null<br>                        ? const Column(<br>                            mainAxisAlignment: MainAxisAlignment.center,<br>                            children: [<br>                              Icon(<br>                                Icons.add_photo_alternate_outlined,<br>                                size: 70,<br>                                color: Colors.black38,<br>                              ),<br>                              SizedBox(height: 12),<br>                              Text(<br>                                &#39;No product image selected&#39;,<br>                                style: TextStyle(<br>                                  color: Colors.black54,<br>                                  fontWeight: FontWeight.w600,<br>                                ),<br>                              ),<br>                            ],<br>                          )<br>                        : ClipRRect(<br>                            borderRadius: BorderRadius.circular(18),<br>                            child: Image.memory(<br>                              _selectedImageBytes!,<br>                              fit: BoxFit.contain,<br>                              width: double.infinity,<br>                            ),<br>                          ),<br>                  ),<br>                  if (_imageError != null) ...[<br>                    const SizedBox(height: 8),<br>                    Text(<br>                      _imageError!,<br>                      style: TextStyle(<br>                        color: Theme.of(context).colorScheme.error,<br>                      ),<br>                    ),<br>                  ],<br>                  const SizedBox(height: 14),<br>                  Wrap(<br>                    spacing: 12,<br>                    runSpacing: 10,<br>                    children: [<br>                      OutlinedButton.icon(<br>                        onPressed: _isPickingImage<br>                            ? null<br>                            : () {<br>                                _pickImage(ImageSource.gallery);<br>                              },<br>                        icon: const Icon(Icons.photo_library_outlined),<br>                        label: const Text(&#39;Choose Image&#39;),<br>                      ),<br>                      OutlinedButton.icon(<br>                        onPressed: _isPickingImage<br>                            ? null<br>                            : () {<br>                                _pickImage(ImageSource.camera);<br>                              },<br>                        icon: const Icon(Icons.camera_alt_outlined),<br>                        label: const Text(&#39;Take Photo&#39;),<br>                      ),<br>                      if (_isPickingImage)<br>                        const Padding(<br>                          padding: EdgeInsets.all(10),<br>                          child: SizedBox(<br>                            width: 22,<br>                            height: 22,<br>                            child: CircularProgressIndicator(<br>                              strokeWidth: 2,<br>                            ),<br>                          ),<br>                        ),<br>                    ],<br>                  ),<br>                  const SizedBox(height: 24),<br>                  TextFormField(<br>                    controller: _nameController,<br>                    textInputAction: TextInputAction.next,<br>                    decoration: const InputDecoration(<br>                      labelText: &#39;Product Name&#39;,<br>                      hintText: &#39;Wireless Keyboard&#39;,<br>                      prefixIcon: Icon(Icons.inventory_2_outlined),<br>                      border: OutlineInputBorder(),<br>                    ),<br>                    validator: (value) {<br>                      if (value == null || value.trim().isEmpty) {<br>                        return &#39;Enter a product name.&#39;;<br>                      }<br><br>                      return null;<br>                    },<br>                  ),<br>                  const SizedBox(height: 16),<br>                  TextFormField(<br>                    controller: _priceController,<br>                    keyboardType: const TextInputType.numberWithOptions(<br>                      decimal: true,<br>                    ),<br>                    inputFormatters: [<br>                      FilteringTextInputFormatter.allow(<br>                        RegExp(r&#39;^\d*\.?\d{0,2}&#39;),<br>                      ),<br>                    ],<br>                    decoration: const InputDecoration(<br>                      labelText: &#39;Price&#39;,<br>                      hintText: &#39;49.00&#39;,<br>                      prefixText: &#39;\$ &#39;,<br>                      prefixIcon: Icon(Icons.attach_money),<br>                      border: OutlineInputBorder(),<br>                    ),<br>                    validator: (value) {<br>                      final price = double.tryParse(<br>                        value?.trim() ?? &#39;&#39;,<br>                      );<br><br>                      if (price == null || price &lt;= 0) {<br>                        return &#39;Enter a valid price greater than zero.&#39;;<br>                      }<br><br>                      return null;<br>                    },<br>                  ),<br>                  const SizedBox(height: 16),<br>                  DropdownButtonFormField&lt;String&gt;(<br>                    initialValue: _selectedCategory,<br>                    decoration: const InputDecoration(<br>                      labelText: &#39;Existing Category&#39;,<br>                      prefixIcon: Icon(Icons.category_outlined),<br>                      border: OutlineInputBorder(),<br>                    ),<br>                    items: widget.categories.map((category) {<br>                      return DropdownMenuItem&lt;String&gt;(<br>                        value: category,<br>                        child: Text(category),<br>                      );<br>                    }).toList(),<br>                    onChanged: (value) {<br>                      setState(() {<br>                        _selectedCategory = value;<br>                      });<br>                    },<br>                    validator: (value) {<br>                      final customCategory =<br>                          _newCategoryController.text.trim();<br><br>                      if ((value == null || value.isEmpty) &amp;&amp;<br>                          customCategory.isEmpty) {<br>                        return &#39;Choose or create a category.&#39;;<br>                      }<br><br>                      return null;<br>                    },<br>                  ),<br>                  const SizedBox(height: 12),<br>                  TextFormField(<br>                    controller: _newCategoryController,<br>                    textInputAction: TextInputAction.next,<br>                    decoration: const InputDecoration(<br>                      labelText: &#39;New Category (Optional)&#39;,<br>                      hintText: &#39;Home Office&#39;,<br>                      prefixIcon: Icon(Icons.create_new_folder_outlined),<br>                      helperText:<br>                          &#39;A new category replaces the selection above.&#39;,<br>                      border: OutlineInputBorder(),<br>                    ),<br>                  ),<br>                  const SizedBox(height: 16),<br>                  TextFormField(<br>                    controller: _descriptionController,<br>                    minLines: 3,<br>                    maxLines: 5,<br>                    decoration: const InputDecoration(<br>                      labelText: &#39;Description&#39;,<br>                      hintText:<br>                          &#39;Write a short description of the product.&#39;,<br>                      alignLabelWithHint: true,<br>                      prefixIcon: Icon(Icons.notes),<br>                      border: OutlineInputBorder(),<br>                    ),<br>                    validator: (value) {<br>                      if (value == null || value.trim().isEmpty) {<br>                        return &#39;Enter a product description.&#39;;<br>                      }<br><br>                      return null;<br>                    },<br>                  ),<br>                  const SizedBox(height: 24),<br>                  FilledButton.icon(<br>                    onPressed: _saveProduct,<br>                    icon: const Icon(Icons.save_outlined),<br>                    label: const Text(&#39;Save Product&#39;),<br>                  ),<br>                ],<br>              ),<br>            ),<br>          ),<br>        ),<br>      ),<br>    );<br>  }<br>}<br><br>&#39;&#39;&#39;<br><br>replace_once(<br>    &quot;const initialProducts = [&quot;,<br>    product_tools + &quot;const initialProducts = [&quot;,<br>    &quot;Product tools and form&quot;,<br>)<br><br><br># 5. Create one editable product collection in the home page state.<br>replace_once(<br>    &quot;&quot;&quot;  final Set&lt;String&gt; _favoriteProductNames = {};&quot;&quot;&quot;,<br>    &quot;&quot;&quot;  late final List&lt;Product&gt; _products;<br><br>  final Set&lt;String&gt; _favoriteProductNames = {};&quot;&quot;&quot;,<br>    &quot;Editable product state&quot;,<br>)<br><br>replace_once(<br>    &quot;&quot;&quot;  bool _isFavorite(Product product) {&quot;&quot;&quot;,<br>    &quot;&quot;&quot;  @override<br>  void initState() {<br>    super.initState();<br>    _products = List&lt;Product&gt;.of(initialProducts);<br>  }<br><br>  bool _isFavorite(Product product) {&quot;&quot;&quot;,<br>    &quot;Editable product initialization&quot;,<br>)<br><br><br># 6. Open the form and add the returned product to the shared list.<br>open_add_product_method = r&#39;&#39;&#39;<br>  Future&lt;void&gt; _openAddProductPage() async {<br>    final categories = _products<br>        .map((product) =&gt; product.category)<br>        .toSet()<br>        .toList()<br>      ..sort();<br><br>    final product = await Navigator.of(context).push&lt;Product&gt;(<br>      MaterialPageRoute(<br>        builder: (context) =&gt; AddProductPage(<br>          categories: categories,<br>        ),<br>      ),<br>    );<br><br>    if (!mounted || product == null) {<br>      return;<br>    }<br><br>    setState(() {<br>      _products.add(product);<br>      _selectedCategory = &#39;All&#39;;<br>      _selectedTab = 0;<br>    });<br><br>    ScaffoldMessenger.of(context)<br>      ..hideCurrentSnackBar()<br>      ..showSnackBar(<br>        SnackBar(<br>          content: Text(&#39;${product.name} added to the catalog.&#39;),<br>          action: SnackBarAction(<br>            label: &#39;View&#39;,<br>            onPressed: () {<br>              _openProductDetail(product);<br>            },<br>          ),<br>        ),<br>      );<br>  }<br><br>&#39;&#39;&#39;<br><br>replace_once(<br>    &quot;&quot;&quot;  void _openProductDetail(Product product) {&quot;&quot;&quot;,<br>    open_add_product_method + &quot;  void _openProductDetail(Product product) {&quot;,<br>    &quot;Open Add Product page&quot;,<br>)<br><br><br># 7. Make catalog and favorites read from the editable collection.<br>product_reference_count = text.count(&quot;products.where&quot;)<br><br>if product_reference_count &lt; 1:<br>    raise SystemExit(<br>        &quot;No direct products.where reference was found.&quot;<br>    )<br><br>text = text.replace(<br>    &quot;products.where&quot;,<br>    &quot;_products.where&quot;,<br>)<br><br><br># 8. Generate category filters from the current catalog.<br>replace_once(<br>    &quot;&quot;&quot;    const categories = [<br>      &#39;All&#39;,<br>      &#39;Audio&#39;,<br>      &#39;Wearables&#39;,<br>      &#39;Photography&#39;,<br>      &#39;Computers&#39;,<br>      &#39;Accessories&#39;,<br>    ];&quot;&quot;&quot;,<br>    &quot;&quot;&quot;    final categories = &lt;String&gt;[<br>      &#39;All&#39;,<br>      ..._products.map((product) =&gt; product.category).toSet(),<br>    ];&quot;&quot;&quot;,<br>    &quot;Dynamic category filters&quot;,<br>)<br><br><br># 9. Add a visible Add Product action to the Catalog page.<br>replace_once(<br>    &quot;&quot;&quot;              const Text(<br>                &#39;Browse products available offline.&#39;,<br>                style: TextStyle(fontSize: 16),<br>              ),<br>              const SizedBox(height: 20),&quot;&quot;&quot;,<br>    &quot;&quot;&quot;              const Text(<br>                &#39;Browse products available offline.&#39;,<br>                style: TextStyle(fontSize: 16),<br>              ),<br>              const SizedBox(height: 14),<br>              Align(<br>                alignment: Alignment.centerLeft,<br>                child: FilledButton.icon(<br>                  onPressed: _openAddProductPage,<br>                  icon: const Icon(Icons.add),<br>                  label: const Text(&#39;Add Product&#39;),<br>                ),<br>              ),<br>              const SizedBox(height: 20),&quot;&quot;&quot;,<br>    &quot;Catalog Add Product button&quot;,<br>)<br><br><br># 10. Replace direct asset rendering with the shared ProductImage widget.<br>image_pattern = re.compile(<br>    r&quot;&quot;&quot;Image\.asset\(<br>        \s*product\.imagePath,<br>        \s*fit:\s*(BoxFit\.\w+),<br>        \s*\)&quot;&quot;&quot;,<br>    re.VERBOSE,<br>)<br><br>text, image_count = image_pattern.subn(<br>    lambda match: (<br>        &quot;ProductImage(&quot;<br>        &quot;product: product, &quot;<br>        f&quot;fit: {match.group(1)}&quot;<br>        &quot;)&quot;<br>    ),<br>    text,<br>)<br><br>if image_count &lt; 2:<br>    raise SystemExit(<br>        f&quot;Expected at least two product images, but replaced {image_count}.&quot;<br>    )<br><br><br>path.write_text(text, encoding=&quot;utf-8&quot;)<br><br>print(&quot;Episode 22 Add Product patch applied successfully.&quot;)<br>print(f&quot;Editable references updated: {product_reference_count}&quot;)<br>print(f&quot;Product image widgets updated: {image_count}&quot;)<br>print(&quot;Updated file:&quot;, path)<br>PY<br><br>dart format lib/main.dart</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*hR3R2_cqCPLubMrmvvrPEg.png" /><figcaption>Building the editable catalog, product image flow, and Add Product form in one connected patch.</figcaption></figure><p>The first Add Product patch stopped before writing any changes to `main.dart`.</p><p>Its safety check expected at least two matching product image widgets, but the current file contains different formatting patterns. Instead of partially modifying the application, the script ended and left the working Episode 21 code unchanged.</p><p>I will inspect the exact image widgets and adjust the patch to the source code that actually exists.</p><pre>cd ~/offline_product_catalog<br><br>printf &#39;\n=== PATCH STATUS ===\n&#39;<br>grep -nE \<br>&quot;class AddProductPage|class ProductImage|dart:typed_data|package:image_picker|initialProducts|final List&lt;Product&gt; _products&quot; \<br>lib/main.dart || true<br><br>printf &#39;\n=== CURRENT FILE STATUS ===\n&#39;<br>grep -nE \<br>&quot;^import |^class Product|^const products|^const initialProducts&quot; \<br>lib/main.dart</pre><pre>cd ~/offline_product_catalog<br><br>python3 &lt;&lt;&#39;PY&#39;<br>from pathlib import Path<br><br>path = Path(&quot;lib/main.dart&quot;)<br>lines = path.read_text(encoding=&quot;utf-8&quot;).splitlines()<br><br>matches = [<br>    index<br>    for index, line in enumerate(lines)<br>    if &quot;Image.asset&quot; in line or &quot;product.imagePath&quot; in line<br>]<br><br>print(&quot;\n=== PRODUCT IMAGE LOCATIONS ===&quot;)<br><br>if not matches:<br>    print(&quot;No Image.asset or product.imagePath references were found.&quot;)<br>else:<br>    shown_ranges = []<br><br>    for match in matches:<br>        start = max(0, match - 6)<br>        end = min(len(lines), match + 10)<br><br>        if any(<br>            start &gt;= previous_start and end &lt;= previous_end<br>            for previous_start, previous_end in shown_ranges<br>        ):<br>            continue<br><br>        shown_ranges.append((start, end))<br><br>        print(f&quot;\n--- Around line {match + 1} ---&quot;)<br><br>        for index in range(start, end):<br>            print(f&quot;{index + 1:5}  {lines[index]}&quot;)<br>PY</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*5--UIxL_49pK9Zeh-ky1uw.png" /><figcaption>Confirming that the failed patch left the source unchanged and locating every product image pattern.</figcaption></figure><p>The first patch stopped before changing the source file because the product images were not all written in the same format.</p><p>I am revising the implementation so it can recognize both single-line and multi-line Image.asset widgets. The new patch will also verify that no direct product image reference is left behind before it writes anything to main.dart.</p><pre>cd ~/offline_product_catalog<br><br>backup_file=&quot;lib/main.dart.episode22_before_add_product_$(date +%Y%m%d_%H%M%S)&quot;<br>cp lib/main.dart &quot;$backup_file&quot;<br><br>printf &#39;\n=== EPISODE 22 BACKUP ===\n&#39;<br>printf &#39;%s\n&#39; &quot;$backup_file&quot;<br><br>python3 &lt;&lt;&#39;PY&#39;<br>from pathlib import Path<br>import re<br><br>path = Path(&quot;lib/main.dart&quot;)<br>text = path.read_text(encoding=&quot;utf-8&quot;)<br><br>if &quot;class AddProductPage&quot; in text:<br>    raise SystemExit(<br>        &quot;AddProductPage already exists. The patch was not applied again.&quot;<br>    )<br><br><br>def replace_once(old: str, new: str, label: str) -&gt; None:<br>    global text<br><br>    count = text.count(old)<br><br>    if count != 1:<br>        raise SystemExit(<br>            f&quot;{label}: expected exactly one match, but found {count}.&quot;<br>        )<br><br>    text = text.replace(old, new, 1)<br><br><br># 1. Add imports for image bytes, input validation, and image selection.<br>replace_once(<br>    &quot;import &#39;package:flutter/material.dart&#39;;&quot;,<br>    &quot;&quot;&quot;import &#39;dart:typed_data&#39;;<br><br>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:flutter/services.dart&#39;;<br>import &#39;package:image_picker/image_picker.dart&#39;;&quot;&quot;&quot;,<br>    &quot;Flutter imports&quot;,<br>)<br><br><br># 2. Let Product use either an asset path or selected image bytes.<br>replace_once(<br>    &quot;&quot;&quot;    required this.imagePath,<br>  });&quot;&quot;&quot;,<br>    &quot;&quot;&quot;    this.imagePath,<br>    this.imageBytes,<br>  });&quot;&quot;&quot;,<br>    &quot;Product image constructor&quot;,<br>)<br><br>replace_once(<br>    &quot;&quot;&quot;  final String imagePath;&quot;&quot;&quot;,<br>    &quot;&quot;&quot;  final String? imagePath;<br>  final Uint8List? imageBytes;&quot;&quot;&quot;,<br>    &quot;Product image fields&quot;,<br>)<br><br>if &quot;double get priceValue&quot; not in text:<br>    replace_once(<br>        &quot;&quot;&quot;  final Uint8List? imageBytes;&quot;&quot;&quot;,<br>        &quot;&quot;&quot;  final Uint8List? imageBytes;<br><br>  double get priceValue {<br>    return double.parse(price.replaceFirst(r&#39;$&#39;, &#39;&#39;));<br>  }&quot;&quot;&quot;,<br>        &quot;Numeric product price&quot;,<br>    )<br><br><br># 3. Preserve the original twenty products as initial catalog data.<br>replace_once(<br>    &quot;const products = [&quot;,<br>    &quot;const initialProducts = [&quot;,<br>    &quot;Initial product list&quot;,<br>)<br><br><br># 4. Add one image widget and the complete Add Product form.<br>product_management_widgets = r&#39;&#39;&#39;<br>class ProductImage extends StatelessWidget {<br>  const ProductImage({<br>    super.key,<br>    required this.product,<br>    this.fit = BoxFit.contain,<br>  });<br><br>  final Product product;<br>  final BoxFit fit;<br><br>  @override<br>  Widget build(BuildContext context) {<br>    final selectedImage = product.imageBytes;<br><br>    if (selectedImage != null) {<br>      return Image.memory(<br>        selectedImage,<br>        fit: fit,<br>      );<br>    }<br><br>    final assetPath = product.imagePath;<br><br>    if (assetPath != null &amp;&amp; assetPath.isNotEmpty) {<br>      return Image.asset(<br>        assetPath,<br>        fit: fit,<br>      );<br>    }<br><br>    return Center(<br>      child: Icon(<br>        product.icon,<br>        size: 64,<br>        color: Colors.black38,<br>      ),<br>    );<br>  }<br>}<br><br>class AddProductPage extends StatefulWidget {<br>  const AddProductPage({<br>    super.key,<br>    required this.categories,<br>    required this.existingProductNames,<br>  });<br><br>  final List&lt;String&gt; categories;<br>  final Set&lt;String&gt; existingProductNames;<br><br>  @override<br>  State&lt;AddProductPage&gt; createState() =&gt; _AddProductPageState();<br>}<br><br>class _AddProductPageState extends State&lt;AddProductPage&gt; {<br>  final GlobalKey&lt;FormState&gt; _formKey = GlobalKey&lt;FormState&gt;();<br><br>  final TextEditingController _nameController = TextEditingController();<br>  final TextEditingController _priceController = TextEditingController();<br>  final TextEditingController _descriptionController =<br>      TextEditingController();<br>  final TextEditingController _newCategoryController =<br>      TextEditingController();<br><br>  final ImagePicker _imagePicker = ImagePicker();<br><br>  Uint8List? _selectedImageBytes;<br>  String? _selectedCategory;<br>  String? _imageError;<br>  bool _isPickingImage = false;<br><br>  @override<br>  void initState() {<br>    super.initState();<br><br>    if (widget.categories.isNotEmpty) {<br>      _selectedCategory = widget.categories.first;<br>    }<br>  }<br><br>  @override<br>  void dispose() {<br>    _nameController.dispose();<br>    _priceController.dispose();<br>    _descriptionController.dispose();<br>    _newCategoryController.dispose();<br>    super.dispose();<br>  }<br><br>  Future&lt;void&gt; _pickImage(ImageSource source) async {<br>    setState(() {<br>      _isPickingImage = true;<br>      _imageError = null;<br>    });<br><br>    try {<br>      final selectedFile = await _imagePicker.pickImage(<br>        source: source,<br>        imageQuality: 85,<br>        maxWidth: 1600,<br>      );<br><br>      if (selectedFile == null) {<br>        return;<br>      }<br><br>      final bytes = await selectedFile.readAsBytes();<br><br>      if (!mounted) {<br>        return;<br>      }<br><br>      setState(() {<br>        _selectedImageBytes = bytes;<br>      });<br>    } catch (_) {<br>      if (!mounted) {<br>        return;<br>      }<br><br>      ScaffoldMessenger.of(context)<br>        ..hideCurrentSnackBar()<br>        ..showSnackBar(<br>          const SnackBar(<br>            content: Text(<br>              &#39;The image could not be selected. Please try again.&#39;,<br>            ),<br>          ),<br>        );<br>    } finally {<br>      if (mounted) {<br>        setState(() {<br>          _isPickingImage = false;<br>        });<br>      }<br>    }<br>  }<br><br>  void _saveProduct() {<br>    final formIsValid = _formKey.currentState?.validate() ?? false;<br>    final imageIsAvailable = _selectedImageBytes != null;<br><br>    setState(() {<br>      _imageError = imageIsAvailable<br>          ? null<br>          : &#39;Choose a product image before saving.&#39;;<br>    });<br><br>    if (!formIsValid || !imageIsAvailable) {<br>      return;<br>    }<br><br>    final numericPrice = double.parse(<br>      _priceController.text.trim(),<br>    );<br><br>    final customCategory = _newCategoryController.text.trim();<br><br>    final category = customCategory.isNotEmpty<br>        ? customCategory<br>        : _selectedCategory!;<br><br>    final product = Product(<br>      name: _nameController.text.trim(),<br>      description: _descriptionController.text.trim(),<br>      price: &#39;\$${numericPrice.toStringAsFixed(2)}&#39;,<br>      icon: Icons.inventory_2_outlined,<br>      category: category,<br>      imageBytes: _selectedImageBytes,<br>    );<br><br>    Navigator.of(context).pop(product);<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(<br>        backgroundColor: Theme.of(context).colorScheme.inversePrimary,<br>        title: const Text(&#39;Add Product&#39;),<br>      ),<br>      body: SingleChildScrollView(<br>        padding: const EdgeInsets.all(20),<br>        child: Center(<br>          child: ConstrainedBox(<br>            constraints: const BoxConstraints(maxWidth: 720),<br>            child: Form(<br>              key: _formKey,<br>              child: Column(<br>                crossAxisAlignment: CrossAxisAlignment.stretch,<br>                children: [<br>                  const Text(<br>                    &#39;Create a New Product&#39;,<br>                    style: TextStyle(<br>                      fontSize: 28,<br>                      fontWeight: FontWeight.bold,<br>                    ),<br>                  ),<br>                  const SizedBox(height: 6),<br>                  const Text(<br>                    &#39;Add a photo and the basic information needed by the catalog.&#39;,<br>                    style: TextStyle(<br>                      fontSize: 16,<br>                      color: Colors.black54,<br>                    ),<br>                  ),<br>                  const SizedBox(height: 24),<br>                  Container(<br>                    height: 260,<br>                    decoration: BoxDecoration(<br>                      color: const Color(0xFFF7F5FA),<br>                      borderRadius: BorderRadius.circular(18),<br>                      border: Border.all(<br>                        color: _imageError == null<br>                            ? Colors.black12<br>                            : Theme.of(context).colorScheme.error,<br>                      ),<br>                    ),<br>                    child: _selectedImageBytes == null<br>                        ? const Column(<br>                            mainAxisAlignment: MainAxisAlignment.center,<br>                            children: [<br>                              Icon(<br>                                Icons.add_photo_alternate_outlined,<br>                                size: 70,<br>                                color: Colors.black38,<br>                              ),<br>                              SizedBox(height: 12),<br>                              Text(<br>                                &#39;No product image selected&#39;,<br>                                style: TextStyle(<br>                                  color: Colors.black54,<br>                                  fontWeight: FontWeight.w600,<br>                                ),<br>                              ),<br>                            ],<br>                          )<br>                        : ClipRRect(<br>                            borderRadius: BorderRadius.circular(18),<br>                            child: Image.memory(<br>                              _selectedImageBytes!,<br>                              width: double.infinity,<br>                              fit: BoxFit.contain,<br>                            ),<br>                          ),<br>                  ),<br>                  if (_imageError != null) ...[<br>                    const SizedBox(height: 8),<br>                    Text(<br>                      _imageError!,<br>                      style: TextStyle(<br>                        color: Theme.of(context).colorScheme.error,<br>                      ),<br>                    ),<br>                  ],<br>                  const SizedBox(height: 14),<br>                  Wrap(<br>                    spacing: 12,<br>                    runSpacing: 10,<br>                    children: [<br>                      OutlinedButton.icon(<br>                        onPressed: _isPickingImage<br>                            ? null<br>                            : () {<br>                                _pickImage(ImageSource.gallery);<br>                              },<br>                        icon: const Icon(Icons.photo_library_outlined),<br>                        label: const Text(&#39;Choose Image&#39;),<br>                      ),<br>                      OutlinedButton.icon(<br>                        onPressed: _isPickingImage<br>                            ? null<br>                            : () {<br>                                _pickImage(ImageSource.camera);<br>                              },<br>                        icon: const Icon(Icons.camera_alt_outlined),<br>                        label: const Text(&#39;Take Photo&#39;),<br>                      ),<br>                      if (_isPickingImage)<br>                        const Padding(<br>                          padding: EdgeInsets.all(10),<br>                          child: SizedBox(<br>                            width: 22,<br>                            height: 22,<br>                            child: CircularProgressIndicator(<br>                              strokeWidth: 2,<br>                            ),<br>                          ),<br>                        ),<br>                    ],<br>                  ),<br>                  const SizedBox(height: 24),<br>                  TextFormField(<br>                    controller: _nameController,<br>                    textInputAction: TextInputAction.next,<br>                    decoration: const InputDecoration(<br>                      labelText: &#39;Product Name&#39;,<br>                      hintText: &#39;Wireless Keyboard&#39;,<br>                      prefixIcon: Icon(Icons.inventory_2_outlined),<br>                      border: OutlineInputBorder(),<br>                    ),<br>                    validator: (value) {<br>                      final name = value?.trim() ?? &#39;&#39;;<br><br>                      if (name.isEmpty) {<br>                        return &#39;Enter a product name.&#39;;<br>                      }<br><br>                      if (widget.existingProductNames.contains(<br>                        name.toLowerCase(),<br>                      )) {<br>                        return &#39;A product with this name already exists.&#39;;<br>                      }<br><br>                      return null;<br>                    },<br>                  ),<br>                  const SizedBox(height: 16),<br>                  TextFormField(<br>                    controller: _priceController,<br>                    keyboardType: const TextInputType.numberWithOptions(<br>                      decimal: true,<br>                    ),<br>                    inputFormatters: [<br>                      FilteringTextInputFormatter.allow(<br>                        RegExp(r&#39;[0-9.]&#39;),<br>                      ),<br>                    ],<br>                    decoration: const InputDecoration(<br>                      labelText: &#39;Price&#39;,<br>                      hintText: &#39;49.00&#39;,<br>                      prefixText: &#39;\$ &#39;,<br>                      prefixIcon: Icon(Icons.attach_money),<br>                      border: OutlineInputBorder(),<br>                    ),<br>                    validator: (value) {<br>                      final price = double.tryParse(<br>                        value?.trim() ?? &#39;&#39;,<br>                      );<br><br>                      if (price == null || price &lt;= 0) {<br>                        return &#39;Enter a valid price greater than zero.&#39;;<br>                      }<br><br>                      return null;<br>                    },<br>                  ),<br>                  const SizedBox(height: 16),<br>                  DropdownButtonFormField&lt;String&gt;(<br>                    initialValue: _selectedCategory,<br>                    decoration: const InputDecoration(<br>                      labelText: &#39;Existing Category&#39;,<br>                      prefixIcon: Icon(Icons.category_outlined),<br>                      border: OutlineInputBorder(),<br>                    ),<br>                    items: widget.categories.map((category) {<br>                      return DropdownMenuItem&lt;String&gt;(<br>                        value: category,<br>                        child: Text(category),<br>                      );<br>                    }).toList(),<br>                    onChanged: (value) {<br>                      setState(() {<br>                        _selectedCategory = value;<br>                      });<br>                    },<br>                    validator: (value) {<br>                      final customCategory =<br>                          _newCategoryController.text.trim();<br><br>                      if ((value == null || value.isEmpty) &amp;&amp;<br>                          customCategory.isEmpty) {<br>                        return &#39;Choose or create a category.&#39;;<br>                      }<br><br>                      return null;<br>                    },<br>                  ),<br>                  const SizedBox(height: 12),<br>                  TextFormField(<br>                    controller: _newCategoryController,<br>                    textInputAction: TextInputAction.next,<br>                    decoration: const InputDecoration(<br>                      labelText: &#39;New Category (Optional)&#39;,<br>                      hintText: &#39;Home Office&#39;,<br>                      prefixIcon: Icon(<br>                        Icons.create_new_folder_outlined,<br>                      ),<br>                      helperText:<br>                          &#39;A new category replaces the selection above.&#39;,<br>                      border: OutlineInputBorder(),<br>                    ),<br>                  ),<br>                  const SizedBox(height: 16),<br>                  TextFormField(<br>                    controller: _descriptionController,<br>                    minLines: 3,<br>                    maxLines: 5,<br>                    decoration: const InputDecoration(<br>                      labelText: &#39;Description&#39;,<br>                      hintText:<br>                          &#39;Write a short description of the product.&#39;,<br>                      alignLabelWithHint: true,<br>                      prefixIcon: Icon(Icons.notes),<br>                      border: OutlineInputBorder(),<br>                    ),<br>                    validator: (value) {<br>                      if (value == null || value.trim().isEmpty) {<br>                        return &#39;Enter a product description.&#39;;<br>                      }<br><br>                      return null;<br>                    },<br>                  ),<br>                  const SizedBox(height: 24),<br>                  FilledButton.icon(<br>                    onPressed: _saveProduct,<br>                    icon: const Icon(Icons.save_outlined),<br>                    label: const Text(&#39;Save Product&#39;),<br>                  ),<br>                ],<br>              ),<br>            ),<br>          ),<br>        ),<br>      ),<br>    );<br>  }<br>}<br><br>&#39;&#39;&#39;<br><br>replace_once(<br>    &quot;const initialProducts = [&quot;,<br>    product_management_widgets + &quot;const initialProducts = [&quot;,<br>    &quot;Product management widgets&quot;,<br>)<br><br><br># 5. Create one editable product list in the shared home state.<br>replace_once(<br>    &quot;&quot;&quot;  final Set&lt;String&gt; _favoriteProductNames = {};&quot;&quot;&quot;,<br>    &quot;&quot;&quot;  late final List&lt;Product&gt; _products;<br><br>  final Set&lt;String&gt; _favoriteProductNames = {};&quot;&quot;&quot;,<br>    &quot;Editable product state&quot;,<br>)<br><br>replace_once(<br>    &quot;&quot;&quot;  bool _isFavorite(Product product) {&quot;&quot;&quot;,<br>    &quot;&quot;&quot;  @override<br>  void initState() {<br>    super.initState();<br>    _products = List&lt;Product&gt;.of(initialProducts);<br>  }<br><br>  bool _isFavorite(Product product) {&quot;&quot;&quot;,<br>    &quot;Editable product initialization&quot;,<br>)<br><br><br># 6. Open the form and receive the newly created product.<br>open_add_product_method = r&#39;&#39;&#39;<br>  Future&lt;void&gt; _openAddProductPage() async {<br>    final categories = _products<br>        .map((product) =&gt; product.category)<br>        .toSet()<br>        .toList()<br>      ..sort();<br><br>    final existingProductNames = _products<br>        .map((product) =&gt; product.name.trim().toLowerCase())<br>        .toSet();<br><br>    final product = await Navigator.of(context).push&lt;Product&gt;(<br>      MaterialPageRoute(<br>        builder: (context) =&gt; AddProductPage(<br>          categories: categories,<br>          existingProductNames: existingProductNames,<br>        ),<br>      ),<br>    );<br><br>    if (!mounted || product == null) {<br>      return;<br>    }<br><br>    setState(() {<br>      _products.add(product);<br>      _selectedCategory = &#39;All&#39;;<br>      _selectedTab = 0;<br>    });<br><br>    ScaffoldMessenger.of(context)<br>      ..hideCurrentSnackBar()<br>      ..showSnackBar(<br>        SnackBar(<br>          content: Text(&#39;${product.name} added to the catalog.&#39;),<br>          action: SnackBarAction(<br>            label: &#39;View&#39;,<br>            onPressed: () {<br>              _openProductDetail(product);<br>            },<br>          ),<br>        ),<br>      );<br>  }<br><br>&#39;&#39;&#39;<br><br>replace_once(<br>    &quot;&quot;&quot;  void _openProductDetail(Product product) {&quot;&quot;&quot;,<br>    open_add_product_method + &quot;  void _openProductDetail(Product product) {&quot;,<br>    &quot;Open Add Product page&quot;,<br>)<br><br><br># 7. Make Catalog and Favorites read from the editable list.<br>reference_count = text.count(&quot;products.where&quot;)<br><br>if reference_count == 0:<br>    raise SystemExit(<br>        &quot;No products.where reference was found.&quot;<br>    )<br><br>text = text.replace(<br>    &quot;products.where&quot;,<br>    &quot;_products.where&quot;,<br>)<br><br><br># 8. Generate categories from the current catalog.<br>replace_once(<br>    &quot;&quot;&quot;    const categories = [<br>      &#39;All&#39;,<br>      &#39;Audio&#39;,<br>      &#39;Wearables&#39;,<br>      &#39;Photography&#39;,<br>      &#39;Computers&#39;,<br>      &#39;Accessories&#39;,<br>    ];&quot;&quot;&quot;,<br>    &quot;&quot;&quot;    final categories = &lt;String&gt;[<br>      &#39;All&#39;,<br>      ..._products.map((product) =&gt; product.category).toSet(),<br>    ];&quot;&quot;&quot;,<br>    &quot;Dynamic category filters&quot;,<br>)<br><br><br># 9. Add the Add Product button to the Catalog page.<br>replace_once(<br>    &quot;&quot;&quot;              const Text(<br>                &#39;Browse products available offline.&#39;,<br>                style: TextStyle(fontSize: 16),<br>              ),<br>              const SizedBox(height: 20),&quot;&quot;&quot;,<br>    &quot;&quot;&quot;              const Text(<br>                &#39;Browse products available offline.&#39;,<br>                style: TextStyle(fontSize: 16),<br>              ),<br>              const SizedBox(height: 14),<br>              Align(<br>                alignment: Alignment.centerLeft,<br>                child: FilledButton.icon(<br>                  onPressed: _openAddProductPage,<br>                  icon: const Icon(Icons.add),<br>                  label: const Text(&#39;Add Product&#39;),<br>                ),<br>              ),<br>              const SizedBox(height: 20),&quot;&quot;&quot;,<br>    &quot;Catalog Add Product button&quot;,<br>)<br><br><br># 10. Replace single-line and multi-line Image.asset widgets.<br>image_pattern = re.compile(<br>    r&quot;&quot;&quot;Image\.asset\(<br>        \s*product\.imagePath\s*,<br>        \s*fit:\s*(BoxFit\.\w+)\s*,<br>        \s*\)<br>        |<br>        Image\.asset\(<br>        \s*product\.imagePath\s*,<br>        \s*fit:\s*(BoxFit\.\w+)\s*<br>        \)<br>    &quot;&quot;&quot;,<br>    re.VERBOSE | re.DOTALL,<br>)<br><br><br>def replace_product_image(match: re.Match[str]) -&gt; str:<br>    fit = match.group(1) or match.group(2)<br><br>    return (<br>        &quot;ProductImage(&quot;<br>        &quot;product: product, &quot;<br>        f&quot;fit: {fit}&quot;<br>        &quot;)&quot;<br>    )<br><br><br>text, image_count = image_pattern.subn(<br>    replace_product_image,<br>    text,<br>)<br><br>if image_count == 0:<br>    raise SystemExit(<br>        &quot;No product Image.asset widget was replaced.&quot;<br>    )<br><br>remaining_direct_images = re.findall(<br>    r&quot;Image\.asset\(\s*product\.imagePath&quot;,<br>    text,<br>    flags=re.DOTALL,<br>)<br><br>if remaining_direct_images:<br>    raise SystemExit(<br>        &quot;A direct product Image.asset reference is still present.&quot;<br>    )<br><br>remaining_image_path_references = text.count(&quot;product.imagePath&quot;)<br><br>if remaining_image_path_references != 1:<br>    raise SystemExit(<br>        &quot;Unexpected product.imagePath references remain: &quot;<br>        f&quot;{remaining_image_path_references}.&quot;<br>    )<br><br><br># 11. Final checks before writing the file.<br>required_markers = [<br>    &quot;class ProductImage&quot;,<br>    &quot;class AddProductPage&quot;,<br>    &quot;late final List&lt;Product&gt; _products&quot;,<br>    &quot;_products = List&lt;Product&gt;.of(initialProducts)&quot;,<br>    &quot;Future&lt;void&gt; _openAddProductPage()&quot;,<br>    &quot;label: const Text(&#39;Add Product&#39;)&quot;,<br>]<br><br>for marker in required_markers:<br>    if marker not in text:<br>        raise SystemExit(<br>            f&quot;Required marker was not created: {marker}&quot;<br>        )<br><br><br>path.write_text(text, encoding=&quot;utf-8&quot;)<br><br>print(&quot;Episode 22 Add Product patch applied successfully.&quot;)<br>print(f&quot;Editable product references updated: {reference_count}&quot;)<br>print(f&quot;Product image widgets updated: {image_count}&quot;)<br>print(&quot;Updated file:&quot;, path)<br>PY<br><br>dart format lib/main.dart</pre><p>The revised patch now supports the image formats that already existed in the application.</p><p>The original twenty products are copied into an editable list when the home page starts. The Add Product form returns a complete Product object, and that object joins the same collection used by search, category filters, favorites, product details, and the shopping cart.</p><p>A shared ProductImage widget now handles both bundled asset images and images selected while the application is running.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*x6D17PJq2rbcYroxPZNthA.png" /><figcaption>Applying the revised Add Product patch after adapting it to the application’s existing image widgets.</figcaption></figure><p>The main implementation is now in place, but I do not want to move directly to the analyzer without reviewing the connected sections.</p><p>The patch added a new image widget, a complete Add Product page, an editable product list, dynamic categories, and the method that returns a newly created product to the catalog.</p><p>I will inspect those sections in the actual file before testing the application.</p><pre>cd ~/offline_product_catalog<br><br>printf &#39;\n=== EPISODE 22 LOCATIONS ===\n&#39;<br>grep -nE \<br>&quot;^class ProductImage|^class AddProductPage|^class _AddProductPageState|late final List&lt;Product&gt; _products|void initState|Future&lt;void&gt; _openAddProductPage|label: const Text\(&#39;Add Product&#39;\)|final categories = &lt;String&gt;&quot; \<br>lib/main.dart<br><br>printf &#39;\n=== REMAINING FIXED PRODUCT REFERENCES ===\n&#39;<br>grep -nE \<br>&quot;\bproducts\.where\b|^const products|^const initialProducts|_products\.where&quot; \<br>lib/main.dart</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*pdcr8aJbTBF4KkpkGjNL8A.png" /><figcaption>The terminal now shows the real locations of every major Episode 22 addition.</figcaption></figure><p>It also checks whether the catalog and Favorites page still read from the old fixed product list. The original data may remain as `initialProducts`, but the visible application should now read from `_products`.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*72vcvJJAT5_x5EiFzt8X9A.png" /><figcaption>Updating the Product model to support both bundled assets and images selected at runtime.</figcaption></figure><p>The new product flow now connects several parts of the application: the Product model, image selection, editable catalog state, dynamic categories, search, favorites, product details, and the shopping cart.</p><p>Before opening Chrome, I am running Flutter’s analyzer once across the complete project. This should catch missing imports, incorrect constructor arguments, type mismatches, and any references that still expect every product image to come from an asset path.</p><pre>cd ~/offline_product_catalog<br><br>printf &#39;\n=== FORMAT CHECK ===\n&#39;<br>dart format lib/main.dart<br><br>printf &#39;\n=== FLUTTER ANALYZE ===\n&#39;<br>flutter analyze</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*cLg5GvoNfaW4-oeomEXBQA.png" /></figure><p>The first analyzer check did not find a broken feature or a type error. It found one unnecessary import at the top of `main.dart`.</p><p>The file imports both `dart:typed_data` and `package:flutter/services.dart`. The Add Product flow uses `Uint8List` for the selected image bytes, but Flutter’s services library already makes that type available.</p><p>Because the second import already provides everything the code needs, keeping `dart:typed_data` would only duplicate the same dependency.</p><p>The fix is small and isolated. I only need to remove the redundant import and leave the product model, image picker, form, and editable catalog state unchanged.</p><pre>cd ~/offline_product_catalog<br><br>python3 &lt;&lt;&#39;PY&#39;<br>from pathlib import Path<br><br>path = Path(&quot;lib/main.dart&quot;)<br>text = path.read_text(encoding=&quot;utf-8&quot;)<br><br>old_import = &quot;import &#39;dart:typed_data&#39;;\n\n&quot;<br><br>if old_import not in text:<br>    raise SystemExit(<br>        &quot;The dart:typed_data import was not found. No change was made.&quot;<br>    )<br><br>text = text.replace(old_import, &quot;&quot;, 1)<br>path.write_text(text, encoding=&quot;utf-8&quot;)<br><br>print(&quot;Removed the unnecessary dart:typed_data import.&quot;)<br>print(&quot;Updated file:&quot;, path)<br>PY<br><br>printf &#39;\n=== FORMAT AFTER FIX ===\n&#39;<br>dart format lib/main.dart<br><br>printf &#39;\n=== ANALYZE AFTER FIX ===\n&#39;<br>flutter analyze</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*jl6My79JO5NKsHJ4pphIMQ.png" /><figcaption>Removing one redundant import and completing a clean analyzer check.</figcaption></figure><p>The project now passes the analyzer without issues.</p><p>The next test needs to happen in the running application. I will launch it once in Chrome, create a product through the new form, and follow that product through the catalog features that already existed before Episode 22.</p><pre>cd ~/offline_product_catalog<br><br>printf &#39;\n=== AVAILABLE DEVICES ===\n&#39;<br>flutter devices<br>flutter run -d chrome</pre><p>Flutter detected Chrome and launched the updated catalog.</p><p>The original twenty products should still be available. The first visible change is the Add Product button near the top of the Catalog page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/1*JTtuUdxJNj-U0o9iP_TBNg.png" /><figcaption>Completing the new product form with an image, price, description, and custom category.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/1*79HiOmvrHhGJO4AlKrEXbA.png" /><figcaption>The newly added product appearing in the catalog with its own dynamic category.</figcaption></figure><p>The catalog immediately displayed twenty-one products, and the custom Home Office category appeared as a new filter without requiring another source-code change.</p><p>The newly created product now behaves like every built-in product.</p><p>It can be searched, filtered by its new category, opened on the detail page, added to Favorites, and placed in the shopping cart. Increasing its quantity also updates the subtotal and order total through the existing cart state.</p><p>The product currently remains available only while the application is running.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/1*iys7Gtlyz7hbyKQmmNJdKQ.png" /><figcaption>Testing the newly created product inside the existing shopping cart flow.</figcaption></figure><p>Refreshing Chrome or closing the application resets the catalog to its original twenty products. That limitation is intentional for this episode. The next step is to save user-created products locally so the catalog can restore them after the application restarts.</p><p>The catalog is no longer limited to the products written inside `main.dart`.</p><p>A user can now open the Add Product form, choose an image, enter a name, price, description, and category, then save the product directly from the application.</p><p>The original twenty products still use images bundled with the Flutter project. Products created through the form use images selected at runtime, and the shared ProductImage widget handles both sources.</p><p>The product collection is now editable and shared across the application. A newly added product immediately appears in the catalog, search results, category filters, product details, favorites, and the shopping cart.</p><p>The catalog is editable, but it is not persistent yet.</p><p>Products created in this episode remain in memory while the application is running. Refreshing the browser or restarting the application restores the original twenty-product catalog.</p><p>In the next episode, I will add local persistence to the catalog.</p><p>User-created products, custom categories, prices, descriptions, and selected images will need to survive a browser refresh or application restart. The app will load the saved catalog when it starts and update local storage whenever the product collection changes.</p><p>The goal is to keep the application offline while making the catalog feel permanent rather than temporary.</p><p>Episode 22 gave the catalog a way to grow. Episode 23 will make sure that growth is still there when the application opens again.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be5de5de8412" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Episode 21: Building a Real Shopping Cart in Flutter]]></title>
            <link>https://medium.com/@lenakendari/episode-21-building-a-real-shopping-cart-in-flutter-c6b646f917fc?source=rss-932b58a7a66a------2</link>
            <guid isPermaLink="false">https://medium.com/p/c6b646f917fc</guid>
            <category><![CDATA[ecommerce]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Atelier Flutter]]></dc:creator>
            <pubDate>Tue, 21 Jul 2026 14:10:55 GMT</pubDate>
            <atom:updated>2026-07-21T14:10:55.257Z</atom:updated>
            <content:encoded><![CDATA[<p>I turn the empty Cart tab into a working shopping flow with Add to Cart buttons, quantities, item removal, and a running order total.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jitf9Y0yRo8IetcgQK8qiA.png" /></figure><p>By the end of Episode 20, the app already had a complete product catalog, search, category filters, product details, favorites, and bottom navigation. The Cart tab, however, was still only a placeholder.</p><p>In this episode, I am turning that empty tab into a working shopping cart. Products will be added from both the catalog and the detail page, repeated additions will increase the quantity, and every item will have its own subtotal.</p><p>The cart will also support quantity controls, item removal, a running order total, an empty state, and a badge on the bottom navigation. Checkout itself will remain simple for now, because the complete checkout flow belongs in Episode 22.</p><p>The goal is to keep the implementation easy to follow while giving the app a shopping flow that feels complete and consistent with the features already built.</p><p>Before building the cart, I need to inspect the code that already connects the catalog, product details, favorites, and bottom navigation.</p><p>The most important detail is the product price. Until now, the app only needed to display values such as $49.00. A shopping cart needs a numeric value so it can calculate item subtotals and the complete order total.</p><p>Instead of changing the model based on an assumption, I will first locate the current Product class, product data, detail page, and Cart placeholder.</p><pre>cd ~/offline_product_catalog<br><br>printf &#39;\n=== PROJECT LOCATION ===\n&#39;<br>pwd<br><br>printf &#39;\n=== PRODUCT MODEL AND PRICE REFERENCES ===\n&#39;<br>grep -nE &quot;class Product|String price|double price|priceValue|price:&quot; lib/main.dart<br><br>printf &#39;\n=== DETAIL, FAVORITES, CART, AND NAVIGATION ===\n&#39;<br>grep -nE &quot;ProductDetailPage|Favorites|Cart|NavigationBar|BottomNavigationBar|currentIndex|selectedIndex&quot; lib/main.dart</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/1*wuBxK1xj--ZZKOulq_Se-g.png" /><figcaption>Inspecting the existing product model, detail page, and navigation before adding cart state.</figcaption></figure><p>The search results give me the locations of the important pieces, but a class name or field declaration is not enough to plan a safe change.</p><p>I also need to see how products are constructed, how the favorite state is shared, how the detail page receives a product, and how the three bottom navigation tabs are currently assembled.</p><p>This inspection will show where the cart state should live without disturbing the features that already work.</p><pre>cd ~/offline_product_catalog<br><br>printf &#39;\n=== PRODUCT MODEL ===\n&#39;<br>grep -n -B 5 -A 35 &quot;class Product&quot; lib/main.dart<br><br>printf &#39;\n=== PRODUCT DATA AND PRICE FORMAT ===\n&#39;<br>grep -n -B 3 -A 8 &quot;price:&quot; lib/main.dart | head -n 140<br><br>printf &#39;\n=== FAVORITE STATE ===\n&#39;<br>grep -n -B 8 -A 35 -E &quot;favoriteProducts|favorites|toggleFavorite|isFavorite&quot; \<br>  lib/main.dart | head -n 180<br><br>printf &#39;\n=== PRODUCT DETAIL PAGE ===\n&#39;<br>grep -n -B 8 -A 100 &quot;class ProductDetailPage&quot; lib/main.dart<br><br>printf &#39;\n=== CART AND BOTTOM NAVIGATION ===\n&#39;<br>grep -n -B 15 -A 100 -E \<br>  &quot;Cart|NavigationDestination|BottomNavigationBar|NavigationBar|selectedIndex|currentIndex&quot; \<br>  lib/main.dart | tail -n 260</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/1*nG76m0nbz8YQjNR2CLMFcA.png" /><figcaption>Reviewing the product model, price format, and the existing shared favorite state.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/1*22gnsquSTxKB3SDPfm76mA.png" /><figcaption>Tracing the product detail page and bottom navigation before connecting the new cart flow.</figcaption></figure><p>Before editing the cart, I am creating a backup of the current working file.</p><p>The catalog, product details, favorites, and navigation already work, so the safest approach is to preserve that version first and then inspect only the sections that the cart needs to connect to.</p><p>This also gives me exact line numbers from the current file instead of relying on an older structure or replacing more code than necessary.</p><pre>cd ~/offline_product_catalog<br><br>backup_file=&quot;lib/main.dart.episode20_backup_$(date +%Y%m%d_%H%M%S)&quot;<br>cp lib/main.dart &quot;$backup_file&quot;<br><br>printf &#39;\n=== BACKUP CREATED ===\n&#39;<br>printf &#39;%s\n&#39; &quot;$backup_file&quot;<br><br>printf &#39;\n=== IMPORTANT LOCATIONS ===\n&#39;<br>grep -nE \<br>&quot;class Product|class ProductCard|class ProductDetailPage|class .*State|NavigationBar|BottomNavigationBar|NavigationDestination|Cart&quot; \<br>lib/main.dart</pre><p>The backup is now in place, and the terminal has identified the current locations of the product model, product cards, detail page, application state, navigation, and Cart tab.</p><p>Those line numbers matter because the application has changed across several episodes. Rather than relying on an older version of the file, I can now inspect the exact code that is running at the beginning of Episode 21.</p><p>The first search only shows where each section begins. Before writing the cart patch, I need enough surrounding code to understand the constructors, callbacks, state variables, and widget hierarchy already in use.</p><p>I will print those sections with their real line numbers. This gives me a clear view of where the new cart state can be added and how it should be passed to the catalog, product details, and bottom navigation.</p><pre>cd ~/offline_product_catalog<br><br>show_context() {<br>  label=&quot;$1&quot;<br>  pattern=&quot;$2&quot;<br>  before=&quot;$3&quot;<br>  after=&quot;$4&quot;<br><br>  line=$(grep -nE &quot;$pattern&quot; lib/main.dart | head -n 1 | cut -d: -f1)<br><br>  printf &#39;\n=== %s ===\n&#39; &quot;$label&quot;<br><br>  if [ -z &quot;$line&quot; ]; then<br>    printf &#39;Pattern not found: %s\n&#39; &quot;$pattern&quot;<br>    return<br>  fi<br><br>  start=$((line - before))<br><br>  if [ &quot;$start&quot; -lt 1 ]; then<br>    start=1<br>  fi<br><br>  end=$((line + after))<br><br>  nl -ba lib/main.dart | sed -n &quot;${start},${end}p&quot;<br>}<br><br>show_context \<br>  &quot;PRODUCT MODEL&quot; \<br>  &quot;^class Product&quot; \<br>  5 \<br>  45<br><br>printf &#39;\n=== PRODUCT PRICE DATA ===\n&#39;<br>grep -n -m 5 -B 4 -A 8 &quot;price:&quot; lib/main.dart<br><br>show_context \<br>  &quot;PRODUCT CARD&quot; \<br>  &quot;^class ProductCard&quot; \<br>  8 \<br>  180<br><br>show_context \<br>  &quot;PRODUCT DETAIL PAGE&quot; \<br>  &quot;^class ProductDetailPage&quot; \<br>  8 \<br>  220<br><br>show_context \<br>  &quot;FAVORITE AND SHARED APP STATE&quot; \<br>  &quot;favoriteProducts|favorites|toggleFavorite|isFavorite&quot; \<br>  25 \<br>  220<br><br>show_context \<br>  &quot;BOTTOM NAVIGATION AND CART TAB&quot; \<br>  &quot;NavigationBar\\(|BottomNavigationBar\\(&quot; \<br>  80 \<br>  220</pre><pre>line=$(grep -nE &quot;$pattern&quot; lib/main.dart | head -n 1 | cut -d: -f1)</pre><p>This command does not modify the application. It only turns the current main.dart into a readable map of the sections involved in the cart flow.</p><p>I am looking for three main connections. First, the Product model must provide a safe numeric value for calculations. Second, the catalog and detail page must call the same Add to Cart function. Third, the Cart tab and its navigation badge must read from the same shared cart state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/1*AIlUjoN8jy1wvya1gO4xdg.png" /><figcaption>Reading the current product model, price data, and product card before adding cart behavior.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/1*Jta8KSRUnLfXDor_EKQb1Q.png" /><figcaption>Mapping the shared state, product detail page, and Cart tab before writing the main implementation.</figcaption></figure><p>Mapping the shared state, product detail page, and Cart tab before writing the main implementation.</p><p>Before changing the cart, I am opening the current application once to confirm the starting point.</p><p>The catalog, favorites, product details, search, filters, and bottom navigation should still work as they did at the end of Episode 20. The Cart tab should still show its empty placeholder.</p><p>This gives me a clear visual baseline before the shopping cart implementation begins.</p><pre>cd ~/offline_product_catalog<br><br>printf &#39;\n=== AVAILABLE DEVICES ===\n&#39;<br>flutter devices<br>flutter run -d chrome</pre><p>Flutter detected Chrome as an available web device and launched the current application without changing the source code.</p><p>At this stage, I am checking that the existing navigation still works and that the Cart tab is still the unfinished part of the shopping flow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/486/1*QwkVZu5vTNrlTsAk06CU9g.png" /><figcaption>The Cart tab at the beginning of Episode 21, still waiting for a complete shopping flow.</figcaption></figure><p>The starting point is now clear. The existing catalog and navigation still work, while the Cart tab remains a placeholder.</p><p>I can now return to the source code and prepare the main implementation. Before editing, I want one final focused view of the product model, product card, detail page, shared state, and navigation.</p><p>These are the exact places that need to communicate with the cart.</p><p>After confirming the visual baseline, I stopped the development session and returned to the current source file.</p><p>The next change will connect several existing widgets, so I am collecting the relevant sections into one readable terminal output before writing the patch.</p><pre>cd ~/offline_product_catalog<br><br>python3 &lt;&lt;&#39;PY&#39;<br>from pathlib import Path<br>import re<br><br>path = Path(&quot;lib/main.dart&quot;)<br>lines = path.read_text(encoding=&quot;utf-8&quot;).splitlines()<br><br>sections = [<br>    (&quot;PRODUCT MODEL&quot;, r&quot;^class Product\b&quot;, 5, 55),<br>    (&quot;PRODUCT CARD&quot;, r&quot;^class ProductCard\b&quot;, 8, 190),<br>    (&quot;PRODUCT DETAIL PAGE&quot;, r&quot;^class ProductDetailPage\b&quot;, 8, 230),<br>    (<br>        &quot;SHARED STATE&quot;,<br>        r&quot;favoriteProducts|toggleFavorite|isFavorite&quot;,<br>        30,<br>        250,<br>    ),<br>    (<br>        &quot;NAVIGATION AND CART&quot;,<br>        r&quot;NavigationBar\(|BottomNavigationBar\(&quot;,<br>        100,<br>        260,<br>    ),<br>]<br><br>for title, pattern, before, after in sections:<br>    match_index = next(<br>        (<br>            index<br>            for index, line in enumerate(lines)<br>            if re.search(pattern, line)<br>        ),<br>        None,<br>    )<br><br>    print(f&quot;\n=== {title} ===&quot;)<br><br>    if match_index is None:<br>        print(f&quot;Pattern not found: {pattern}&quot;)<br>        continue<br><br>    start = max(0, match_index - before)<br>    end = min(len(lines), match_index + after + 1)<br><br>    for index in range(start, end):<br>        print(f&quot;{index + 1:5}  {lines[index]}&quot;)<br>PY</pre><p>This script only reads main.dart. It searches for the existing classes and state variables, then prints the surrounding code with its real line numbers.</p><p>Using the current file as the source of truth prevents the cart implementation from depending on an older version of the application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/1*NTnf21IhxFNRz0Dj_ZCXsQ.png" /><figcaption>Reviewing the exact product and card structure before introducing Add to Cart actions.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*6ekOdpO9Cat1GB9zKh7d5g.png" /><figcaption>Locating the shared application state and Cart placeholder before connecting the complete shopping flow.</figcaption></figure><p>A working cart needs one source of truth.</p><p>The catalog cards, product detail page, Cart tab, and navigation badge should not keep separate copies of the same information. If they did, adding a product from one screen could leave the other screens out of sync.</p><p>The safest approach is to place the cart state beside the existing favorite state. From there, the application can pass simple callbacks and values to every screen that needs them.</p><p>The cart state needs to support a small set of predictable operations.</p><p>Adding a new product should create one cart entry with a quantity of one. Adding the same product again should increase that quantity instead of creating another row.</p><p>The same state also needs methods for increasing quantities, decreasing quantities, removing products, counting all units in the cart, and calculating the complete order total.</p><p>The inspection revealed that the application does not use a separate ProductCard widget. Each card is built directly inside the catalog grid, while the shared favorite state lives in the main home page state.</p><p>The Product model still stores prices as formatted strings such as $49.00. Instead of rewriting all twenty product entries, I can add a numeric getter to the existing model and keep the current display value unchanged.</p><p>The Cart tab is also still connected through a dedicated placeholder method. This gives me a clear replacement point for the working cart interface.</p><p>One section is still missing from the terminal output. The previous inspection stopped near the bottom of the catalog card, just before the complete card actions and Cart placeholder became visible.</p><p>I will print that final range directly from the current file. The line numbers are no longer estimates because the earlier search confirmed that the Cart placeholder begins near line 798.</p><pre>cd ~/offline_product_catalog<br><br>printf &#39;\n=== CARD ACTIONS, FAVORITES, AND CART PLACEHOLDER ===\n&#39;<br>nl -ba lib/main.dart | sed -n &#39;700,850p&#39;<br></pre><pre>nl -ba lib/main.dart</pre><pre>sed -n &#39;700,850p&#39;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*OD-j8urODjnQOVIRV-kMKQ.png" /><figcaption>Inspecting the final catalog card actions and the exact Cart placeholder before writing the main cart patch.</figcaption></figure><p>The code inspection confirmed that the catalog cards are built directly inside the product grid, while the shared application state lives in MyHomePage.</p><p>The current Product model keeps its formatted price as a string. I will preserve that value for display and add a numeric getter for calculations. This avoids rewriting the twenty existing products.</p><p>The main patch will now connect one cart state to the catalog, product detail page, Cart tab, and navigation badge. Adding the same product again will update its quantity instead of creating another cart row.</p><p>The previous inspection confirmed the main structure, but its output stopped near the bottom of the catalog card.</p><p>Before applying the cart patch, I need to see the remaining card actions, the Favorites page, and the complete Cart placeholder. This is the final inspection before the source code changes.</p><pre>cd ~/offline_product_catalog<br><br>printf &#39;\n=== FINAL SECTION BEFORE THE CART PATCH ===\n&#39;<br>nl -ba lib/main.dart | sed -n &#39;700,850p&#39;</pre><p>This command prints the final section of the current home page state with its real line numbers.</p><p>It does not modify the application. I am using it to confirm where the catalog card ends, how the Favorites page is built, and exactly what the Cart placeholder currently returns.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*wmb4AWGUeOtPOhttTZhhYg.png" /><figcaption>Reviewing the final catalog and Cart sections before connecting the shared shopping state.</figcaption></figure><p>The existing structure is now clear enough for the main cart implementation.</p><p>I will keep the formatted price string that the application already uses for display, then add a numeric getter for calculations. This avoids rewriting all twenty product entries while still giving the cart a reliable value for subtotals and totals.</p><p>The cart state will live beside the favorite state in the main home page. From there, the same data can be used by the catalog, product detail page, Cart tab, and navigation badge.</p><pre>cd ~/offline_product_catalog<br><br>python3 &lt;&lt;&#39;PY&#39;<br>from pathlib import Path<br><br>path = Path(&quot;lib/main.dart&quot;)<br>text = path.read_text(encoding=&quot;utf-8&quot;)<br><br>if &quot;final Map&lt;Product, int&gt; _cartItems&quot; in text:<br>    raise SystemExit(<br>        &quot;Cart state already exists. The patch was not applied a second time.&quot;<br>    )<br><br><br>def replace_once(old, new, label):<br>    global text<br><br>    count = text.count(old)<br><br>    if count != 1:<br>        raise SystemExit(<br>            f&quot;{label}: expected exactly one match, but found {count}.&quot;<br>        )<br><br>    text = text.replace(old, new, 1)<br><br><br>def find_method_span(source, signature):<br>    start = source.find(signature)<br><br>    if start == -1:<br>        raise SystemExit(f&quot;Method not found: {signature}&quot;)<br><br>    opening_brace = source.find(&quot;{&quot;, start)<br><br>    if opening_brace == -1:<br>        raise SystemExit(f&quot;Opening brace not found: {signature}&quot;)<br><br>    depth = 0<br><br>    for index in range(opening_brace, len(source)):<br>        character = source[index]<br><br>        if character == &quot;{&quot;:<br>            depth += 1<br>        elif character == &quot;}&quot;:<br>            depth -= 1<br><br>            if depth == 0:<br>                return start, index + 1<br><br>    raise SystemExit(f&quot;Closing brace not found: {signature}&quot;)<br><br><br># 1. Keep the formatted price and add a numeric value for calculations.<br>replace_once(<br>    &quot;&quot;&quot;  final String imagePath;<br>}&quot;&quot;&quot;,<br>    &quot;&quot;&quot;  final String imagePath;<br><br>  double get priceValue {<br>    return double.parse(price.replaceFirst(r&#39;$&#39;, &#39;&#39;));<br>  }<br>}&quot;&quot;&quot;,<br>    &quot;Product price getter&quot;,<br>)<br><br><br># 2. Give ProductDetailPage access to the shared Add to Cart action.<br>replace_once(<br>    &quot;&quot;&quot;    required this.onToggleFavorite,<br>  });&quot;&quot;&quot;,<br>    &quot;&quot;&quot;    required this.onToggleFavorite,<br>    required this.onAddToCart,<br>  });&quot;&quot;&quot;,<br>    &quot;ProductDetailPage constructor&quot;,<br>)<br><br>replace_once(<br>    &quot;&quot;&quot;  final bool isFavorite;<br>  final VoidCallback onToggleFavorite;&quot;&quot;&quot;,<br>    &quot;&quot;&quot;  final bool isFavorite;<br>  final VoidCallback onToggleFavorite;<br>  final VoidCallback onAddToCart;&quot;&quot;&quot;,<br>    &quot;ProductDetailPage fields&quot;,<br>)<br><br>replace_once(<br>    &quot;&quot;&quot;  bool get isFavorite =&gt; _favorite;<br>  VoidCallback get onToggleFavorite =&gt; _handleToggleFavorite;&quot;&quot;&quot;,<br>    &quot;&quot;&quot;  bool get isFavorite =&gt; _favorite;<br>  VoidCallback get onToggleFavorite =&gt; _handleToggleFavorite;<br>  VoidCallback get onAddToCart =&gt; widget.onAddToCart;&quot;&quot;&quot;,<br>    &quot;ProductDetailPage getters&quot;,<br>)<br><br>replace_once(<br>    &quot;&quot;&quot;              FilledButton.icon(<br>                onPressed: onToggleFavorite,<br>                icon: Icon(isFavorite ? Icons.favorite : Icons.favorite_border),<br>                label: Text(<br>                  isFavorite ? &#39;Remove from Favorites&#39; : &#39;Add to Favorites&#39;,<br>                ),<br>              ),&quot;&quot;&quot;,<br>    &quot;&quot;&quot;              FilledButton.icon(<br>                onPressed: onToggleFavorite,<br>                icon: Icon(isFavorite ? Icons.favorite : Icons.favorite_border),<br>                label: Text(<br>                  isFavorite ? &#39;Remove from Favorites&#39; : &#39;Add to Favorites&#39;,<br>                ),<br>              ),<br>              const SizedBox(height: 12),<br>              FilledButton.icon(<br>                onPressed: () {<br>                  onAddToCart();<br><br>                  ScaffoldMessenger.of(context)<br>                    ..hideCurrentSnackBar()<br>                    ..showSnackBar(<br>                      SnackBar(<br>                        content: Text(&#39;${product.name} added to cart.&#39;),<br>                      ),<br>                    );<br>                },<br>                icon: const Icon(Icons.add_shopping_cart),<br>                label: const Text(&#39;Add to Cart&#39;),<br>              ),&quot;&quot;&quot;,<br>    &quot;Product detail buttons&quot;,<br>)<br><br><br># 3. Add the Episode 22 checkout preview page.<br>checkout_page = r&#39;&#39;&#39;<br>class CheckoutPreviewPage extends StatelessWidget {<br>  const CheckoutPreviewPage({<br>    super.key,<br>    required this.itemCount,<br>    required this.total,<br>  });<br><br>  final int itemCount;<br>  final double total;<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(<br>        backgroundColor: Theme.of(context).colorScheme.inversePrimary,<br>        title: const Text(&#39;Checkout&#39;),<br>      ),<br>      body: Center(<br>        child: SingleChildScrollView(<br>          padding: const EdgeInsets.all(24),<br>          child: ConstrainedBox(<br>            constraints: const BoxConstraints(maxWidth: 560),<br>            child: Card(<br>              child: Padding(<br>                padding: const EdgeInsets.all(32),<br>                child: Column(<br>                  mainAxisSize: MainAxisSize.min,<br>                  children: [<br>                    const Icon(<br>                      Icons.shopping_bag_outlined,<br>                      size: 72,<br>                      color: Color(0xFF5E35B1),<br>                    ),<br>                    const SizedBox(height: 20),<br>                    const Text(<br>                      &#39;Checkout Is Coming in Episode 22&#39;,<br>                      textAlign: TextAlign.center,<br>                      style: TextStyle(<br>                        fontSize: 26,<br>                        fontWeight: FontWeight.bold,<br>                      ),<br>                    ),<br>                    const SizedBox(height: 12),<br>                    const Text(<br>                      &#39;The cart is ready, but delivery information, order review, and the complete checkout flow will be built in the next episode.&#39;,<br>                      textAlign: TextAlign.center,<br>                      style: TextStyle(fontSize: 16, height: 1.5),<br>                    ),<br>                    const SizedBox(height: 24),<br>                    Text(<br>                      &#39;$itemCount items&#39;,<br>                      style: const TextStyle(<br>                        fontSize: 16,<br>                        fontWeight: FontWeight.w600,<br>                      ),<br>                    ),<br>                    const SizedBox(height: 6),<br>                    Text(<br>                      &#39;Order total: \$${total.toStringAsFixed(2)}&#39;,<br>                      style: const TextStyle(<br>                        fontSize: 22,<br>                        fontWeight: FontWeight.bold,<br>                        color: Color(0xFF5E35B1),<br>                      ),<br>                    ),<br>                    const SizedBox(height: 28),<br>                    FilledButton.icon(<br>                      onPressed: () {<br>                        Navigator.of(context).pop();<br>                      },<br>                      icon: const Icon(Icons.arrow_back),<br>                      label: const Text(&#39;Back to Cart&#39;),<br>                    ),<br>                  ],<br>                ),<br>              ),<br>            ),<br>          ),<br>        ),<br>      ),<br>    );<br>  }<br>}<br><br>&#39;&#39;&#39;<br><br>replace_once(<br>    &quot;class MyApp extends StatelessWidget {&quot;,<br>    checkout_page + &quot;class MyApp extends StatelessWidget {&quot;,<br>    &quot;Checkout preview page&quot;,<br>)<br><br><br># 4. Add the shared cart state beside the existing favorite state.<br>replace_once(<br>    &quot;&quot;&quot;  final Set&lt;String&gt; _favoriteProductNames = {};&quot;&quot;&quot;,<br>    &quot;&quot;&quot;  final Set&lt;String&gt; _favoriteProductNames = {};<br>  final Map&lt;Product, int&gt; _cartItems = {};&quot;&quot;&quot;,<br>    &quot;Shared cart state&quot;,<br>)<br><br>cart_state_methods = r&#39;&#39;&#39;<br>  int get _cartItemCount {<br>    return _cartItems.values.fold(<br>      0,<br>      (total, quantity) =&gt; total + quantity,<br>    );<br>  }<br><br>  double get _cartTotal {<br>    return _cartItems.entries.fold(<br>      0,<br>      (total, entry) {<br>        return total + (entry.key.priceValue * entry.value);<br>      },<br>    );<br>  }<br><br>  String _formatPrice(double value) {<br>    return &#39;\$${value.toStringAsFixed(2)}&#39;;<br>  }<br><br>  void _addToCart(Product product) {<br>    setState(() {<br>      _cartItems.update(<br>        product,<br>        (quantity) =&gt; quantity + 1,<br>        ifAbsent: () =&gt; 1,<br>      );<br>    });<br>  }<br><br>  void _increaseCartQuantity(Product product) {<br>    setState(() {<br>      _cartItems.update(<br>        product,<br>        (quantity) =&gt; quantity + 1,<br>        ifAbsent: () =&gt; 1,<br>      );<br>    });<br>  }<br><br>  void _decreaseCartQuantity(Product product) {<br>    final quantity = _cartItems[product];<br><br>    if (quantity == null) {<br>      return;<br>    }<br><br>    setState(() {<br>      if (quantity &lt;= 1) {<br>        _cartItems.remove(product);<br>      } else {<br>        _cartItems[product] = quantity - 1;<br>      }<br>    });<br>  }<br><br>  void _removeFromCart(Product product) {<br>    setState(() {<br>      _cartItems.remove(product);<br>    });<br>  }<br><br>  void _openCheckout() {<br>    Navigator.of(context).push(<br>      MaterialPageRoute(<br>        builder: (context) =&gt; CheckoutPreviewPage(<br>          itemCount: _cartItemCount,<br>          total: _cartTotal,<br>        ),<br>      ),<br>    );<br>  }<br><br>&#39;&#39;&#39;<br><br>replace_once(<br>    &quot;  void _openProductDetail(Product product) {&quot;,<br>    cart_state_methods + &quot;  void _openProductDetail(Product product) {&quot;,<br>    &quot;Cart operations&quot;,<br>)<br><br><br># 5. Connect ProductDetailPage to the shared cart state.<br>replace_once(<br>    &quot;&quot;&quot;              onToggleFavorite: () {<br>                _toggleFavorite(product);<br>              },<br>            ),&quot;&quot;&quot;,<br>    &quot;&quot;&quot;              onToggleFavorite: () {<br>                _toggleFavorite(product);<br>              },<br>              onAddToCart: () {<br>                _addToCart(product);<br>              },<br>            ),&quot;&quot;&quot;,<br>    &quot;Product detail cart callback&quot;,<br>)<br><br><br># 6. Replace the Cart placeholder in the page list.<br>replace_once(<br>    &quot;&quot;&quot;      _buildCartPlaceholder(),&quot;&quot;&quot;,<br>    &quot;&quot;&quot;      _buildCartPage(),&quot;&quot;&quot;,<br>    &quot;Cart page connection&quot;,<br>)<br><br><br># 7. Make the NavigationBar badge dynamic.<br>replace_once(<br>    &quot;&quot;&quot;        destinations: const [&quot;&quot;&quot;,<br>    &quot;&quot;&quot;        destinations: [&quot;&quot;&quot;,<br>    &quot;Dynamic navigation destinations&quot;,<br>)<br><br>replace_once(<br>    &quot;&quot;&quot;          NavigationDestination(<br>            icon: Icon(Icons.shopping_cart_outlined),<br>            selectedIcon: Icon(Icons.shopping_cart),<br>            label: &#39;Cart&#39;,<br>          ),&quot;&quot;&quot;,<br>    &quot;&quot;&quot;          NavigationDestination(<br>            icon: Badge(<br>              isLabelVisible: _cartItemCount &gt; 0,<br>              label: Text(&#39;$_cartItemCount&#39;),<br>              child: const Icon(Icons.shopping_cart_outlined),<br>            ),<br>            selectedIcon: Badge(<br>              isLabelVisible: _cartItemCount &gt; 0,<br>              label: Text(&#39;$_cartItemCount&#39;),<br>              child: const Icon(Icons.shopping_cart),<br>            ),<br>            label: &#39;Cart&#39;,<br>          ),&quot;&quot;&quot;,<br>    &quot;Cart navigation badge&quot;,<br>)<br><br><br># 8. Add an Add to Cart button below the price on each catalog card.<br>catalog_start, catalog_end = find_method_span(<br>    text,<br>    &quot;  Widget _buildCatalogPage() {&quot;,<br>)<br><br>catalog = text[catalog_start:catalog_end]<br>price_position = catalog.find(&quot;product.price&quot;)<br><br>if price_position == -1:<br>    raise SystemExit(&quot;Catalog price widget was not found.&quot;)<br><br>text_widget_start = catalog.rfind(&quot;Text(&quot;, 0, price_position)<br><br>if text_widget_start == -1:<br>    raise SystemExit(&quot;Catalog price Text widget was not found.&quot;)<br><br>opening_parenthesis = catalog.find(&quot;(&quot;, text_widget_start)<br>depth = 0<br>text_widget_end = None<br><br>for index in range(opening_parenthesis, len(catalog)):<br>    character = catalog[index]<br><br>    if character == &quot;(&quot;:<br>        depth += 1<br>    elif character == &quot;)&quot;:<br>        depth -= 1<br><br>        if depth == 0:<br>            text_widget_end = index + 1<br>            break<br><br>if text_widget_end is None:<br>    raise SystemExit(&quot;The end of the catalog price widget was not found.&quot;)<br><br>while (<br>    text_widget_end &lt; len(catalog)<br>    and catalog[text_widget_end] in &quot; \t&quot;<br>):<br>    text_widget_end += 1<br><br>if (<br>    text_widget_end &lt; len(catalog)<br>    and catalog[text_widget_end] == &quot;,&quot;<br>):<br>    text_widget_end += 1<br><br>catalog_button = r&#39;&#39;&#39;<br>                                    const SizedBox(height: 10),<br>                                    SizedBox(<br>                                      width: double.infinity,<br>                                      child: FilledButton.icon(<br>                                        onPressed: () {<br>                                          _addToCart(product);<br><br>                                          ScaffoldMessenger.of(context)<br>                                            ..hideCurrentSnackBar()<br>                                            ..showSnackBar(<br>                                              SnackBar(<br>                                                content: Text(<br>                                                  &#39;${product.name} added to cart.&#39;,<br>                                                ),<br>                                              ),<br>                                            );<br>                                        },<br>                                        icon: const Icon(<br>                                          Icons.add_shopping_cart,<br>                                          size: 18,<br>                                        ),<br>                                        label: const Text(&#39;Add to Cart&#39;),<br>                                      ),<br>                                    ),&#39;&#39;&#39;<br><br>catalog = (<br>    catalog[:text_widget_end]<br>    + catalog_button<br>    + catalog[text_widget_end:]<br>)<br><br>text = (<br>    text[:catalog_start]<br>    + catalog<br>    + text[catalog_end:]<br>)<br><br>replace_once(<br>    &quot;&quot;&quot;    final childAspectRatio = width &gt;= 700 ? 0.78 : 0.67;&quot;&quot;&quot;,<br>    &quot;&quot;&quot;    final childAspectRatio = width &gt;= 700 ? 0.70 : 0.57;&quot;&quot;&quot;,<br>    &quot;Product card height&quot;,<br>)<br><br><br># 9. Replace the placeholder with the complete Cart interface.<br>cart_page_code = r&#39;&#39;&#39;  Widget _buildCartPage() {<br>    if (_cartItems.isEmpty) {<br>      return Center(<br>        child: SingleChildScrollView(<br>          padding: const EdgeInsets.all(24),<br>          child: Column(<br>            mainAxisSize: MainAxisSize.min,<br>            children: [<br>              const Icon(<br>                Icons.remove_shopping_cart_outlined,<br>                size: 76,<br>                color: Colors.black38,<br>              ),<br>              const SizedBox(height: 18),<br>              const Text(<br>                &#39;Your Cart Is Empty&#39;,<br>                style: TextStyle(<br>                  fontSize: 26,<br>                  fontWeight: FontWeight.bold,<br>                ),<br>              ),<br>              const SizedBox(height: 8),<br>              const Text(<br>                &#39;Add a few products from the catalog to begin your order.&#39;,<br>                textAlign: TextAlign.center,<br>                style: TextStyle(fontSize: 16, color: Colors.black54),<br>              ),<br>              const SizedBox(height: 24),<br>              FilledButton.icon(<br>                onPressed: () {<br>                  setState(() {<br>                    _selectedTab = 0;<br>                  });<br>                },<br>                icon: const Icon(Icons.storefront),<br>                label: const Text(&#39;Browse Catalog&#39;),<br>              ),<br>            ],<br>          ),<br>        ),<br>      );<br>    }<br><br>    final entries = _cartItems.entries.toList();<br><br>    return LayoutBuilder(<br>      builder: (context, constraints) {<br>        final isWide = constraints.maxWidth &gt;= 900;<br><br>        final itemsPanel = Column(<br>          children: entries.map((entry) {<br>            return _buildCartItemCard(entry.key, entry.value);<br>          }).toList(),<br>        );<br><br>        final summaryPanel = Card(<br>          margin: EdgeInsets.zero,<br>          child: Padding(<br>            padding: const EdgeInsets.all(22),<br>            child: Column(<br>              crossAxisAlignment: CrossAxisAlignment.stretch,<br>              children: [<br>                const Text(<br>                  &#39;Order Summary&#39;,<br>                  style: TextStyle(<br>                    fontSize: 22,<br>                    fontWeight: FontWeight.bold,<br>                  ),<br>                ),<br>                const SizedBox(height: 20),<br>                Row(<br>                  mainAxisAlignment: MainAxisAlignment.spaceBetween,<br>                  children: [<br>                    const Text(&#39;Items&#39;),<br>                    Text(<br>                      &#39;$_cartItemCount&#39;,<br>                      style: const TextStyle(fontWeight: FontWeight.w700),<br>                    ),<br>                  ],<br>                ),<br>                const SizedBox(height: 14),<br>                const Divider(),<br>                const SizedBox(height: 14),<br>                Row(<br>                  mainAxisAlignment: MainAxisAlignment.spaceBetween,<br>                  children: [<br>                    const Text(<br>                      &#39;Order Total&#39;,<br>                      style: TextStyle(<br>                        fontSize: 18,<br>                        fontWeight: FontWeight.bold,<br>                      ),<br>                    ),<br>                    Text(<br>                      _formatPrice(_cartTotal),<br>                      style: const TextStyle(<br>                        fontSize: 22,<br>                        fontWeight: FontWeight.bold,<br>                        color: Color(0xFF5E35B1),<br>                      ),<br>                    ),<br>                  ],<br>                ),<br>                const SizedBox(height: 22),<br>                FilledButton.icon(<br>                  onPressed: _openCheckout,<br>                  icon: const Icon(Icons.arrow_forward),<br>                  label: const Text(&#39;Proceed to Checkout&#39;),<br>                ),<br>              ],<br>            ),<br>          ),<br>        );<br><br>        return SingleChildScrollView(<br>          padding: const EdgeInsets.all(20),<br>          child: Column(<br>            crossAxisAlignment: CrossAxisAlignment.start,<br>            children: [<br>              const Text(<br>                &#39;Shopping Cart&#39;,<br>                style: TextStyle(<br>                  fontSize: 28,<br>                  fontWeight: FontWeight.bold,<br>                ),<br>              ),<br>              const SizedBox(height: 6),<br>              Text(<br>                &#39;$_cartItemCount items ready for checkout.&#39;,<br>                style: const TextStyle(<br>                  fontSize: 16,<br>                  color: Colors.black54,<br>                ),<br>              ),<br>              const SizedBox(height: 22),<br>              if (isWide)<br>                Row(<br>                  crossAxisAlignment: CrossAxisAlignment.start,<br>                  children: [<br>                    Expanded(child: itemsPanel),<br>                    const SizedBox(width: 22),<br>                    SizedBox(width: 330, child: summaryPanel),<br>                  ],<br>                )<br>              else<br>                Column(<br>                  children: [<br>                    itemsPanel,<br>                    const SizedBox(height: 18),<br>                    summaryPanel,<br>                  ],<br>                ),<br>            ],<br>          ),<br>        );<br>      },<br>    );<br>  }<br><br>  Widget _buildCartItemCard(Product product, int quantity) {<br>    final subtotal = product.priceValue * quantity;<br><br>    return Card(<br>      margin: const EdgeInsets.only(bottom: 14),<br>      child: Padding(<br>        padding: const EdgeInsets.all(14),<br>        child: LayoutBuilder(<br>          builder: (context, constraints) {<br>            final isCompact = constraints.maxWidth &lt; 560;<br><br>            final productImage = Container(<br>              width: isCompact ? 82 : 104,<br>              height: isCompact ? 82 : 104,<br>              padding: const EdgeInsets.all(8),<br>              decoration: BoxDecoration(<br>                color: const Color(0xFFF7F5FA),<br>                borderRadius: BorderRadius.circular(14),<br>              ),<br>              child: Image.asset(<br>                product.imagePath,<br>                fit: BoxFit.contain,<br>              ),<br>            );<br><br>            final productInformation = Column(<br>              crossAxisAlignment: CrossAxisAlignment.start,<br>              children: [<br>                Text(<br>                  product.name,<br>                  maxLines: 2,<br>                  overflow: TextOverflow.ellipsis,<br>                  style: const TextStyle(<br>                    fontSize: 17,<br>                    fontWeight: FontWeight.bold,<br>                  ),<br>                ),<br>                const SizedBox(height: 5),<br>                Text(<br>                  product.category,<br>                  style: const TextStyle(<br>                    color: Color(0xFF5E35B1),<br>                    fontWeight: FontWeight.w600,<br>                  ),<br>                ),<br>                const SizedBox(height: 5),<br>                Text(<br>                  product.price,<br>                  style: const TextStyle(color: Colors.black54),<br>                ),<br>              ],<br>            );<br><br>            final quantityControl = Container(<br>              decoration: BoxDecoration(<br>                border: Border.all(color: Colors.black12),<br>                borderRadius: BorderRadius.circular(12),<br>              ),<br>              child: Row(<br>                mainAxisSize: MainAxisSize.min,<br>                children: [<br>                  IconButton(<br>                    tooltip: &#39;Decrease quantity&#39;,<br>                    onPressed: () {<br>                      _decreaseCartQuantity(product);<br>                    },<br>                    icon: const Icon(Icons.remove),<br>                  ),<br>                  Text(<br>                    &#39;$quantity&#39;,<br>                    style: const TextStyle(<br>                      fontSize: 16,<br>                      fontWeight: FontWeight.bold,<br>                    ),<br>                  ),<br>                  IconButton(<br>                    tooltip: &#39;Increase quantity&#39;,<br>                    onPressed: () {<br>                      _increaseCartQuantity(product);<br>                    },<br>                    icon: const Icon(Icons.add),<br>                  ),<br>                ],<br>              ),<br>            );<br><br>            if (isCompact) {<br>              return Column(<br>                children: [<br>                  Row(<br>                    crossAxisAlignment: CrossAxisAlignment.start,<br>                    children: [<br>                      productImage,<br>                      const SizedBox(width: 12),<br>                      Expanded(child: productInformation),<br>                      IconButton(<br>                        tooltip: &#39;Remove from cart&#39;,<br>                        onPressed: () {<br>                          _removeFromCart(product);<br>                        },<br>                        icon: const Icon(Icons.delete_outline),<br>                      ),<br>                    ],<br>                  ),<br>                  const SizedBox(height: 14),<br>                  Row(<br>                    mainAxisAlignment: MainAxisAlignment.spaceBetween,<br>                    children: [<br>                      Column(<br>                        crossAxisAlignment: CrossAxisAlignment.start,<br>                        children: [<br>                          const Text(<br>                            &#39;Subtotal&#39;,<br>                            style: TextStyle(color: Colors.black54),<br>                          ),<br>                          Text(<br>                            _formatPrice(subtotal),<br>                            style: const TextStyle(<br>                              fontSize: 18,<br>                              fontWeight: FontWeight.bold,<br>                            ),<br>                          ),<br>                        ],<br>                      ),<br>                      quantityControl,<br>                    ],<br>                  ),<br>                ],<br>              );<br>            }<br><br>            return Row(<br>              children: [<br>                productImage,<br>                const SizedBox(width: 16),<br>                Expanded(child: productInformation),<br>                const SizedBox(width: 16),<br>                Column(<br>                  crossAxisAlignment: CrossAxisAlignment.end,<br>                  children: [<br>                    const Text(<br>                      &#39;Subtotal&#39;,<br>                      style: TextStyle(color: Colors.black54),<br>                    ),<br>                    const SizedBox(height: 4),<br>                    Text(<br>                      _formatPrice(subtotal),<br>                      style: const TextStyle(<br>                        fontSize: 18,<br>                        fontWeight: FontWeight.bold,<br>                      ),<br>                    ),<br>                    const SizedBox(height: 10),<br>                    quantityControl,<br>                    TextButton.icon(<br>                      onPressed: () {<br>                        _removeFromCart(product);<br>                      },<br>                      icon: const Icon(Icons.delete_outline),<br>                      label: const Text(&#39;Remove&#39;),<br>                    ),<br>                  ],<br>                ),<br>              ],<br>            );<br>          },<br>        ),<br>      ),<br>    );<br>  }&#39;&#39;&#39;<br><br>cart_start, cart_end = find_method_span(<br>    text,<br>    &quot;  Widget _buildCartPlaceholder() {&quot;,<br>)<br><br>text = text[:cart_start] + cart_page_code + text[cart_end:]<br><br><br>path.write_text(text, encoding=&quot;utf-8&quot;)<br><br>print(&quot;Cart patch applied successfully.&quot;)<br>print(&quot;Updated file:&quot;, path)<br>print(&quot;The Episode 20 backup was left unchanged.&quot;)<br>PY<br><br>dart format lib/main.dart</pre><p>The main cart patch now connects the shopping flow across the application.</p><p>The Product model still displays its original formatted price, but it can also provide a numeric value for calculations. The home page now owns a shared map that connects each product to its quantity.</p><p>Adding the same product updates that quantity instead of creating another cart row. The Cart tab reads directly from the same map, which also drives the navigation badge, item subtotals, and complete order total.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*xkm_wXKMbvXsCiq3eRpgxw.png" /><figcaption>Applying the main cart patch and formatting the connected shopping flow.</figcaption></figure><p>The Cart tab is no longer an empty placeholder.</p><p>Products can now be added from the catalog and the detail page, repeated additions increase the quantity, and every cart item has its own subtotal. The cart also supports quantity controls, item removal, a running order total, an empty state, and a live badge in the bottom navigation.</p><p>The Proceed to Checkout button currently opens a simple preview page. That is intentional. Episode 21 focused on building a reliable cart foundation without adding payments, delivery services, accounts, or external APIs.</p><p>The shopping flow now works, but the catalog itself is still static.</p><p>All twenty products are still defined directly in the source code. Adding another product currently requires editing `main.dart`, placing a new image inside the project assets, and rebuilding the application.</p><p>That works for a tutorial catalog, but it is not practical for someone who wants to manage real products from inside the app.</p><p>In the next episode, I will begin turning this static catalog into an editable local product manager.</p><p>The app will receive a simple Add Product flow where a user can choose a product image, enter its name, price, description, and category, then save it directly from the application. New categories will no longer need to be written manually into the source code.</p><p>The products added through the form will appear in the same catalog and continue working with search, category filters, product details, favorites, and the shopping cart.</p><p>The first goal is not to build a remote store or connect a server. It is to make the offline catalog useful enough that its contents can be managed without opening the Flutter source code.</p><p>The cart gave the catalog a working shopping flow. The next step is to give the catalog an easier way to grow.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c6b646f917fc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Episode 20: Adding Favorites and Bottom Navigation to the Flutter Catalog]]></title>
            <link>https://medium.com/@lenakendari/episode-20-adding-favorites-and-bottom-navigation-to-the-flutter-catalog-2e0adf4c32c6?source=rss-932b58a7a66a------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e0adf4c32c6</guid>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[mobile-app-navigation]]></category>
            <dc:creator><![CDATA[Atelier Flutter]]></dc:creator>
            <pubDate>Sun, 19 Jul 2026 23:22:51 GMT</pubDate>
            <atom:updated>2026-07-19T23:22:51.148Z</atom:updated>
            <content:encoded><![CDATA[<p>I let users save products they like and switch between the full catalog and a dedicated favorites screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CIwk3Y-77uwyXpqC7rEHRg.png" /></figure><p>Episode 20 begins with a catalog that can finally do more than display products.</p><p>Users can search the inventory, filter by category, open a product, read the full details, and return to the grid.</p><p>That already feels like a real app.</p><p>But there is still one thing missing.</p><p>People need a way to remember the products they actually care about.</p><p>Right now, every visit starts the same way. Find the product, open the card, read the details, then repeat the whole scavenger hunt later.</p><p>So in this episode, I am adding favorites and bottom navigation.</p><p>Every product card will get a heart button.</p><p>The detail page will get one too.</p><p>Tapping the heart will add or remove that product from a dedicated Favorites screen, and the bottom navigation will let users move between the full catalog and their saved items.</p><p>The favorite data will stay in memory while the app is running.</p><p>Permanent storage comes later, because one episode should build a feature, not attempt to swallow the entire roadmap before lunch.</p><p>By the end of Episode 20, the app will have a much more personal flow:</p><p>Catalog → Save Product → Favorites → Open Product Detail.</p><p>The catalog already knows what it sells.</p><p>Now it starts remembering what the user likes.</p><p>Before adding favorites, I first inspect the two places that already control product interaction:</p><p>the catalog card and the product detail page.</p><p>The catalog card needs a heart button.</p><p>The detail page needs the same favorite state.</p><p>Both screens also need access to one shared collection of saved products.</p><p>That means this feature cannot live inside one isolated widget. The favorite state has to sit high enough in the app to serve the catalog, the detail page, and the new Favorites screen.</p><p>Before moving anything, I inspect the current class structure and navigation code.</p><p>This is less exciting than tapping a heart icon, but it prevents the heart from ending up in somebody’s shoe.</p><pre>cd ~/offline_product_catalog<br><br>grep -nE \<br>&quot;^class MyApp|^class MyHomePage|^class _MyHomePageState|^class ProductDetailPage|Navigator\.of|GridView\.builder|Scaffold\(&quot; \<br>lib/main.dart</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/815/1*_8OIM2l3uGp0xxSrJ_sYTQ.png" /><figcaption>The terminal maps the current catalog, detail page, and navigation structure before shared favorite state is introduced.</figcaption></figure><p>The command locates the app root, the catalog screen, the detail page, the existing navigation call, and the grid that builds every product card.</p><p>These are the exact sections that need to share the new favorite state.</p><p>The terminal confirms that the catalog, detail page, grid, and navigation are all connected through the same file.</p><p>Now I can decide where the favorite state should live.</p><p>If I store favorites inside one product card, the rest of the app will never hear about them.</p><p>If I store them only inside the detail page, the catalog screen will be equally confused.</p><p>So I need one shared collection that sits above both screens and can be updated from anywhere.</p><p>The simplest approach for this stage of the app is a `Set&lt;String&gt;` containing the names of favorited products.</p><p>Each product name is already unique, so the set can answer one important question quickly:</p><p>Is this product saved or not?</p><p>That gives the heart button a clear job and keeps the first version of Favorites easy to understand.</p><p>Before changing the app structure, I create a backup of `main.dart`.</p><p>This episode will touch the catalog screen, the detail page, and the navigation shell.</p><p>That is enough moving parts to justify one small parachute.</p><pre>cd ~/offline_product_catalog<br><br>cp lib/main.dart \<br>  lib/main.dart.backup_before_favorites</pre><pre>ls -lh lib/main.dart*</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/815/1*EWZ4y1ADrvDdSLuEdJL8CA.png" /><figcaption>A fresh backup protects the working catalog before shared favorites and bottom navigation are introduced.</figcaption></figure><p>The first search showed me where the important classes begin.</p><p>Now I inspect the section around `MyApp`, `MyHomePage`, and `_MyHomePageState` more closely.</p><p>I need the exact boundaries before moving shared state higher in the widget tree.</p><p>This is the part where a few careful line numbers save a great deal of future muttering.</p><pre>nl -ba lib/main.dart | sed -n &#39;280,620p&#39;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/815/1*GrvOX22hjNGydyhBPUQu3A.png" /><figcaption>The terminal displays the exact class boundaries that will be updated to share favorites across the catalog and detail page.</figcaption></figure><p>The terminal inspection gives me a clear picture of the current app structure.</p><p>MyHomePage already owns the search query, selected category, product grid, and navigation to the detail page.</p><p>That makes `_MyHomePageState` the simplest place to store the favorites for now.</p><p>I will add one `Set&lt;String&gt;` containing the names of saved products.</p><p>Both the catalog and the detail page will read from the same set.</p><p>When a heart button is pressed, the parent screen updates the collection and rebuilds the interface.</p><p>One shared list keeps every heart in agreement.</p><p>Without it, the catalog could say a product is saved while the detail page insists they have never met.</p><pre>Catalog tab<br>Favorites tab<br>Cart placeholder tab<br>Heart button on every product card<br>Heart button on ProductDetailPage<br>Open product details from Favorites<br>Empty Favorites screen<br>Bottom navigation</pre><pre>cd ~/offline_product_catalog<br><br>cp lib/main.dart \<br>  lib/main.dart.backup_before_favorites_navigation</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/815/1*ZIJDLT_jyD48oQ4hzbNMBQ.png" /><figcaption>A fresh backup preserves the working catalog before favorites and bottom navigation are added.</figcaption></figure><pre>python3 - &lt;&lt;&#39;PY&#39;<br>from pathlib import Path<br><br>file_path = Path(&quot;lib/main.dart&quot;)<br>text = file_path.read_text()<br><br><br>def find_class_range(source: str, class_name: str) -&gt; tuple[int, int]:<br>    marker = f&quot;class {class_name}&quot;<br>    start = source.find(marker)<br><br>    if start == -1:<br>        raise SystemExit(f&quot;{class_name} was not found.&quot;)<br><br>    opening = source.find(&quot;{&quot;, start)<br><br>    if opening == -1:<br>        raise SystemExit(f&quot;Opening brace for {class_name} was not found.&quot;)<br><br>    depth = 0<br><br>    for index in range(opening, len(source)):<br>        if source[index] == &quot;{&quot;:<br>            depth += 1<br>        elif source[index] == &quot;}&quot;:<br>            depth -= 1<br><br>            if depth == 0:<br>                return start, index + 1<br><br>    raise SystemExit(f&quot;Closing brace for {class_name} was not found.&quot;)<br><br><br>detail_start, detail_end = find_class_range(<br>    text,<br>    &quot;ProductDetailPage&quot;,<br>)<br><br>new_detail_page = r&quot;&quot;&quot;class ProductDetailPage extends StatelessWidget {<br>  const ProductDetailPage({<br>    super.key,<br>    required this.product,<br>    required this.isFavorite,<br>    required this.onToggleFavorite,<br>  });<br><br>  final Product product;<br>  final bool isFavorite;<br>  final VoidCallback onToggleFavorite;<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(<br>        backgroundColor:<br>            Theme.of(context).colorScheme.inversePrimary,<br>        title: Text(product.name),<br>        actions: [<br>          IconButton(<br>            tooltip: isFavorite<br>                ? &#39;Remove from favorites&#39;<br>                : &#39;Add to favorites&#39;,<br>            onPressed: onToggleFavorite,<br>            icon: Icon(<br>              isFavorite<br>                  ? Icons.favorite<br>                  : Icons.favorite_border,<br>              color: isFavorite ? Colors.red : null,<br>            ),<br>          ),<br>        ],<br>      ),<br>      body: LayoutBuilder(<br>        builder: (context, constraints) {<br>          final isWide = constraints.maxWidth &gt;= 760;<br><br>          final imagePanel = Container(<br>            width: double.infinity,<br>            constraints: const BoxConstraints(<br>              minHeight: 320,<br>            ),<br>            decoration: BoxDecoration(<br>              color: const Color(0xFFF7F5FA),<br>              borderRadius: BorderRadius.circular(20),<br>            ),<br>            child: Padding(<br>              padding: const EdgeInsets.all(24),<br>              child: Image.asset(<br>                product.imagePath,<br>                fit: BoxFit.contain,<br>              ),<br>            ),<br>          );<br><br>          final informationPanel = Column(<br>            crossAxisAlignment: CrossAxisAlignment.start,<br>            children: [<br>              Container(<br>                padding: const EdgeInsets.symmetric(<br>                  horizontal: 12,<br>                  vertical: 6,<br>                ),<br>                decoration: BoxDecoration(<br>                  color: const Color(0xFFEDE7F6),<br>                  borderRadius: BorderRadius.circular(20),<br>                ),<br>                child: Text(<br>                  product.category,<br>                  style: const TextStyle(<br>                    color: Color(0xFF5E35B1),<br>                    fontWeight: FontWeight.w700,<br>                  ),<br>                ),<br>              ),<br>              const SizedBox(height: 18),<br>              Text(<br>                product.name,<br>                style: const TextStyle(<br>                  fontSize: 30,<br>                  fontWeight: FontWeight.bold,<br>                ),<br>              ),<br>              const SizedBox(height: 10),<br>              Text(<br>                product.price,<br>                style: const TextStyle(<br>                  fontSize: 24,<br>                  fontWeight: FontWeight.bold,<br>                  color: Color(0xFF5E35B1),<br>                ),<br>              ),<br>              const SizedBox(height: 20),<br>              Text(<br>                product.description,<br>                style: const TextStyle(<br>                  fontSize: 17,<br>                  height: 1.5,<br>                ),<br>              ),<br>              const SizedBox(height: 24),<br>              const Row(<br>                children: [<br>                  Icon(<br>                    Icons.offline_bolt_outlined,<br>                    color: Color(0xFF5E35B1),<br>                  ),<br>                  SizedBox(width: 10),<br>                  Expanded(<br>                    child: Text(<br>                      &#39;This product information is available offline.&#39;,<br>                      style: TextStyle(<br>                        fontWeight: FontWeight.w600,<br>                      ),<br>                    ),<br>                  ),<br>                ],<br>              ),<br>              const SizedBox(height: 24),<br>              FilledButton.icon(<br>                onPressed: onToggleFavorite,<br>                icon: Icon(<br>                  isFavorite<br>                      ? Icons.favorite<br>                      : Icons.favorite_border,<br>                ),<br>                label: Text(<br>                  isFavorite<br>                      ? &#39;Remove from Favorites&#39;<br>                      : &#39;Add to Favorites&#39;,<br>                ),<br>              ),<br>            ],<br>          );<br><br>          return SingleChildScrollView(<br>            padding: const EdgeInsets.all(24),<br>            child: isWide<br>                ? Row(<br>                    crossAxisAlignment:<br>                        CrossAxisAlignment.start,<br>                    children: [<br>                      Expanded(child: imagePanel),<br>                      const SizedBox(width: 32),<br>                      Expanded(child: informationPanel),<br>                    ],<br>                  )<br>                : Column(<br>                    crossAxisAlignment:<br>                        CrossAxisAlignment.start,<br>                    children: [<br>                      imagePanel,<br>                      const SizedBox(height: 24),<br>                      informationPanel,<br>                    ],<br>                  ),<br>          );<br>        },<br>      ),<br>    );<br>  }<br>}&quot;&quot;&quot;<br><br>text = (<br>    text[:detail_start]<br>    + new_detail_page<br>    + text[detail_end:]<br>)<br><br>home_start, home_end = find_class_range(<br>    text,<br>    &quot;_MyHomePageState&quot;,<br>)<br><br>new_home_state = r&quot;&quot;&quot;class _MyHomePageState extends State&lt;MyHomePage&gt; {<br>  String _selectedCategory = &#39;All&#39;;<br>  String _searchQuery = &#39;&#39;;<br>  int _selectedTab = 0;<br><br>  final Set&lt;String&gt; _favoriteProductNames = {};<br><br>  bool _isFavorite(Product product) {<br>    return _favoriteProductNames.contains(product.name);<br>  }<br><br>  void _toggleFavorite(Product product) {<br>    setState(() {<br>      if (_isFavorite(product)) {<br>        _favoriteProductNames.remove(product.name);<br>      } else {<br>        _favoriteProductNames.add(product.name);<br>      }<br>    });<br>  }<br><br>  void _openProductDetail(Product product) {<br>    Navigator.of(context).push(<br>      MaterialPageRoute(<br>        builder: (context) =&gt; ProductDetailPage(<br>          product: product,<br>          isFavorite: _isFavorite(product),<br>          onToggleFavorite: () {<br>            _toggleFavorite(product);<br>          },<br>        ),<br>      ),<br>    ).then((_) {<br>      if (mounted) {<br>        setState(() {});<br>      }<br>    });<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    final pages = [<br>      _buildCatalogPage(),<br>      _buildFavoritesPage(),<br>      _buildCartPlaceholder(),<br>    ];<br><br>    final titles = [<br>      widget.title,<br>      &#39;Favorites&#39;,<br>      &#39;Cart&#39;,<br>    ];<br><br>    return Scaffold(<br>      appBar: AppBar(<br>        backgroundColor:<br>            Theme.of(context).colorScheme.inversePrimary,<br>        title: Text(titles[_selectedTab]),<br>      ),<br>      body: IndexedStack(<br>        index: _selectedTab,<br>        children: pages,<br>      ),<br>      bottomNavigationBar: NavigationBar(<br>        selectedIndex: _selectedTab,<br>        onDestinationSelected: (index) {<br>          setState(() {<br>            _selectedTab = index;<br>          });<br>        },<br>        destinations: const [<br>          NavigationDestination(<br>            icon: Icon(Icons.storefront_outlined),<br>            selectedIcon: Icon(Icons.storefront),<br>            label: &#39;Catalog&#39;,<br>          ),<br>          NavigationDestination(<br>            icon: Icon(Icons.favorite_border),<br>            selectedIcon: Icon(Icons.favorite),<br>            label: &#39;Favorites&#39;,<br>          ),<br>          NavigationDestination(<br>            icon: Icon(Icons.shopping_cart_outlined),<br>            selectedIcon: Icon(Icons.shopping_cart),<br>            label: &#39;Cart&#39;,<br>          ),<br>        ],<br>      ),<br>    );<br>  }<br><br>  Widget _buildCatalogPage() {<br>    const categories = [<br>      &#39;All&#39;,<br>      &#39;Audio&#39;,<br>      &#39;Wearables&#39;,<br>      &#39;Photography&#39;,<br>      &#39;Computers&#39;,<br>      &#39;Accessories&#39;,<br>    ];<br><br>    final normalizedQuery =<br>        _searchQuery.trim().toLowerCase();<br><br>    final filteredProducts = products.where((product) {<br>      final matchesCategory =<br>          _selectedCategory == &#39;All&#39; ||<br>          product.category == _selectedCategory;<br><br>      final matchesSearch =<br>          normalizedQuery.isEmpty ||<br>          product.name<br>              .toLowerCase()<br>              .contains(normalizedQuery) ||<br>          product.description<br>              .toLowerCase()<br>              .contains(normalizedQuery);<br><br>      return matchesCategory &amp;&amp; matchesSearch;<br>    }).toList();<br><br>    return LayoutBuilder(<br>      builder: (context, constraints) {<br>        final width = constraints.maxWidth;<br><br>        final crossAxisCount = width &gt;= 1100<br>            ? 4<br>            : width &gt;= 700<br>                ? 3<br>                : 2;<br><br>        final childAspectRatio =<br>            width &gt;= 700 ? 0.78 : 0.67;<br><br>        return SingleChildScrollView(<br>          padding: const EdgeInsets.all(20),<br>          child: Column(<br>            crossAxisAlignment:<br>                CrossAxisAlignment.start,<br>            children: [<br>              const Text(<br>                &#39;Our Products&#39;,<br>                style: TextStyle(<br>                  fontSize: 28,<br>                  fontWeight: FontWeight.bold,<br>                ),<br>              ),<br>              const SizedBox(height: 6),<br>              const Text(<br>                &#39;Browse products available offline.&#39;,<br>                style: TextStyle(fontSize: 16),<br>              ),<br>              const SizedBox(height: 20),<br>              TextField(<br>                onChanged: (value) {<br>                  setState(() {<br>                    _searchQuery = value;<br>                  });<br>                },<br>                decoration: InputDecoration(<br>                  hintText: &#39;Search products...&#39;,<br>                  prefixIcon:<br>                      const Icon(Icons.search),<br>                  border: OutlineInputBorder(<br>                    borderRadius:<br>                        BorderRadius.circular(14),<br>                  ),<br>                ),<br>              ),<br>              const SizedBox(height: 18),<br>              SingleChildScrollView(<br>                scrollDirection: Axis.horizontal,<br>                child: Row(<br>                  children: categories.map((category) {<br>                    final isSelected =<br>                        category == _selectedCategory;<br><br>                    return Padding(<br>                      padding:<br>                          const EdgeInsets.only(right: 10),<br>                      child: ChoiceChip(<br>                        label: Text(category),<br>                        selected: isSelected,<br>                        selectedColor:<br>                            const Color(0xFF5E35B1),<br>                        labelStyle: TextStyle(<br>                          color: isSelected<br>                              ? Colors.white<br>                              : Colors.black87,<br>                          fontWeight:<br>                              FontWeight.w600,<br>                        ),<br>                        onSelected: (_) {<br>                          setState(() {<br>                            _selectedCategory =<br>                                category;<br>                          });<br>                        },<br>                      ),<br>                    );<br>                  }).toList(),<br>                ),<br>              ),<br>              const SizedBox(height: 22),<br>              Text(<br>                &#39;${filteredProducts.length} products&#39;,<br>                style: const TextStyle(<br>                  fontWeight: FontWeight.w600,<br>                  color: Colors.black54,<br>                ),<br>              ),<br>              const SizedBox(height: 12),<br>              if (filteredProducts.isEmpty)<br>                const Padding(<br>                  padding:<br>                      EdgeInsets.symmetric(vertical: 60),<br>                  child: Center(<br>                    child: Column(<br>                      children: [<br>                        Icon(<br>                          Icons.search_off,<br>                          size: 52,<br>                          color: Colors.black38,<br>                        ),<br>                        SizedBox(height: 12),<br>                        Text(<br>                          &#39;No products found.&#39;,<br>                          style: TextStyle(<br>                            fontSize: 17,<br>                            fontWeight:<br>                                FontWeight.w600,<br>                          ),<br>                        ),<br>                      ],<br>                    ),<br>                  ),<br>                )<br>              else<br>                GridView.builder(<br>                  shrinkWrap: true,<br>                  physics:<br>                      const NeverScrollableScrollPhysics(),<br>                  itemCount: filteredProducts.length,<br>                  gridDelegate:<br>                      SliverGridDelegateWithFixedCrossAxisCount(<br>                    crossAxisCount: crossAxisCount,<br>                    crossAxisSpacing: 14,<br>                    mainAxisSpacing: 14,<br>                    childAspectRatio: childAspectRatio,<br>                  ),<br>                  itemBuilder: (context, index) {<br>                    final product =<br>                        filteredProducts[index];<br>                    final favorite =<br>                        _isFavorite(product);<br><br>                    return Card(<br>                      clipBehavior: Clip.antiAlias,<br>                      elevation: 1,<br>                      shape: RoundedRectangleBorder(<br>                        borderRadius:<br>                            BorderRadius.circular(16),<br>                      ),<br>                      child: InkWell(<br>                        onTap: () {<br>                          _openProductDetail(product);<br>                        },<br>                        child: Column(<br>                          crossAxisAlignment:<br>                              CrossAxisAlignment.start,<br>                          children: [<br>                            Expanded(<br>                              child: Stack(<br>                                children: [<br>                                  Positioned.fill(<br>                                    child: Container(<br>                                      color: const Color(<br>                                        0xFFF7F5FA,<br>                                      ),<br>                                      child: Image.asset(<br>                                        product.imagePath,<br>                                        fit: BoxFit.contain,<br>                                      ),<br>                                    ),<br>                                  ),<br>                                  Positioned(<br>                                    top: 8,<br>                                    right: 8,<br>                                    child: IconButton.filledTonal(<br>                                      tooltip: favorite<br>                                          ? &#39;Remove from favorites&#39;<br>                                          : &#39;Add to favorites&#39;,<br>                                      onPressed: () {<br>                                        _toggleFavorite(product);<br>                                      },<br>                                      icon: Icon(<br>                                        favorite<br>                                            ? Icons.favorite<br>                                            : Icons.favorite_border,<br>                                        color: favorite<br>                                            ? Colors.red<br>                                            : null,<br>                                      ),<br>                                    ),<br>                                  ),<br>                                ],<br>                              ),<br>                            ),<br>                            Padding(<br>                              padding:<br>                                  const EdgeInsets.fromLTRB(<br>                                12,<br>                                12,<br>                                12,<br>                                14,<br>                              ),<br>                              child: Column(<br>                                crossAxisAlignment:<br>                                    CrossAxisAlignment.start,<br>                                children: [<br>                                  Container(<br>                                    padding:<br>                                        const EdgeInsets.symmetric(<br>                                      horizontal: 8,<br>                                      vertical: 3,<br>                                    ),<br>                                    decoration:<br>                                        BoxDecoration(<br>                                      color: const Color(<br>                                        0xFFEDE7F6,<br>                                      ),<br>                                      borderRadius:<br>                                          BorderRadius.circular(<br>                                        20,<br>                                      ),<br>                                    ),<br>                                    child: Text(<br>                                      product.category,<br>                                      style:<br>                                          const TextStyle(<br>                                        color: Color(<br>                                          0xFF5E35B1,<br>                                        ),<br>                                        fontSize: 11,<br>                                        fontWeight:<br>                                            FontWeight.w700,<br>                                      ),<br>                                    ),<br>                                  ),<br>                                  const SizedBox(height: 8),<br>                                  Text(<br>                                    product.name,<br>                                    maxLines: 1,<br>                                    overflow:<br>                                        TextOverflow.ellipsis,<br>                                    style:<br>                                        const TextStyle(<br>                                      fontSize: 15,<br>                                      fontWeight:<br>                                          FontWeight.bold,<br>                                    ),<br>                                  ),<br>                                  const SizedBox(height: 4),<br>                                  Text(<br>                                    product.description,<br>                                    maxLines: 2,<br>                                    overflow:<br>                                        TextOverflow.ellipsis,<br>                                    style:<br>                                        const TextStyle(<br>                                      fontSize: 12,<br>                                      color: Colors.black54,<br>                                    ),<br>                                  ),<br>                                  const SizedBox(height: 10),<br>                                  Text(<br>                                    product.price,<br>                                    style:<br>                                        const TextStyle(<br>                                      color: Color(<br>                                        0xFF5E35B1,<br>                                      ),<br>                                      fontSize: 16,<br>                                      fontWeight:<br>                                          FontWeight.bold,<br>                                    ),<br>                                  ),<br>                                ],<br>                              ),<br>                            ),<br>                          ],<br>                        ),<br>                      ),<br>                    );<br>                  },<br>                ),<br>            ],<br>          ),<br>        );<br>      },<br>    );<br>  }<br><br>  Widget _buildFavoritesPage() {<br>    final favoriteProducts = products<br>        .where(_isFavorite)<br>        .toList();<br><br>    if (favoriteProducts.isEmpty) {<br>      return const Center(<br>        child: Padding(<br>          padding: EdgeInsets.all(32),<br>          child: Column(<br>            mainAxisSize: MainAxisSize.min,<br>            children: [<br>              Icon(<br>                Icons.favorite_border,<br>                size: 64,<br>                color: Colors.black38,<br>              ),<br>              SizedBox(height: 16),<br>              Text(<br>                &#39;No favorites yet.&#39;,<br>                style: TextStyle(<br>                  fontSize: 22,<br>                  fontWeight: FontWeight.bold,<br>                ),<br>              ),<br>              SizedBox(height: 8),<br>              Text(<br>                &#39;Save a product from the catalog and it will appear here.&#39;,<br>                textAlign: TextAlign.center,<br>              ),<br>            ],<br>          ),<br>        ),<br>      );<br>    }<br><br>    return ListView.separated(<br>      padding: const EdgeInsets.all(20),<br>      itemCount: favoriteProducts.length,<br>      separatorBuilder: (_, _) =&gt;<br>          const SizedBox(height: 12),<br>      itemBuilder: (context, index) {<br>        final product = favoriteProducts[index];<br><br>        return Card(<br>          child: ListTile(<br>            onTap: () {<br>              _openProductDetail(product);<br>            },<br>            leading: SizedBox(<br>              width: 58,<br>              height: 58,<br>              child: Image.asset(<br>                product.imagePath,<br>                fit: BoxFit.contain,<br>              ),<br>            ),<br>            title: Text(product.name),<br>            subtitle: Text(<br>              &#39;${product.category} • ${product.price}&#39;,<br>            ),<br>            trailing: IconButton(<br>              tooltip: &#39;Remove from favorites&#39;,<br>              onPressed: () {<br>                _toggleFavorite(product);<br>              },<br>              icon: const Icon(<br>                Icons.favorite,<br>                color: Colors.red,<br>              ),<br>            ),<br>          ),<br>        );<br>      },<br>    );<br>  }<br><br>  Widget _buildCartPlaceholder() {<br>    return const Center(<br>      child: Padding(<br>        padding: EdgeInsets.all(32),<br>        child: Column(<br>          mainAxisSize: MainAxisSize.min,<br>          children: [<br>            Icon(<br>              Icons.shopping_cart_outlined,<br>              size: 64,<br>              color: Colors.black38,<br>            ),<br>            SizedBox(height: 16),<br>            Text(<br>              &#39;Your cart is empty.&#39;,<br>              style: TextStyle(<br>                fontSize: 22,<br>                fontWeight: FontWeight.bold,<br>              ),<br>            ),<br>            SizedBox(height: 8),<br>            Text(<br>              &#39;Shopping cart features arrive in Episode 21.&#39;,<br>              textAlign: TextAlign.center,<br>            ),<br>          ],<br>        ),<br>      ),<br>    );<br>  }<br>}&quot;&quot;&quot;<br><br>text = (<br>    text[:home_start]<br>    + new_home_state<br>    + text[home_end:]<br>)<br><br>file_path.write_text(text)<br><br>print(&quot;Shared favorites state created.&quot;)<br>print(&quot;Catalog, Favorites, and Cart tabs added.&quot;)<br>print(&quot;Heart buttons connected across cards and details.&quot;)<br>PY</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/815/1*hpc5o9IhOUWd-iHzcUKTTQ.png" /><figcaption>The terminal creates shared favorites, three bottom-navigation destinations, and synchronized heart buttons across the app.</figcaption></figure><p>The patch creates one shared favorites collection and connects it to every part of the app.</p><p>Product cards now show heart buttons.</p><p>The detail page can add or remove the same product.</p><p>The Favorites tab reads from the shared collection, and every saved item can still open its detail page.</p><p>A third Cart tab is also added as a clean placeholder for the next episode.</p><p>The app now has a real navigation shell instead of asking every feature to crowd onto one screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/815/1*RMY6Q8JwuEHORFDPLBbdww.png" /><figcaption>No issues found!</figcaption></figure><p>The analyzer is clean, which means the new navigation shell and favorites code are structurally valid.</p><p>Now I need to test the behavior that static analysis cannot prove.</p><p>A green analyzer can confirm that the code makes sense to Dart.</p><p>It cannot confirm that a heart actually behaves like a heart instead of becoming a decorative tomato.</p><p>When the app reloads, three destinations appear at the bottom of the screen:</p><p>Catalog, Favorites, and Cart.</p><p>The Catalog tab keeps the twenty-product grid, search field, and category filters from the previous episodes.</p><p>Favorites begins with an empty state.</p><p>Cart also begins empty, but it already has a permanent place in the app for the shopping features coming next.</p><p>The interface now has clear destinations instead of asking every feature to live in one increasingly crowded room.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/1*PDslxBwRlU8ZOCVDLhmtcA.png" /><figcaption>The app now has a three-tab navigation shell for the catalog, saved products, and the upcoming shopping cart.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/1*cH7QCUlcIN97vnJB1jpXrw.png" /><figcaption>The Favorites tab begins with a clear empty state before any products are saved.</figcaption></figure><p>I return to the catalog and tap the heart on Wireless Headphones.</p><p>The outlined heart becomes filled, confirming that the product has been added to the shared favorites collection.</p><p>I then open the Favorites tab again.</p><p>Wireless Headphones appears with its image, category, and price.</p><p>The product did not move to a separate duplicate list. The Favorites screen is reading the same Product object from the original catalog data.</p><p>A favorite should not become a dead bookmark, so I tap Wireless Headphones from the saved list.</p><p>The same reusable ProductDetailPage opens with the larger image and complete product information.</p><p>This confirms that Favorites is connected to the existing navigation flow rather than becoming a separate display-only screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/1*l2ojMHzBfYUA3T7PCOyJHA.png" /><figcaption>Selecting a saved product opens the same reusable detail page used by the main catalog.</figcaption></figure><p>The updated product detail page now includes an Add to Favorites button below the product information.</p><p>The layout remains responsive, so the larger product image, category, price, description, and favorite action still fit comfortably on a narrow browser window.</p><p>The interface looks correct, but appearance is only half the test.</p><p>Next, I press the button and check whether the detail page, catalog card, and Favorites screen all agree on the new state.</p><p>The detail page is visible and the new favorite button fits neatly below the product information.</p><p>But before calling the feature complete, I inspect how the button receives its state.</p><p>ProductDetailPage is still a StatelessWidget.</p><p>That means it receives the favorite value when the page opens, but it cannot repaint itself after the value changes.</p><p>The shared favorites collection updates correctly behind the page, while the button may continue displaying its old label.</p><p>The code compiles, but the interface has not received the memo.</p><p>To fix that, I convert ProductDetailPage into a StatefulWidget and keep a small local favorite value synchronized with the shared collection.</p><pre>cd ~/offline_product_catalog<br><br>python3 - &lt;&lt;&#39;PY&#39;<br>from pathlib import Path<br><br>file_path = Path(&quot;lib/main.dart&quot;)<br>text = file_path.read_text()<br><br>old = &quot;&quot;&quot;class ProductDetailPage extends StatelessWidget {<br>  const ProductDetailPage({<br>    super.key,<br>    required this.product,<br>    required this.isFavorite,<br>    required this.onToggleFavorite,<br>  });<br><br>  final Product product;<br>  final bool isFavorite;<br>  final VoidCallback onToggleFavorite;<br><br>  @override<br>  Widget build(BuildContext context) {<br>&quot;&quot;&quot;<br><br>new = &quot;&quot;&quot;class ProductDetailPage extends StatefulWidget {<br>  const ProductDetailPage({<br>    super.key,<br>    required this.product,<br>    required this.isFavorite,<br>    required this.onToggleFavorite,<br>  });<br><br>  final Product product;<br>  final bool isFavorite;<br>  final VoidCallback onToggleFavorite;<br><br>  @override<br>  State&lt;ProductDetailPage&gt; createState() =&gt; _ProductDetailPageState();<br>}<br><br>class _ProductDetailPageState extends State&lt;ProductDetailPage&gt; {<br>  late bool _favorite;<br><br>  Product get product =&gt; widget.product;<br>  bool get isFavorite =&gt; _favorite;<br>  VoidCallback get onToggleFavorite =&gt; _handleToggleFavorite;<br><br>  @override<br>  void initState() {<br>    super.initState();<br>    _favorite = widget.isFavorite;<br>  }<br><br>  void _handleToggleFavorite() {<br>    widget.onToggleFavorite();<br><br>    setState(() {<br>      _favorite = !_favorite;<br>    });<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>&quot;&quot;&quot;<br><br>if old not in text:<br>    raise SystemExit(<br>        &quot;The expected ProductDetailPage header was not found. &quot;<br>        &quot;No file changes were made.&quot;<br>    )<br><br>text = text.replace(old, new, 1)<br>file_path.write_text(text)<br><br>print(&quot;ProductDetailPage is now stateful.&quot;)<br>print(&quot;The favorite button can update immediately.&quot;)<br>PY</pre><p>The patch keeps the existing detail-page layout intact.</p><p>It only changes how the page manages its favorite value.</p><p>The page still reports every change to the shared collection in MyHomePage, but it now also rebuilds its own button immediately.</p><p>The local interface and the shared app state can finally nod at each other in agreement.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/1*M2KwbOp7F1RrEj7Hf9jnNQ.png" /><figcaption>ProductDetailPage is converted into a stateful screen so its favorite button can update without reopening the page.</figcaption></figure><pre>dart format lib/main.dart<br>flutter analyze</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/1*azagEMhPLDRRaY5PUZPZAQ.png" /><figcaption>Flutter confirms that the synchronized favorite-state fix introduces no analyzer issues.</figcaption></figure><p>I format the updated file and run Flutter’s analyzer again.</p><p>The analyzer returns with no issues, confirming that the new stateful detail page is structurally valid.</p><p>Now the remaining test is behavioral: pressing the button must update the detail page, catalog card, and Favorites screen together.</p><p>I open Wireless Headphones and press Add to Favorites.</p><p>This time, the change appears immediately.</p><p>The outlined heart becomes filled, and the button changes from Add to Favorites to Remove from Favorites without closing the page.</p><p>The detail page is no longer displaying a frozen copy of the original state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/669/1*pLlXAd_q09sl3pTJIxnLNA.png" /><figcaption>The detail page updates immediately after Wireless Headphones is added to Favorites.</figcaption></figure><p>The Favorites tab now contains Wireless Headphones with its image, category, and price.</p><p>I can open the product from this screen, return to the catalog, or remove it directly from the saved list.</p><p>Favorites is now a working destination rather than a decorative heart-shaped promise.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/669/1*PHUecd_DWPs-zSSokvRaMw.png" /><figcaption>The catalog card preserves the favorite state created from the product detail page.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/669/1*z4iQJyb7VlvNpXknpUky5A.png" /><figcaption>The Cart tab reserves a permanent destination for the shopping features coming in Episode 21.</figcaption></figure><p>The third destination is Cart.</p><p>It currently displays a clear empty state because the shopping-cart logic belongs to the next episode.</p><p>Adding the destination now gives the app a stable navigation structure before quantities, totals, and checkout controls arrive.</p><p>The storefront has its rooms. Next, one of them gets a cash register.</p><p>The browser confirms that the feature works.</p><p>Now I return to the code and inspect the pieces responsible for the result.</p><p>Episode 20 added more than a few heart icons.</p><p>The app now has shared favorite state, reusable toggle logic, synchronized detail-page controls, a dedicated Favorites screen, and a three-destination navigation shell.</p><p>Instead of reading the entire file from top to bottom, I use the terminal to locate those exact sections.</p><pre>cd ~/offline_product_catalog<br><br>grep -nE \<br>&quot;_ProductDetailPageState|_favoriteProductNames|_isFavorite|_toggleFavorite|NavigationBar|_buildFavoritesPage|_buildCartPlaceholder&quot; \<br>lib/main.dart</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/706/1*UVGn-A6_7kwzerR98AzG1Q.png" /><figcaption>The terminal locates every major section added for favorites and bottom navigation.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/706/1*0-5BKkepuYcb2dotLwsfsw.png" /><figcaption>One shared Set and one toggle method keep favorite state consistent across the app.</figcaption></figure><p>The shared favorite state is intentionally small.</p><p>A Set stores the names of saved products and automatically prevents duplicates.</p><p>The `_isFavorite` method checks whether a product is already saved.</p><p>The `_toggleFavorite` method then performs one of two actions: remove the existing name or add the new one.</p><p>Because the method calls setState, every screen connected to this collection can rebuild with the latest result.</p><p>The NavigationBar gives the app three permanent destinations.</p><p>Catalog remains the main shopping area.</p><p>Favorites displays saved products.</p><p>Cart is already part of the navigation structure, even though its full shopping logic will arrive in the next episode.</p><p>The selected index determines which page appears inside the IndexedStack.</p><p>Using IndexedStack also preserves the catalog state while I move between tabs, so the selected category and current search do not vanish every time I visit Favorites.</p><p>For the final test, I save two products from the catalog.</p><p>Both appear inside Favorites.</p><p>I open one of them, remove it from the detail page, and return to the saved list.</p><p>Only the remaining product is displayed.</p><p>I then visit Cart and return to Catalog.</p><p>The search field, category selection, navigation shell, and favorite state continue working together.</p><p>Episode 20 is no longer a collection of isolated interface pieces.</p><p>It is one connected user flow.</p><p>Episode 20 gives the offline catalog a memory and a proper navigation system.</p><p>Users can now save products directly from the catalog, manage the same favorite state from the detail page, and revisit everything from a dedicated Favorites screen.</p><p>The app also has three stable destinations:</p><p>Catalog, Favorites, and Cart.</p><p>Favorites currently remain in memory while the application is running. Closing or restarting the app will clear them.</p><p>That limitation is intentional.</p><p>Before saving data permanently, the application first needs a complete shopping flow worth preserving.</p><p>In Episode 21, I will turn the empty Cart tab into a working shopping cart.</p><p>Products will gain Add to Cart buttons, repeated items will increase their quantities, and the cart will calculate running totals instead of merely sitting there looking spacious.</p><p>The catalog can already remember what the user likes.</p><p>Next, it learns what the user wants to buy.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e0adf4c32c6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Episode 19: Opening a Product Detail Page From the Flutter Grid]]></title>
            <link>https://medium.com/@lenakendari/episode-19-opening-a-product-detail-page-from-the-flutter-grid-ae6d848740ee?source=rss-932b58a7a66a------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae6d848740ee</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[mobile-app-navigation]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Atelier Flutter]]></dc:creator>
            <pubDate>Sat, 18 Jul 2026 23:10:29 GMT</pubDate>
            <atom:updated>2026-07-18T23:10:29.792Z</atom:updated>
            <content:encoded><![CDATA[<p>I make every product card clickable and open a reusable detail page with a larger image, category, price, description, and smooth back navigation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qArcS7YwN1bXT7cgR0D0Uw.png" /></figure><p>Episode 19 begins with a catalog that finally feels like a real app.</p><p>There are twenty products on the screen. Search works. Category filters work. Every card has its own image, name, description, category, and price.</p><p>But the cards still have one awkward problem.</p><p>They look clickable.</p><p>They feel clickable.</p><p>They are absolutely not clickable.</p><p>Right now, tapping Wireless Headphones does nothing. Tapping Digital Camera gets the same response as tapping a picture frame in a waiting room.</p><p>So in this episode, I am fixing that.</p><p>Each product card will open a dedicated detail page with a larger image, full product information, category, price, and a clear way back to the catalog.</p><p>I am not building twenty separate pages.</p><p>That would be less software architecture and more copy-and-paste cardio.</p><p>Instead, I will build one reusable detail page that changes automatically based on the product the user selects.</p><p>By the end of this episode, the app will have a real navigation flow:</p><p>Catalog grid → Product detail → Back to catalog.</p><p>The storefront is ready.</p><p>Now the products finally get their own rooms.</p><p>Before adding a detail page, I first locate the exact section that builds each product card.</p><p>The grid already knows which product belongs to each position. That makes it the perfect place to add navigation.</p><p>I do not need to rebuild the catalog.</p><p>I only need to teach each card what to do when someone taps it.</p><p>Tiny change in behavior. Big change in how the app feels.</p><pre>cd ~/offline_product_catalog<br><br>grep -nE \<br>&quot;GridView.builder|final product =|return Card|Image.asset|product.name&quot; \<br>lib/main.dart</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/1*PikJPqq8imtpw-Ikb8yRVg.png" /><figcaption>The terminal locates the reusable product card inside the grid, which is where the new tap behavior will be added.</figcaption></figure><pre>nl -ba lib/main.dart | sed -n &#39;300,430p&#39;</pre><p>The terminal now shows the full product card block.</p><p>The grid begins at line 372, and each product is pulled from `filteredProducts` on line 383.</p><p>The card itself starts on line 385, while the local product image appears a few lines later.</p><p>This gives me the exact place to add tap behavior without disturbing search, category filters, or the responsive grid.</p><p>The card is already doing most of the work.</p><p>It just needs to learn what “open” means.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/1*aBHirz__lOqd7yoXLJJgkQ.png" /><figcaption>The terminal reveals the exact product card boundary inside the responsive grid before navigation is added.</figcaption></figure><pre>nl -ba lib/main.dart | sed -n &#39;430,520p&#39;</pre><p>The second terminal view reveals the rest of the card.</p><p>The product name, description, and price all live inside the same reusable block, and the card closes at line 474.</p><p>Now I know exactly where to add the tap behavior without touching the search field, category filters, or grid logic.</p><p>The card has clear walls.</p><p>Time to add a door.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/1*cdKhuWklX0dcD3NXEKkAqQ.png" /><figcaption>The complete product card is now visible from its image section to the final closing line, ready for navigation.</figcaption></figure><p>The next step is not to build twenty separate screens.</p><p>Instead, I will create one reusable `ProductDetailPage` that receives a Product object.</p><p>The page will read the selected product’s image, name, category, description, and price directly from that object.</p><p>That means Wireless Headphones and Digital Camera can share the same screen structure while still showing completely different information.</p><p>One page does the work.</p><p>Twenty products get the benefit.</p><p>Copy-and-paste can take the afternoon off.</p><pre>cp lib/main.dart lib/main.dart.backup_before_product_detail</pre><pre>python3 - &lt;&lt;&#39;PY&#39;<br>from pathlib import Path<br><br>file_path = Path(&quot;lib/main.dart&quot;)<br>text = file_path.read_text()<br><br>detail_marker = &quot;class MyApp extends StatelessWidget {&quot;<br><br>detail_page = r&quot;&quot;&quot;<br>class ProductDetailPage extends StatelessWidget {<br>  const ProductDetailPage({<br>    super.key,<br>    required this.product,<br>  });<br><br>  final Product product;<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(<br>        backgroundColor:<br>            Theme.of(context).colorScheme.inversePrimary,<br>        title: Text(product.name),<br>      ),<br>      body: LayoutBuilder(<br>        builder: (context, constraints) {<br>          final isWide = constraints.maxWidth &gt;= 760;<br><br>          final imagePanel = Container(<br>            width: double.infinity,<br>            constraints: const BoxConstraints(<br>              minHeight: 320,<br>            ),<br>            decoration: BoxDecoration(<br>              color: const Color(0xFFF7F5FA),<br>              borderRadius: BorderRadius.circular(20),<br>            ),<br>            child: Padding(<br>              padding: const EdgeInsets.all(24),<br>              child: Image.asset(<br>                product.imagePath,<br>                fit: BoxFit.contain,<br>              ),<br>            ),<br>          );<br><br>          final informationPanel = Column(<br>            crossAxisAlignment: CrossAxisAlignment.start,<br>            children: [<br>              Container(<br>                padding: const EdgeInsets.symmetric(<br>                  horizontal: 12,<br>                  vertical: 6,<br>                ),<br>                decoration: BoxDecoration(<br>                  color: const Color(0xFFEDE7F6),<br>                  borderRadius: BorderRadius.circular(20),<br>                ),<br>                child: Text(<br>                  product.category,<br>                  style: const TextStyle(<br>                    color: Color(0xFF5E35B1),<br>                    fontWeight: FontWeight.w700,<br>                  ),<br>                ),<br>              ),<br>              const SizedBox(height: 18),<br>              Text(<br>                product.name,<br>                style: const TextStyle(<br>                  fontSize: 30,<br>                  fontWeight: FontWeight.bold,<br>                ),<br>              ),<br>              const SizedBox(height: 10),<br>              Text(<br>                product.price,<br>                style: const TextStyle(<br>                  fontSize: 24,<br>                  fontWeight: FontWeight.bold,<br>                  color: Color(0xFF5E35B1),<br>                ),<br>              ),<br>              const SizedBox(height: 20),<br>              Text(<br>                product.description,<br>                style: const TextStyle(<br>                  fontSize: 17,<br>                  height: 1.5,<br>                ),<br>              ),<br>              const SizedBox(height: 24),<br>              const Row(<br>                children: [<br>                  Icon(<br>                    Icons.offline_bolt_outlined,<br>                    color: Color(0xFF5E35B1),<br>                  ),<br>                  SizedBox(width: 10),<br>                  Expanded(<br>                    child: Text(<br>                      &#39;This product information is available offline.&#39;,<br>                      style: TextStyle(<br>                        fontWeight: FontWeight.w600,<br>                      ),<br>                    ),<br>                  ),<br>                ],<br>              ),<br>            ],<br>          );<br><br>          return SingleChildScrollView(<br>            padding: const EdgeInsets.all(24),<br>            child: isWide<br>                ? Row(<br>                    crossAxisAlignment:<br>                        CrossAxisAlignment.start,<br>                    children: [<br>                      Expanded(child: imagePanel),<br>                      const SizedBox(width: 32),<br>                      Expanded(child: informationPanel),<br>                    ],<br>                  )<br>                : Column(<br>                    crossAxisAlignment:<br>                        CrossAxisAlignment.start,<br>                    children: [<br>                      imagePanel,<br>                      const SizedBox(height: 24),<br>                      informationPanel,<br>                    ],<br>                  ),<br>          );<br>        },<br>      ),<br>    );<br>  }<br>}<br><br>&quot;&quot;&quot;<br><br>if detail_marker not in text:<br>    raise SystemExit(&quot;MyApp marker was not found.&quot;)<br><br>if &quot;class ProductDetailPage&quot; not in text:<br>    text = text.replace(<br>        detail_marker,<br>        detail_page + detail_marker,<br>        1,<br>    )<br><br>old_card_start = &quot;&quot;&quot;                      return Card(<br>                        clipBehavior: Clip.antiAlias,&quot;&quot;&quot;<br><br>new_card_start = &quot;&quot;&quot;                      return Card(<br>                        clipBehavior: Clip.antiAlias,<br>                        child: InkWell(<br>                          onTap: () {<br>                            Navigator.of(context).push(<br>                              MaterialPageRoute(<br>                                builder: (context) =&gt;<br>                                    ProductDetailPage(<br>                                  product: product,<br>                                ),<br>                              ),<br>                            );<br>                          },<br>                          child: Column(&quot;&quot;&quot;<br><br>old_card_column = &quot;&quot;&quot;                        child: Column(<br>                          crossAxisAlignment: CrossAxisAlignment.start,<br>                          children: [&quot;&quot;&quot;<br><br>new_card_column = &quot;&quot;&quot;                            crossAxisAlignment:<br>                                CrossAxisAlignment.start,<br>                            children: [&quot;&quot;&quot;<br><br>old_card_end = &quot;&quot;&quot;                          ],<br>                        ),<br>                      );&quot;&quot;&quot;<br><br>new_card_end = &quot;&quot;&quot;                            ],<br>                          ),<br>                        ),<br>                      );&quot;&quot;&quot;<br><br>if old_card_start not in text:<br>    raise SystemExit(&quot;Card start block was not found.&quot;)<br><br>if old_card_column not in text:<br>    raise SystemExit(&quot;Card column block was not found.&quot;)<br><br>if old_card_end not in text:<br>    raise SystemExit(&quot;Card end block was not found.&quot;)<br><br>text = text.replace(old_card_start, new_card_start, 1)<br>text = text.replace(old_card_column, new_card_column, 1)<br>text = text.replace(old_card_end, new_card_end, 1)<br><br>file_path.write_text(text)<br><br>print(&quot;Reusable ProductDetailPage created.&quot;)<br>print(&quot;Every product card now opens the detail page.&quot;)<br>PY</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/1*cxXUmFA64_abao-e2RDcwg.png" /><figcaption>The terminal creates one reusable detail page and connects every product card to it through Flutter navigation.</figcaption></figure><pre>dart format lib/main.dart<br>flutter analyze</pre><p>The analyzer finds two errors after the navigation patch:</p><p>`elevation` is not defined.</p><p>`shape` is not defined.</p><p>Both properties are valid for a `Card`, so the problem is not the properties themselves.</p><p>The patch accidentally placed them inside the new `InkWell` or `Column` instead of leaving them on the outer `Card`.</p><p>Flutter is reading the structure roughly like this:</p><p>Card <br>→ InkWell <br>→ Column <br>→ elevation and shape</p><p>But `elevation` and `shape` belong to the Card at the top.</p><p>The furniture is correct.</p><p>It was simply delivered to the wrong floor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/1*pzJ_AslQd98h-iyrCYXKcA.png" /><figcaption>Flutter reports that the Card properties `elevation` and `shape` were accidentally placed inside the wrong widget during the navigation update.</figcaption></figure><pre>nl -ba lib/main.dart | sed -n &#39;495,535p&#39;</pre><p>The first repair script does not find the expected code pattern.</p><p>That does not mean the file is damaged.</p><p>It means `dart format` changed the spacing and line structure, so the regular expression no longer matches the code exactly.</p><p>Instead of forcing another blind replacement, I inspect the real widget block around the reported error lines.</p><p>The analyzer already pointed to lines 510 and 511. Now I need to see where `elevation` and `shape` actually landed before moving them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/1*sEMeSmwBKf0AxV9rcgEuFg.png" /><figcaption>The terminal displays the exact widget structure around the analyzer errors before a safer repair is applied.</figcaption></figure><p>The terminal view makes the problem obvious.</p><p>`elevation` and `shape` are sitting inside `Column`, but those properties belong to `Card`.</p><p>The navigation patch did not break the product page itself. It only placed two Card properties one level too deep in the widget tree.</p><p>Flutter is strict about widget responsibilities.</p><p>A Column arranges children.</p><p>A Card owns elevation and shape.</p><p>The fix is simply to move those two properties back to the Card.</p><pre>python3 - &lt;&lt;&#39;PY&#39;<br>from pathlib import Path<br><br>file_path = Path(&quot;lib/main.dart&quot;)<br>text = file_path.read_text()<br><br>old_block = &quot;&quot;&quot;                      return Card(<br>                        clipBehavior: Clip.antiAlias,<br>                        child: InkWell(<br>                          onTap: () {<br>                            Navigator.of(context).push(<br>                              MaterialPageRoute(<br>                                builder: (context) =&gt;<br>                                    ProductDetailPage(product: product),<br>                              ),<br>                            );<br>                          },<br>                          child: Column(<br>                            elevation: 1,<br>                            shape: RoundedRectangleBorder(<br>                              borderRadius: BorderRadius.circular(16),<br>                            ),<br>                            crossAxisAlignment: CrossAxisAlignment.start,&quot;&quot;&quot;<br><br>new_block = &quot;&quot;&quot;                      return Card(<br>                        clipBehavior: Clip.antiAlias,<br>                        elevation: 1,<br>                        shape: RoundedRectangleBorder(<br>                          borderRadius: BorderRadius.circular(16),<br>                        ),<br>                        child: InkWell(<br>                          onTap: () {<br>                            Navigator.of(context).push(<br>                              MaterialPageRoute(<br>                                builder: (context) =&gt;<br>                                    ProductDetailPage(product: product),<br>                              ),<br>                            );<br>                          },<br>                          child: Column(<br>                            crossAxisAlignment: CrossAxisAlignment.start,&quot;&quot;&quot;<br><br>if old_block not in text:<br>    raise SystemExit(<br>        &quot;The exact misplaced widget block was not found.&quot;<br>    )<br><br>file_path.write_text(<br>    text.replace(old_block, new_block, 1)<br>)<br><br>print(&quot;Card properties moved to the correct widget.&quot;)<br>PY</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/1*rA9qDrfcwSi7r8gptn1Elg.png" /><figcaption>The terminal moves `elevation` and `shape` from the Column back to the outer Card.</figcaption></figure><pre>dart format lib/main.dart<br>flutter analyze</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/1*nDH_Ba5nIWLrTURmbQUd7A.png" /><figcaption>No issues found!</figcaption></figure><p>I format the file and run the analyzer again.</p><p>This time, Flutter accepts the widget hierarchy.</p><p>The Card controls its own elevation and rounded shape.</p><p>The InkWell handles the tap.</p><p>The Column arranges the product content.</p><p>The two errors disappear, and the detail-page navigation remains intact.</p><p>The analyzer is clean, so the next step is to test the interaction in the running app.</p><p>Because this change only affects Dart code and navigation, a hot reload is enough if Flutter is still running.</p><p>I return to the terminal where `flutter run` is active and press:</p><p>r</p><p>Flutter reloads the updated widget tree without rebuilding the asset bundle.</p><p>A moment later, the product grid is ready for its first real tap test.</p><p>The product folder currently contains zero images.</p><p>That is expected because I have only prepared the master product sheet. I have not copied it into the Flutter project or sliced it yet.</p><p>The master sheet is stored inside my Pictures folder as one large image containing all twenty products.</p><p>Before cutting anything, I create a safe working copy inside the project and verify that Linux can read it correctly.</p><p>The original image stays untouched.</p><p>The project gets its own copy to work with, because editing the only copy of a file is a hobby best left to people who enjoy unnecessary suspense.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/653/1*4-jefX_U64e5Qs382vXhfQ.png" /><figcaption>Flutter hot reloads the updated navigation code into the running Chrome session.</figcaption></figure><p>I start with Wireless Headphones.</p><p>The card now responds to the click and opens a new page.</p><p>The larger product image appears at the top, followed by the category, product name, price, description, and an offline-information note.</p><p>The back arrow in the app bar returns me to the catalog.</p><p>The card is no longer just a display panel.</p><p>It has officially learned how to open a door.</p><p>The complete flow now works in both directions:</p><p>Catalog grid → Product detail → Back to catalog</p><p>The product cards respond to user input, the detail page displays the correct data, and the back button returns to the original catalog.</p><p>Episode 19 has turned the catalog from a collection of static cards into an app with real navigation.</p><p>Episode 19 began with twenty product cards that looked interactive but could not actually open anything.</p><p>By the end of the episode, every card can launch a reusable product detail page.</p><p>The new page displays:</p><p>- a larger local product image,<br>- the correct category,<br>- the product name,<br>- price,<br>- full description,<br>- offline availability,<br>- and a working back button.</p><p>I also tested the same page with Wireless Headphones and Digital Camera.</p><p>Both products used the same layout, but the content changed automatically based on the selected Product object.</p><p>That confirms the detail page is reusable across the entire catalog.</p><p>The app now has a complete navigation flow:</p><p>Catalog grid → Product detail → Back to catalog.</p><p>The strongest part of this episode is not the new screen itself.</p><p>It is the fact that one screen can serve all twenty products without duplicating the layout.</p><p>Each card passes its own Product object into ProductDetailPage.</p><p>The page reads that data and builds the correct result.</p><p>No fixed product text.</p><p>No twenty-page copy-and-paste marathon.</p><p>Just one reusable screen doing its job without requesting overtime pay.</p><p>In Episode 20, I will add a favorites system and bottom navigation.</p><p>Users will be able to save products they like, switch between the main catalog and a favorites screen, and keep those selections available while using the app.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae6d848740ee" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Episode 18: Building a Searchable and Filterable Product Grid in Flutter]]></title>
            <link>https://medium.com/@lenakendari/episode-18-building-a-searchable-and-filterable-product-grid-in-flutter-d55eddb3168f?source=rss-932b58a7a66a------2</link>
            <guid isPermaLink="false">https://medium.com/p/d55eddb3168f</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[linux]]></category>
            <dc:creator><![CDATA[Atelier Flutter]]></dc:creator>
            <pubDate>Sat, 18 Jul 2026 23:10:02 GMT</pubDate>
            <atom:updated>2026-07-18T23:10:02.882Z</atom:updated>
            <content:encoded><![CDATA[<p>I transform the simple product list into a two-column catalog with local images, working search, and interactive category filters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MR4nxPHCDnS2x-leSUGgzw.png" /></figure><p>Episode 18 is where the catalog stops behaving like a small Flutter demo and starts becoming a real application.</p><p>Until now, the screen has displayed only three products in a vertical list.</p><p>That was enough to build the structure, test the Product model, and prove that reusable cards could work.</p><p>But three products do not create much of a shopping experience.</p><p>They create a very quiet store.</p><p>So this episode brings the largest visual upgrade of the project so far.</p><p>I will expand the inventory from three products to twenty popular items across five categories:</p><p>Audio, Wearables, Photography, Computers, and Accessories.</p><p>The old vertical list will become a responsive product grid with local images stored inside the app.</p><p>I will also add a working search field and interactive category filters.</p><p>Typing “camera” should immediately narrow the catalog to camera-related products.</p><p>Selecting Audio should display headphones, speakers, earbuds, and other audio products.</p><p>Selecting All should bring the entire inventory back, because every product deserves another chance at screen time.</p><p>With twenty items, scrolling will finally have a real purpose.</p><p>Search will have enough data to search.</p><p>Category filters will have enough products to organize.</p><p>By the end of this episode, the catalog should feel dramatically different from the screen I started with.</p><p>It will no longer be three cards sitting politely beneath a heading.</p><p>It will become a searchable, filterable, image-based product catalog that is ready to grow.</p><p>Before changing any code, I open the current version of the app one more time.</p><p>The catalog still contains only three products:</p><p>Wireless Headphones, Smart Watch, and Digital Camera.</p><p>Each item already has a category, description, icon, and price. The layout works, but most of the screen is still empty.</p><p>This screenshot will become the “before” picture for Episode 18.</p><p>Later, when twenty products, real images, search, filters, and a responsive grid are in place, the difference should be impossible to miss.</p><p>A good renovation deserves a proper before photo. Otherwise, everyone has to trust the contractor.</p><p>Before adding seventeen new products, local images, search, and category filters, I open the current version of the app one more time.</p><p>I want a clear record of where Episode 18 begins.</p><p>The catalog currently contains only three products:</p><p>Wireless Headphones, Smart Watch, and Digital Camera.</p><p>Each card already displays a category, description, icon, and price. The reusable Product model is working, and the layout can scroll.</p><p>Technically, the catalog works.</p><p>Visually, it still feels like a store that opened before the delivery truck arrived.</p><p>This screenshot will become the “before” image for the episode.</p><p>Later, I will compare it with a catalog containing twenty products, real local images, a responsive grid, working search, and interactive category filters.</p><p>I open the project from the terminal and run the current catalog in Chrome:</p><pre>cd ~/offline_product_catalog<br>flutter run -d chrome</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/591/1*qgrXSFLtuNs1G0e_85EtBw.png" /><figcaption>The catalog at the beginning of Episode 18 still contains only three products in a vertical list.</figcaption></figure><p>Flutter builds the project and opens the app in Chrome.</p><p>I check that all three existing products still appear correctly before making the larger changes.</p><p>This confirms that I am starting Episode 18 from a stable version of the app, rather than building new features on top of an unnoticed problem.</p><p>With the starting point recorded, I stop the running app and return to the code.</p><p>The next task is to expand the inventory from three products to twenty.</p><p>I will add the product data first and verify that every item appears in the correct order before connecting the image assets.</p><p>Names first. Pictures second.</p><p>That reduces the chance of a camera accidentally introducing itself as a power bank.</p><p>With the original three-product catalog documented, I return to the terminal and begin expanding the inventory.</p><p>I am adding the product data before touching the images or redesigning the layout.</p><p>That order matters.</p><p>Each future image needs a clear destination: one product name, one category, one price, and one position inside the catalog.</p><p>Once all twenty entries are working, I can connect the image assets without guessing which camera belongs to which card.</p><p>Data first. Pictures second. Fewer opportunities for a smartwatch to wake up wearing a laptop’s name tag.</p><pre>cd ~/offline_product_catalog<br>grep -c &quot;^  Product(&quot; lib/main.dart</pre><p>The terminal count confirms that the current product list contains exactly three entries.</p><p>This gives me a clean baseline before adding seventeen new products.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*_n5tPI6y-WlmBTKesBlcUg.png" /><figcaption>The terminal confirms that the catalog currently contains only three product entries.</figcaption></figure><p>Before replacing the product list, I create a backup of `main.dart`.</p><p>The change is straightforward, but this episode touches a large amount of data. Keeping a backup means I can return to the working three-product version if anything goes sideways.</p><p>Backups are less exciting than new features, but so are seat belts until the moment they become very interesting.</p><pre>cp lib/main.dart lib/main.dart.backup_before_20_products</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*D8otOwnaUYPilGiZ21besA.png" /><figcaption>A backup of `main.dart` is stored before the product inventory is expanded.</figcaption></figure><p>Now I replace the original three entries with twenty products across five categories.</p><p>The categories are:</p><p>Audio <br>Wearables <br>Photography <br>Computers <br>Accessories</p><p>Each category receives four products, giving the catalog enough inventory for scrolling, searching, and filtering to become meaningful.</p><pre>python3 - &lt;&lt;&#39;PY&#39;<br>from pathlib import Path<br><br>file_path = Path(&quot;lib/main.dart&quot;)<br>text = file_path.read_text()<br><br>start_marker = &quot;const products = [&quot;<br>start = text.find(start_marker)<br><br>if start == -1:<br>    raise SystemExit(&quot;The products list was not found.&quot;)<br><br>end = text.find(&quot;\n];&quot;, start)<br><br>if end == -1:<br>    raise SystemExit(&quot;The end of the products list was not found.&quot;)<br><br>end += len(&quot;\n];&quot;)<br><br>new_products = r&quot;&quot;&quot;const products = [<br>  Product(<br>    name: &#39;Wireless Headphones&#39;,<br>    description: &#39;Comfortable wireless audio for everyday listening&#39;,<br>    price: &#39;\$49.00&#39;,<br>    icon: Icons.headphones,<br>    category: &#39;Audio&#39;,<br>  ),<br>  Product(<br>    name: &#39;Bluetooth Speaker&#39;,<br>    description: &#39;Portable sound for home and outdoor use&#39;,<br>    price: &#39;\$79.00&#39;,<br>    icon: Icons.speaker,<br>    category: &#39;Audio&#39;,<br>  ),<br>  Product(<br>    name: &#39;Wireless Earbuds&#39;,<br>    description: &#39;Compact earbuds with a charging case&#39;,<br>    price: &#39;\$59.00&#39;,<br>    icon: Icons.earbuds,<br>    category: &#39;Audio&#39;,<br>  ),<br>  Product(<br>    name: &#39;Portable Soundbar&#39;,<br>    description: &#39;Clear sound in a slim portable design&#39;,<br>    price: &#39;\$99.00&#39;,<br>    icon: Icons.surround_sound,<br>    category: &#39;Audio&#39;,<br>  ),<br>  Product(<br>    name: &#39;Smart Watch&#39;,<br>    description: &#39;Track activity and stay connected&#39;,<br>    price: &#39;\$89.00&#39;,<br>    icon: Icons.watch,<br>    category: &#39;Wearables&#39;,<br>  ),<br>  Product(<br>    name: &#39;Fitness Band&#39;,<br>    description: &#39;Simple daily activity and fitness tracking&#39;,<br>    price: &#39;\$39.00&#39;,<br>    icon: Icons.fitness_center,<br>    category: &#39;Wearables&#39;,<br>  ),<br>  Product(<br>    name: &#39;Classic Watch&#39;,<br>    description: &#39;A clean traditional watch for everyday wear&#39;,<br>    price: &#39;\$69.00&#39;,<br>    icon: Icons.watch_outlined,<br>    category: &#39;Wearables&#39;,<br>  ),<br>  Product(<br>    name: &#39;Sport Watch&#39;,<br>    description: &#39;A durable watch designed for active routines&#39;,<br>    price: &#39;\$99.00&#39;,<br>    icon: Icons.directions_run,<br>    category: &#39;Wearables&#39;,<br>  ),<br>  Product(<br>    name: &#39;Digital Camera&#39;,<br>    description: &#39;Capture everyday memories in high quality&#39;,<br>    price: &#39;\$299.00&#39;,<br>    icon: Icons.camera_alt,<br>    category: &#39;Photography&#39;,<br>  ),<br>  Product(<br>    name: &#39;Action Camera&#39;,<br>    description: &#39;Compact video recording for outdoor adventures&#39;,<br>    price: &#39;\$199.00&#39;,<br>    icon: Icons.videocam,<br>    category: &#39;Photography&#39;,<br>  ),<br>  Product(<br>    name: &#39;Instant Camera&#39;,<br>    description: &#39;Create printed photographs in seconds&#39;,<br>    price: &#39;\$129.00&#39;,<br>    icon: Icons.camera,<br>    category: &#39;Photography&#39;,<br>  ),<br>  Product(<br>    name: &#39;Camera Lens&#39;,<br>    description: &#39;A versatile lens for sharper photographs&#39;,<br>    price: &#39;\$149.00&#39;,<br>    icon: Icons.camera_enhance,<br>    category: &#39;Photography&#39;,<br>  ),<br>  Product(<br>    name: &#39;Laptop&#39;,<br>    description: &#39;A portable computer for work and study&#39;,<br>    price: &#39;\$899.00&#39;,<br>    icon: Icons.laptop,<br>    category: &#39;Computers&#39;,<br>  ),<br>  Product(<br>    name: &#39;Mechanical Keyboard&#39;,<br>    description: &#39;Responsive keys for typing and gaming&#39;,<br>    price: &#39;\$79.00&#39;,<br>    icon: Icons.keyboard,<br>    category: &#39;Computers&#39;,<br>  ),<br>  Product(<br>    name: &#39;Wireless Mouse&#39;,<br>    description: &#39;Smooth and comfortable wireless control&#39;,<br>    price: &#39;\$29.00&#39;,<br>    icon: Icons.mouse,<br>    category: &#39;Computers&#39;,<br>  ),<br>  Product(<br>    name: &#39;Desktop Monitor&#39;,<br>    description: &#39;A larger display for work and entertainment&#39;,<br>    price: &#39;\$159.00&#39;,<br>    icon: Icons.desktop_windows,<br>    category: &#39;Computers&#39;,<br>  ),<br>  Product(<br>    name: &#39;Minimal Backpack&#39;,<br>    description: &#39;A simple backpack for devices and essentials&#39;,<br>    price: &#39;\$34.00&#39;,<br>    icon: Icons.backpack,<br>    category: &#39;Accessories&#39;,<br>  ),<br>  Product(<br>    name: &#39;Power Bank&#39;,<br>    description: &#39;Portable power for phones and small devices&#39;,<br>    price: &#39;\$25.00&#39;,<br>    icon: Icons.battery_charging_full,<br>    category: &#39;Accessories&#39;,<br>  ),<br>  Product(<br>    name: &#39;USB-C Hub&#39;,<br>    description: &#39;Add useful ports through one USB-C connection&#39;,<br>    price: &#39;\$19.00&#39;,<br>    icon: Icons.hub,<br>    category: &#39;Accessories&#39;,<br>  ),<br>  Product(<br>    name: &#39;Phone Stand&#39;,<br>    description: &#39;Keep a phone upright on a desk&#39;,<br>    price: &#39;\$9.00&#39;,<br>    icon: Icons.phone_android,<br>    category: &#39;Accessories&#39;,<br>  ),<br>];&quot;&quot;&quot;<br><br>updated = text[:start] + new_products + text[end:]<br>file_path.write_text(updated)<br><br>print(&quot;Catalog expanded from 3 products to 20 products.&quot;)<br>PY</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*QVbiLOxlDuDi2ciJlRfxWg.png" /><figcaption>The terminal confirms that the catalog inventory has expanded from three products to twenty.</figcaption></figure><p>The replacement finishes successfully, but I do not trust a large data change based on one cheerful terminal message.</p><p>I count the product entries again.</p><pre>grep -c &quot;^  Product(&quot; lib/main.dart</pre><pre>grep -n &quot;name:&quot; lib/main.dart | head -n 4<br>grep -n &quot;name:&quot; lib/main.dart | tail -n 4</pre><p>The new count returns twenty.</p><p>The first entries belong to Audio, while the final entries belong to Accessories. This confirms that the full inventory was inserted in the intended order.</p><p>The catalog now has products.</p><p>The images are still waiting outside with their luggage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*dnb1ejYIDeKYv0owF77eqQ.png" /><figcaption>A second terminal check confirms that all twenty product entries are present and arranged in the expected order.</figcaption></figure><pre>dart format lib/main.dart<br>flutter analyze</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*8JwAGX_3mp2UJLUkxYPOdw.png" /><figcaption>Dart formats the expanded inventory, and Flutter confirms that all twenty product entries are valid.</figcaption></figure><p>The larger inventory has passed Flutter’s checks, so I am ready to see what twenty products actually look like on the screen.</p><p>The catalog is still using icons instead of product images, and the layout is still the vertical card list from Episode 17.</p><p>That is intentional.</p><p>Before changing the design, I want to confirm that every new product appears correctly, in the right order, and under the right category.</p><p>This gives me one stable checkpoint between the old three-product catalog and the image-based grid that comes next.</p><p>The store now has inventory.</p><p>The shelves just have not received their photographs yet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/599/1*b2Vu1GKBeEQ1iopsh-L_4Q.png" /><figcaption>The expanded catalog opens in Chrome with the first products appearing in the correct order.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/599/1*_wWY_qTREDYnWkWNK1Gn5g.png" /><figcaption>Reaching the bottom of the catalog confirms that all twenty products are present and ready to receive their local images.</figcaption></figure><p>I scroll from the first Audio product to the final Accessories item.</p><p>All twenty entries are present.</p><p>The names, descriptions, categories, prices, and icons appear in the expected order.</p><p>The vertical list is now much longer, which also proves why the next design change is necessary.</p><p>Twenty large cards work, but they consume a great deal of space.</p><p>The catalog needs a grid.</p><p>It also needs real product images, because twenty Flutter icons begin to look less like inventory and more like a very organized settings menu.</p><p>The twenty products now exist in the catalog data, but they still use Flutter icons.</p><p>To give the app a more convincing storefront, I prepared one AI-generated master sheet containing all twenty product images in a five-column, four-row grid.</p><p>Using one master sheet keeps the lighting, background, and overall visual style consistent across the entire catalog.</p><p>Now Linux gets the satisfying part of the job: slicing one large image into twenty individual product assets.</p><p>It is essentially meal prep, except the containers hold headphones and camera lenses.</p><pre>cd ~/offline_product_catalog<br><br>mkdir -p tools/product_assets<br>mkdir -p assets/products<br><br>cp &quot;$HOME/Pictures/PRODUCT/Pasted image.png&quot; \<br>  tools/product_assets/product_master.png<br><br>file tools/product_assets/product_master.png<br>ls -lh tools/product_assets/product_master.png</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/819/1*hzHEGwl_7QcaW6wxA_BODQ.png" /><figcaption>The master product sheet is copied into the project and verified before the slicing process begins.</figcaption></figure><p>I first copy the master image into the project.</p><p>The original file remains safely inside my Pictures folder, while the project receives its own working copy under `tools/product_assets`.</p><p>I keep the master sheet outside the final Flutter asset folder because the app only needs the twenty individual images, not the large source sheet.</p><p>There is no reason to make the future APK carry the entire cutting board into the dining room.</p><p>Before cutting the master sheet, I check whether Python can access Pillow, the image-processing library used by the slicing script.</p><p>Pillow will open the master image, calculate the crop positions, resize every result, and save twenty individual PNG files.</p><p>Without it, Python can admire the product sheet, but it cannot bring scissors.</p><pre>python3 -c &quot;from PIL import Image; print(&#39;Pillow is ready.&#39;)&quot;</pre><p>Pillow is ready.</p><p>The confirmation appears immediately.</p><p>Pillow is installed and ready, which means the slicing process can continue without adding another dependency to the project.</p><p>It is a small check, but it prevents me from launching a large script only to discover that the most important tool never entered the workshop.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/819/1*Tlb77kBtHnYeOHyPHJ7aAA.png" /><figcaption>Python confirms that Pillow is installed and ready to process the master product image.</figcaption></figure><p>If Python reports that the PIL module cannot be found, Pillow needs to be installed before continuing.</p><p>On Ubuntu, I can install the system package directly from the terminal:</p><pre>sudo apt update<br>sudo apt install -y python3-pil</pre><pre>python3 -c &quot;from PIL import Image; print(&#39;Pillow is ready.&#39;)&quot;</pre><p>Once the confirmation appears, the environment is ready.</p><p>This keeps the tutorial useful for readers whose Ubuntu installation does not already include Pillow.</p><p>My laptop happened to be prepared. The next reader’s laptop may arrive wearing different shoes.</p><p>With Pillow ready, I run the slicing script.</p><p>The script reads the dimensions of the master sheet and divides it into five columns and four rows.</p><p>Each position has a fixed destination.</p><p>The first tile becomes Wireless Headphones.</p><p>The second becomes Bluetooth Speaker.</p><p>The process continues from left to right and top to bottom until the twentieth tile becomes Phone Stand.</p><p>Every crop is placed on a consistent 600-by-600 white canvas before being saved inside `assets/products`.</p><p>A single image enters the terminal.</p><p>Twenty organized Flutter assets come out.</p><p>Linux has turned one crowded product photo into a very efficient unpacking department.</p><p>The script reports success, but I verify the output before connecting anything to Flutter.</p><p>A successful message is encouraging.</p><p>A counted folder is evidence.</p><pre>find assets/products \<br>  -maxdepth 1 \<br>  -type f \<br>  -name &quot;*.png&quot; \<br>  | sort<br><br>printf &quot;\nTotal product images: &quot;<br>find assets/products \<br>  -maxdepth 1 \<br>  -type f \<br>  -name &quot;*.png&quot; \<br>  | wc -l</pre><p>The product folder currently contains zero images.</p><p>That is expected because I have only prepared the master product sheet. I have not copied it into the Flutter project or sliced it yet.</p><p>The master sheet is stored inside my Pictures folder as one large image containing all twenty products.</p><p>Before cutting anything, I create a safe working copy inside the project and verify that Linux can read it correctly.</p><p>The original image stays untouched.</p><p>The project gets its own copy to work with, because editing the only copy of a file is a hobby best left to people who enjoy unnecessary suspense.</p><pre>cd ~/offline_product_catalog<br><br>ls -lh &quot;$HOME/Pictures/PRODUCT/Pasted image.png&quot;</pre><pre>mkdir -p tools/product_assets<br>mkdir -p assets/products<br><br>cp &quot;$HOME/Pictures/PRODUCT/Pasted image.png&quot; \<br>  tools/product_assets/product_master.png</pre><pre>mkdir -p tools/product_assets<br>mkdir -p assets/products<br><br>cp &quot;$HOME/Pictures/PRODUCT/Pasted image.png&quot; \<br>  tools/product_assets/product_master.png</pre><p>Linux finds the source image and copies it into `tools/product_assets` as `product_master.png`.</p><p>I then inspect its format and exact dimensions.</p><p>This information matters because the slicing script will divide the image into five columns and four rows. It should calculate every crop from the real image dimensions instead of relying on measurements copied from a napkin.</p><p>The master sheet is now inside the project.</p><p>The scissors are still closed, but they are finally on the table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/819/1*AfvGcjCQIrXNQ17nkU_YNw.png" /><figcaption>The master product sheet is copied into the project and verified as a 1402-by-1122 PNG image before the slicing process begins.</figcaption></figure><p>The terminal confirms that the master sheet is a valid PNG image measuring 1402 by 1122 pixels.</p><p>The same check also proves that Pillow is already installed and able to open the file.</p><p>That means the project has everything it needs for the next step.</p><p>I now have one image containing twenty products, a known five-column and four-row layout, and a Python image tool waiting with its digital scissors.</p><p>The master sheet has survived inspection.</p><p>It is time to take it apart.</p><p>The master image is arranged in five columns and four rows.</p><p>That gives me exactly twenty product positions.</p><p>The slicing script will move from left to right and top to bottom, matching the same order used by the product data inside `main.dart`.</p><p>The first tile becomes Wireless Headphones.</p><p>The fifth becomes Smart Watch.</p><p>The tenth becomes Action Camera.</p><p>The twentieth becomes Phone Stand.</p><p>Each crop will be cleaned, resized, centered on a square white canvas, and saved with an ordered filename inside `assets/products`.</p><p>One crowded image goes in.</p><p>Twenty well-behaved Flutter assets come out.</p><pre>cd ~/offline_product_catalog<br><br>mkdir -p assets/products<br>rm -f assets/products/*.png<br><br>python3 - &lt;&lt;&#39;PY&#39;<br>from pathlib import Path<br>from PIL import Image<br><br>source = Path(&quot;tools/product_assets/product_master.png&quot;)<br>output_dir = Path(&quot;assets/products&quot;)<br><br>product_files = [<br>    &quot;01_wireless_headphones.png&quot;,<br>    &quot;02_bluetooth_speaker.png&quot;,<br>    &quot;03_wireless_earbuds.png&quot;,<br>    &quot;04_portable_soundbar.png&quot;,<br>    &quot;05_smart_watch.png&quot;,<br>    &quot;06_fitness_band.png&quot;,<br>    &quot;07_classic_watch.png&quot;,<br>    &quot;08_sport_watch.png&quot;,<br>    &quot;09_digital_camera.png&quot;,<br>    &quot;10_action_camera.png&quot;,<br>    &quot;11_instant_camera.png&quot;,<br>    &quot;12_camera_lens.png&quot;,<br>    &quot;13_laptop.png&quot;,<br>    &quot;14_mechanical_keyboard.png&quot;,<br>    &quot;15_wireless_mouse.png&quot;,<br>    &quot;16_desktop_monitor.png&quot;,<br>    &quot;17_minimal_backpack.png&quot;,<br>    &quot;18_power_bank.png&quot;,<br>    &quot;19_usb_c_hub.png&quot;,<br>    &quot;20_phone_stand.png&quot;,<br>]<br><br>if not source.exists():<br>    raise SystemExit(f&quot;Master image not found: {source}&quot;)<br><br>image = Image.open(source).convert(&quot;RGB&quot;)<br>width, height = image.size<br><br>columns = 5<br>rows = 4<br>canvas_size = 600<br>content_size = 570<br><br>resampling = getattr(Image, &quot;Resampling&quot;, Image).LANCZOS<br><br>print(f&quot;Master image: {width} x {height} pixels&quot;)<br>print(f&quot;Grid layout: {columns} columns x {rows} rows&quot;)<br>print()<br><br>for index, filename in enumerate(product_files):<br>    row, column = divmod(index, columns)<br><br>    left = round(column * width / columns)<br>    right = round((column + 1) * width / columns)<br>    top = round(row * height / rows)<br>    bottom = round((row + 1) * height / rows)<br><br>    tile = image.crop((left, top, right, bottom))<br><br>    # Remove only the thin white separator around each grid cell.<br>    border_trim = 2<br>    tile = tile.crop(<br>        (<br>            border_trim,<br>            border_trim,<br>            tile.width - border_trim,<br>            tile.height - border_trim,<br>        )<br>    )<br><br>    tile.thumbnail(<br>        (content_size, content_size),<br>        resampling,<br>    )<br><br>    canvas = Image.new(<br>        &quot;RGB&quot;,<br>        (canvas_size, canvas_size),<br>        &quot;white&quot;,<br>    )<br><br>    x = (canvas_size - tile.width) // 2<br>    y = (canvas_size - tile.height) // 2<br><br>    canvas.paste(tile, (x, y))<br><br>    destination = output_dir / filename<br>    canvas.save(destination, &quot;PNG&quot;, optimize=True)<br><br>    print(f&quot;{index + 1:02d}/20  {filename}&quot;)<br><br>print()<br>print(&quot;All 20 product images were created successfully.&quot;)<br>PY</pre><p>01/20 01_wireless_headphones.png<br>02/20 02_bluetooth_speaker.png<br>03/20 03_wireless_earbuds.png<br>…<br>18/20 18_power_bank.png<br>19/20 19_usb_c_hub.png<br>20/20 20_phone_stand.png</p><p>All 20 product images were created successfully.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/819/1*sGRiTg_JZi9ep2NN2iV-6A.png" /><figcaption>Python divides the five-by-four master sheet into twenty ordered product images and saves each one on a consistent square canvas.</figcaption></figure><pre>printf &quot;Total product images: &quot;<br><br>find assets/products \<br>  -maxdepth 1 \<br>  -type f \<br>  -name &quot;*.png&quot; \<br>  | wc -l</pre><p>Total product images: 20</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/819/1*fL4pVBaCaSjNjWI1aQwkBQ.png" /><figcaption>A terminal count confirms that the project now contains exactly twenty individual product image assets.</figcaption></figure><p>The slicing process finishes successfully, but I verify the output before moving on.</p><p>The terminal counts twenty PNG files inside `assets/products`.</p><p>That number matters because the catalog also contains twenty product entries.</p><p>Every product now has exactly one image waiting for it.</p><p>No missing files. No extra mystery tile. No headphones attempting a second career as a desktop monitor.</p><p>The terminal has created twenty image files, but a correct file count does not guarantee a correct crop.</p><p>Before connecting the images to Flutter, I inspect them visually.</p><p>I want to confirm that every product is centered, fully visible, and matched with the correct filename.</p><p>A folder can contain twenty perfectly valid PNG files and still hide one backpack pretending to be a Bluetooth speaker.</p><pre>python3 - &lt;&lt;&#39;PY&#39;<br>from pathlib import Path<br>from PIL import Image<br><br>folder = Path(&quot;assets/products&quot;)<br>files = sorted(folder.glob(&quot;*.png&quot;))<br><br>print(f&quot;Images found: {len(files)}&quot;)<br>print()<br><br>invalid = []<br><br>for file in files:<br>    with Image.open(file) as image:<br>        width, height = image.size<br>        status = &quot;OK&quot; if (width, height) == (600, 600) else &quot;CHECK&quot;<br><br>        print(f&quot;{status:5}  {file.name:32}  {width} x {height}&quot;)<br><br>        if status != &quot;OK&quot;:<br>            invalid.append(file.name)<br><br>print()<br><br>if len(files) != 20:<br>    print(f&quot;WARNING: Expected 20 images, found {len(files)}.&quot;)<br>elif invalid:<br>    print(&quot;WARNING: Some images do not use the expected 600 x 600 size.&quot;)<br>else:<br>    print(&quot;All 20 product images passed the size check.&quot;)<br>PY</pre><p>All 20 product images passed the size check.</p><p>I run one more automated check before opening the folder.</p><p>The script confirms that all twenty images use the same 600-by-600 dimensions.</p><p>Consistent image sizes matter because the catalog grid should not jump, stretch, or negotiate separate furniture arrangements for every product.</p><p>The assets are now technically uniform.</p><p>Next, I check whether they also look correct.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/819/1*bLiQYXC1l8IHiyX_EyQ8xg.png" /><figcaption>All twenty product images pass the size check and share the same 600-by-600 dimensions.</figcaption></figure><pre>xdg-open assets/products</pre><p>01 Wireless Headphones<br>02 Bluetooth Speaker<br>03 Wireless Earbuds<br>04 Portable Soundbar<br>05 Smart Watch</p><p>06 Fitness Band<br>07 Classic Watch<br>08 Sport Watch<br>09 Digital Camera<br>10 Action Camera</p><p>11 Instant Camera<br>12 Camera Lens<br>13 Laptop<br>14 Mechanical Keyboard<br>15 Wireless Mouse</p><p>16 Desktop Monitor<br>17 Minimal Backpack<br>18 Power Bank<br>19 USB-C Hub<br>20 Phone Stand</p><p>I open the asset folder and inspect the images from the first file to the twentieth.</p><p>The filenames preserve the same order used by the product list.</p><p>The headphones appear first.</p><p>The phone stand appears last.</p><p>Between them, every speaker, watch, camera, computer accessory, and backpack sits inside its own square image.</p><p>The terminal handled the cutting.</p><p>Now my eyes handle quality control.</p><p>The images now exist inside the project, but Flutter will not package them automatically.</p><p>I need to register the asset folder inside `pubspec.yaml`.</p><p>Instead of listing twenty image files separately, I register the entire directory.</p><p>That keeps the configuration clean and leaves the door open for future products without turning `pubspec.yaml` into a nightclub guest list.</p><pre>grep -nA8 &quot;^flutter:&quot; pubspec.yaml</pre><pre>cp pubspec.yaml pubspec.yaml.backup_episode18<br><br>python3 - &lt;&lt;&#39;PY&#39;<br>from pathlib import Path<br><br>file_path = Path(&quot;pubspec.yaml&quot;)<br>text = file_path.read_text()<br><br>asset_entry = &quot;    - assets/products/\n&quot;<br><br>if asset_entry in text:<br>    print(&quot;Product asset folder is already registered.&quot;)<br>else:<br>    marker = &quot;  uses-material-design: true\n&quot;<br><br>    if marker not in text:<br>        raise SystemExit(<br>            &quot;Could not find &#39;uses-material-design: true&#39; in pubspec.yaml.&quot;<br>        )<br><br>    replacement = (<br>        marker<br>        + &quot;\n&quot;<br>        + &quot;  assets:\n&quot;<br>        + asset_entry<br>    )<br><br>    file_path.write_text(text.replace(marker, replacement, 1))<br>    print(&quot;Product asset folder registered successfully.&quot;)<br>PY</pre><pre>flutter:<br>  uses-material-design: true<br><br>  assets:<br>    - assets/products/</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/819/1*N14XcNRkylj5nC0YOQvnPg.png" /><figcaption>The product image directory is registered in `pubspec.yaml`, allowing Flutter to package all twenty local assets.</figcaption></figure><p>I register the complete `assets/products` directory under Flutter’s asset configuration.</p><p>The indentation is important because YAML treats spacing as structure, not decoration.</p><p>One misplaced space can turn a harmless configuration file into a tiny bureaucrat refusing to stamp the paperwork.</p><pre>flutter pub get</pre><pre>flutter analyze</pre><pre>No issues found!</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*kxHr1Xz4zdd_Rl-w6-1zzw.png" /><figcaption>Flutter accepts the new asset directory and confirms that the project remains free of code issues.</figcaption></figure><p>I run `flutter pub get` so Flutter can refresh the project configuration and recognize the newly registered directory.</p><p>Then I run `flutter analyze` to make sure the asset configuration has not introduced a project error.</p><p>The images are now inside the project, correctly cropped, consistently sized, visually checked, and officially known to Flutter.</p><p>They are ready.</p><p>The catalog still does not display them yet, but that is about to change.</p><p>The image files are now registered with Flutter, but the product data still does not know which image belongs to which item.</p><p>I need to connect every product entry to its matching asset path.</p><p>Wireless Headphones should point to `01_wireless_headphones.png`.</p><p>Bluetooth Speaker should point to `02_bluetooth_speaker.png`.</p><p>The pattern continues until Phone Stand reaches `20_phone_stand.png`.</p><p>Because all twenty files live inside the app, the catalog will be able to display them without downloading anything from the internet.</p><p>The products already have names, prices, descriptions, and categories.</p><p>Now they are finally getting faces.</p><p>Before editing the Product model and twenty data entries, I create another backup.</p><p>This change touches the model and the entire inventory, so having a working checkpoint nearby is simply good manners toward Future Me.</p><pre>cd ~/offline_product_catalog<br><br>cp lib/main.dart \<br>  lib/main.dart.backup_before_product_images</pre><pre>ls -lh lib/main.dart*</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*YW4W0jrFvDRB6BwlNBDOuw.png" /><figcaption>A fresh backup protects the working twenty-product catalog before image paths are added.</figcaption></figure><pre>python3 - &lt;&lt;&#39;PY&#39;<br>from pathlib import Path<br>import re<br><br>file_path = Path(&quot;lib/main.dart&quot;)<br>text = file_path.read_text()<br><br>product_images = {<br>    &quot;Wireless Headphones&quot;: &quot;assets/products/01_wireless_headphones.png&quot;,<br>    &quot;Bluetooth Speaker&quot;: &quot;assets/products/02_bluetooth_speaker.png&quot;,<br>    &quot;Wireless Earbuds&quot;: &quot;assets/products/03_wireless_earbuds.png&quot;,<br>    &quot;Portable Soundbar&quot;: &quot;assets/products/04_portable_soundbar.png&quot;,<br>    &quot;Smart Watch&quot;: &quot;assets/products/05_smart_watch.png&quot;,<br>    &quot;Fitness Band&quot;: &quot;assets/products/06_fitness_band.png&quot;,<br>    &quot;Classic Watch&quot;: &quot;assets/products/07_classic_watch.png&quot;,<br>    &quot;Sport Watch&quot;: &quot;assets/products/08_sport_watch.png&quot;,<br>    &quot;Digital Camera&quot;: &quot;assets/products/09_digital_camera.png&quot;,<br>    &quot;Action Camera&quot;: &quot;assets/products/10_action_camera.png&quot;,<br>    &quot;Instant Camera&quot;: &quot;assets/products/11_instant_camera.png&quot;,<br>    &quot;Camera Lens&quot;: &quot;assets/products/12_camera_lens.png&quot;,<br>    &quot;Laptop&quot;: &quot;assets/products/13_laptop.png&quot;,<br>    &quot;Mechanical Keyboard&quot;: &quot;assets/products/14_mechanical_keyboard.png&quot;,<br>    &quot;Wireless Mouse&quot;: &quot;assets/products/15_wireless_mouse.png&quot;,<br>    &quot;Desktop Monitor&quot;: &quot;assets/products/16_desktop_monitor.png&quot;,<br>    &quot;Minimal Backpack&quot;: &quot;assets/products/17_minimal_backpack.png&quot;,<br>    &quot;Power Bank&quot;: &quot;assets/products/18_power_bank.png&quot;,<br>    &quot;USB-C Hub&quot;: &quot;assets/products/19_usb_c_hub.png&quot;,<br>    &quot;Phone Stand&quot;: &quot;assets/products/20_phone_stand.png&quot;,<br>}<br><br>if &quot;required this.imagePath,&quot; not in text:<br>    constructor_marker = &quot;    required this.category,\n&quot;<br><br>    if constructor_marker not in text:<br>        raise SystemExit(&quot;Product constructor marker was not found.&quot;)<br><br>    text = text.replace(<br>        constructor_marker,<br>        constructor_marker + &quot;    required this.imagePath,\n&quot;,<br>        1,<br>    )<br><br>if &quot;final String imagePath;&quot; not in text:<br>    field_marker = &quot;  final String category;\n&quot;<br><br>    if field_marker not in text:<br>        raise SystemExit(&quot;Product category field was not found.&quot;)<br><br>    text = text.replace(<br>        field_marker,<br>        field_marker + &quot;  final String imagePath;\n&quot;,<br>        1,<br>    )<br><br>product_pattern = re.compile(<br>    r&quot;  Product\(\n(?P&lt;body&gt;.*?\n  \),)&quot;,<br>    re.DOTALL,<br>)<br><br>found_products = set()<br><br>def update_product(match):<br>    block = match.group(0)<br>    body = match.group(&quot;body&quot;)<br><br>    name_match = re.search(<br>        r&quot;name: &#39;([^&#39;]+)&#39;&quot;,<br>        body,<br>    )<br><br>    if not name_match:<br>        return block<br><br>    name = name_match.group(1)<br><br>    if name not in product_images:<br>        return block<br><br>    found_products.add(name)<br><br>    if &quot;imagePath:&quot; in block:<br>        return block<br><br>    category_match = re.search(<br>        r&quot;(?P&lt;line&gt;    category: &#39;[^&#39;]+&#39;,\n)&quot;,<br>        block,<br>    )<br><br>    if not category_match:<br>        raise SystemExit(<br>            f&quot;Category line was not found for {name}.&quot;<br>        )<br><br>    image_line = (<br>        f&quot;    imagePath: &#39;{product_images[name]}&#39;,\n&quot;<br>    )<br><br>    return block.replace(<br>        category_match.group(&quot;line&quot;),<br>        category_match.group(&quot;line&quot;) + image_line,<br>        1,<br>    )<br><br>text = product_pattern.sub(update_product, text)<br><br>missing_products = sorted(<br>    set(product_images) - found_products<br>)<br><br>if missing_products:<br>    raise SystemExit(<br>        &quot;These products were not found:\n&quot;<br>        + &quot;\n&quot;.join(missing_products)<br>    )<br><br>file_path.write_text(text)<br><br>print(&quot;imagePath added to the Product model.&quot;)<br>print(&quot;All 20 products connected to local images.&quot;)<br>PY</pre><p>imagePath added to the Product model.<br>All 20 products connected to local images.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*qzgsZDUB2SD-oOMc1fU4aw.png" /><figcaption>The terminal adds an image path to the Product model and connects all twenty products to their matching local assets.</figcaption></figure><p>The filenames are not selected randomly.</p><p>They follow the same order used when the master sheet was sliced.</p><p>The first product receives the first image, and the twentieth product receives the twentieth image.</p><p>This keeps the relationship between the product data and the asset folder predictable.</p><p>More importantly, the image path now lives inside each Product object.</p><p>The future grid does not need a separate pile of conditions asking whether headphones should use one file and cameras should use another.</p><p>Each product simply carries its own address.</p><pre>grep -n &quot;imagePath:&quot; lib/main.dart</pre><pre>printf &quot;Product image paths in main.dart: &quot;<br><br>grep -c &quot;imagePath: &#39;assets/products/&quot; \<br>  lib/main.dart</pre><p>Product image paths in main.dart: 20</p><pre>python3 - &lt;&lt;&#39;PY&#39;<br>from pathlib import Path<br>import re<br><br>main_file = Path(&quot;lib/main.dart&quot;)<br>text = main_file.read_text()<br><br>paths = re.findall(<br>    r&quot;imagePath: &#39;([^&#39;]+)&#39;&quot;,<br>    text,<br>)<br><br>print(f&quot;Image paths found in product data: {len(paths)}&quot;)<br>print()<br><br>missing = []<br><br>for path_text in paths:<br>    path = Path(path_text)<br>    status = &quot;OK&quot; if path.exists() else &quot;MISSING&quot;<br><br>    print(f&quot;{status:7} {path}&quot;)<br><br>    if not path.exists():<br>        missing.append(path_text)<br><br>print()<br><br>if len(paths) != 20:<br>    print(<br>        f&quot;WARNING: Expected 20 image paths, &quot;<br>        f&quot;but found {len(paths)}.&quot;<br>    )<br>elif missing:<br>    print(&quot;WARNING: Some product images are missing.&quot;)<br>else:<br>    print(<br>        &quot;All 20 product image paths match real files.&quot;<br>    )<br>PY</pre><p>All 20 product image paths match real files.</p><p>I verify both sides of the connection.</p><p>The product data contains twenty image paths, and every path points to a file that actually exists.</p><p>This catches spelling mistakes before Flutter reaches the screen.</p><p>An image path can look perfectly reasonable while quietly pointing to nowhere, which is how applications end up displaying blank boxes with the confidence of modern art.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*XBkQrvRpTsS_4uyXgEeWrQ.png" /><figcaption>A terminal audit confirms that all twenty image paths point to real files inside the project.</figcaption></figure><pre>code lib/main.dart</pre><pre>required this.imagePath,</pre><pre>class Product {<br>  const Product({<br>    required this.name,<br>    required this.description,<br>    required this.price,<br>    required this.icon,<br>    required this.category,<br>    required this.imagePath,<br>  });<br><br>  final String name;<br>  final String description;<br>  final String price;<br>  final IconData icon;<br>  final String category;<br>  final String imagePath;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*YBiPlR0ux3Il5TQB7A7Vig.png" /><figcaption>Visual Studio Code shows the Product model extended with a local image path for every catalog item.</figcaption></figure><pre>Product(<br>  name: &#39;Wireless Headphones&#39;,<br>  description: &#39;Comfortable wireless audio for everyday listening&#39;,<br>  price: &#39;\$49.00&#39;,<br>  icon: Icons.headphones,<br>  category: &#39;Audio&#39;,<br>  imagePath: &#39;assets/products/01_wireless_headphones.png&#39;,<br>),</pre><pre>Product(<br>  name: &#39;Phone Stand&#39;,<br>  description: &#39;Keep a phone upright on a desk&#39;,<br>  price: &#39;\$9.00&#39;,<br>  icon: Icons.phone_android,<br>  category: &#39;Accessories&#39;,<br>  imagePath: &#39;assets/products/20_phone_stand.png&#39;,<br>),</pre><pre>dart format lib/main.dart<br>flutter analyze</pre><p>No issues found!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/819/1*Qh560O16f9HW--NX4u-umA.png" /><figcaption>Dart formats the updated product data, and Flutter confirms that all twenty image mappings are valid.</figcaption></figure><p>The image mapping is complete, so I format the file and ask Flutter to inspect the updated model.</p><p>The analyzer reports no issues.</p><p>Twenty products now carry twenty valid local image paths.</p><p>The data layer is ready.</p><p>Next, I will replace the long vertical list with a responsive image grid, then add the search field and category filters that will control what appears on the screen.</p><p>The product data is ready, and all twenty image paths point to real files.</p><p>Now I can make the change that will define Episode 18 visually.</p><p>The long vertical list is leaving.</p><p>In its place, I will build a responsive product grid with local images, a working search field, and category filters that update the catalog immediately.</p><p>The grid will show two columns on a narrow screen and expand when more space becomes available.</p><p>Search will inspect product names and descriptions.</p><p>The category buttons will switch between All, Audio, Wearables, Photography, Computers, and Accessories.</p><p>This is no longer a small adjustment to the old layout.</p><p>The storefront is being rebuilt while the inventory waits patiently in twenty neatly labeled boxes.</p><p>Before replacing the complete catalog screen, I create one more backup.</p><p>The product data and image mapping are already working, so this backup gives me a safe checkpoint before the interface receives its largest rewrite so far.</p><p>A backup is not glamorous, but neither is rebuilding a working file from memory at midnight.</p><pre>cd ~/offline_product_catalog<br><br>cp lib/main.dart \<br>  lib/main.dart.backup_before_searchable_grid</pre><pre>ls -lh lib/main.dart*</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/819/1*_UHoXVikPwIw4p2R2_VqFg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/819/1*uHVUxKfVHuFO3m6SXFOhpQ.png" /><figcaption>A fresh backup preserves the working twenty-product data before the catalog interface is rebuilt.</figcaption></figure><p>The catalog page is already stateful, which gives me a place to store two pieces of changing information:</p><p>the selected category and the current search query.</p><p>Whenever the user types into the search field or chooses a category, Flutter calls `setState()` and rebuilds the grid with only the matching products.</p><p>The product cards will also stop using icons.</p><p>Each card will now read its own local image path and display the corresponding product photograph from the asset folder.</p><pre>python3 - &lt;&lt;&#39;PY&#39;<br>from pathlib import Path<br><br>file_path = Path(&quot;lib/main.dart&quot;)<br>text = file_path.read_text()<br><br>class_marker = (<br>    &quot;class _MyHomePageState extends State&lt;MyHomePage&gt; {&quot;<br>)<br><br>if class_marker not in text:<br>    raise SystemExit(<br>        &quot;Could not find _MyHomePageState in lib/main.dart.&quot;<br>    )<br><br>state_fields = &quot;&quot;&quot;<br>  String _selectedCategory = &#39;All&#39;;<br>  String _searchQuery = &#39;&#39;;<br><br>&quot;&quot;&quot;<br><br>if &quot;String _selectedCategory&quot; not in text:<br>    text = text.replace(<br>        class_marker,<br>        class_marker + state_fields,<br>        1,<br>    )<br><br>method_marker = (<br>    &quot;  @override\n&quot;<br>    &quot;  Widget build(BuildContext context) {&quot;<br>)<br><br>method_start = text.find(method_marker)<br><br>if method_start == -1:<br>    raise SystemExit(&quot;Could not find the build method.&quot;)<br><br>opening_brace = text.find(&quot;{&quot;, method_start)<br><br>depth = 0<br>method_end = None<br><br>for index in range(opening_brace, len(text)):<br>    character = text[index]<br><br>    if character == &quot;{&quot;:<br>        depth += 1<br>    elif character == &quot;}&quot;:<br>        depth -= 1<br><br>        if depth == 0:<br>            method_end = index + 1<br>            break<br><br>if method_end is None:<br>    raise SystemExit(&quot;Could not locate the end of build().&quot;)<br><br>new_build_method = r&quot;&quot;&quot;  @override<br>  Widget build(BuildContext context) {<br>    const categories = [<br>      &#39;All&#39;,<br>      &#39;Audio&#39;,<br>      &#39;Wearables&#39;,<br>      &#39;Photography&#39;,<br>      &#39;Computers&#39;,<br>      &#39;Accessories&#39;,<br>    ];<br><br>    final normalizedQuery = _searchQuery.trim().toLowerCase();<br><br>    final filteredProducts = products.where((product) {<br>      final matchesCategory =<br>          _selectedCategory == &#39;All&#39; ||<br>          product.category == _selectedCategory;<br><br>      final matchesSearch =<br>          normalizedQuery.isEmpty ||<br>          product.name.toLowerCase().contains(normalizedQuery) ||<br>          product.description.toLowerCase().contains(normalizedQuery);<br><br>      return matchesCategory &amp;&amp; matchesSearch;<br>    }).toList();<br><br>    return Scaffold(<br>      appBar: AppBar(<br>        backgroundColor:<br>            Theme.of(context).colorScheme.inversePrimary,<br>        title: Text(widget.title),<br>      ),<br>      body: LayoutBuilder(<br>        builder: (context, constraints) {<br>          final width = constraints.maxWidth;<br><br>          final crossAxisCount = width &gt;= 1100<br>              ? 4<br>              : width &gt;= 700<br>              ? 3<br>              : 2;<br><br>          final childAspectRatio = width &gt;= 700 ? 0.78 : 0.67;<br><br>          return SingleChildScrollView(<br>            padding: const EdgeInsets.all(20),<br>            child: Column(<br>              crossAxisAlignment: CrossAxisAlignment.start,<br>              children: [<br>                const Text(<br>                  &#39;Our Products&#39;,<br>                  style: TextStyle(<br>                    fontSize: 28,<br>                    fontWeight: FontWeight.bold,<br>                  ),<br>                ),<br>                const SizedBox(height: 6),<br>                const Text(<br>                  &#39;Browse products available offline.&#39;,<br>                  style: TextStyle(fontSize: 16),<br>                ),<br>                const SizedBox(height: 20),<br>                TextField(<br>                  onChanged: (value) {<br>                    setState(() {<br>                      _searchQuery = value;<br>                    });<br>                  },<br>                  decoration: InputDecoration(<br>                    hintText: &#39;Search products...&#39;,<br>                    prefixIcon: const Icon(Icons.search),<br>                    suffixIcon: _searchQuery.isEmpty<br>                        ? null<br>                        : IconButton(<br>                            tooltip: &#39;Clear search&#39;,<br>                            onPressed: () {<br>                              setState(() {<br>                                _searchQuery = &#39;&#39;;<br>                              });<br>                            },<br>                            icon: const Icon(Icons.close),<br>                          ),<br>                    border: OutlineInputBorder(<br>                      borderRadius: BorderRadius.circular(14),<br>                    ),<br>                  ),<br>                ),<br>                const SizedBox(height: 18),<br>                SingleChildScrollView(<br>                  scrollDirection: Axis.horizontal,<br>                  child: Row(<br>                    children: categories.map((category) {<br>                      final isSelected =<br>                          category == _selectedCategory;<br><br>                      return Padding(<br>                        padding: const EdgeInsets.only(right: 10),<br>                        child: ChoiceChip(<br>                          label: Text(category),<br>                          selected: isSelected,<br>                          selectedColor:<br>                              const Color(0xFF5E35B1),<br>                          labelStyle: TextStyle(<br>                            color: isSelected<br>                                ? Colors.white<br>                                : Colors.black87,<br>                            fontWeight: FontWeight.w600,<br>                          ),<br>                          onSelected: (_) {<br>                            setState(() {<br>                              _selectedCategory = category;<br>                            });<br>                          },<br>                        ),<br>                      );<br>                    }).toList(),<br>                  ),<br>                ),<br>                const SizedBox(height: 22),<br>                Text(<br>                  &#39;${filteredProducts.length} products&#39;,<br>                  style: const TextStyle(<br>                    fontWeight: FontWeight.w600,<br>                    color: Colors.black54,<br>                  ),<br>                ),<br>                const SizedBox(height: 12),<br>                if (filteredProducts.isEmpty)<br>                  const Padding(<br>                    padding: EdgeInsets.symmetric(vertical: 60),<br>                    child: Center(<br>                      child: Column(<br>                        children: [<br>                          Icon(<br>                            Icons.search_off,<br>                            size: 52,<br>                            color: Colors.black38,<br>                          ),<br>                          SizedBox(height: 12),<br>                          Text(<br>                            &#39;No products found.&#39;,<br>                            style: TextStyle(<br>                              fontSize: 17,<br>                              fontWeight: FontWeight.w600,<br>                            ),<br>                          ),<br>                        ],<br>                      ),<br>                    ),<br>                  )<br>                else<br>                  GridView.builder(<br>                    shrinkWrap: true,<br>                    physics:<br>                        const NeverScrollableScrollPhysics(),<br>                    itemCount: filteredProducts.length,<br>                    gridDelegate:<br>                        SliverGridDelegateWithFixedCrossAxisCount(<br>                      crossAxisCount: crossAxisCount,<br>                      crossAxisSpacing: 14,<br>                      mainAxisSpacing: 14,<br>                      childAspectRatio: childAspectRatio,<br>                    ),<br>                    itemBuilder: (context, index) {<br>                      final product = filteredProducts[index];<br><br>                      return Card(<br>                        clipBehavior: Clip.antiAlias,<br>                        elevation: 1,<br>                        shape: RoundedRectangleBorder(<br>                          borderRadius:<br>                              BorderRadius.circular(16),<br>                        ),<br>                        child: Column(<br>                          crossAxisAlignment:<br>                              CrossAxisAlignment.start,<br>                          children: [<br>                            Expanded(<br>                              child: Container(<br>                                width: double.infinity,<br>                                color:<br>                                    const Color(0xFFF7F5FA),<br>                                child: Image.asset(<br>                                  product.imagePath,<br>                                  fit: BoxFit.contain,<br>                                  errorBuilder: (<br>                                    context,<br>                                    error,<br>                                    stackTrace,<br>                                  ) {<br>                                    return const Center(<br>                                      child: Icon(<br>                                        Icons.broken_image_outlined,<br>                                        size: 44,<br>                                      ),<br>                                    );<br>                                  },<br>                                ),<br>                              ),<br>                            ),<br>                            Padding(<br>                              padding:<br>                                  const EdgeInsets.fromLTRB(<br>                                12,<br>                                12,<br>                                12,<br>                                14,<br>                              ),<br>                              child: Column(<br>                                crossAxisAlignment:<br>                                    CrossAxisAlignment.start,<br>                                children: [<br>                                  Container(<br>                                    padding:<br>                                        const EdgeInsets.symmetric(<br>                                      horizontal: 8,<br>                                      vertical: 3,<br>                                    ),<br>                                    decoration: BoxDecoration(<br>                                      color: const Color(<br>                                        0xFFEDE7F6,<br>                                      ),<br>                                      borderRadius:<br>                                          BorderRadius.circular(20),<br>                                    ),<br>                                    child: Text(<br>                                      product.category,<br>                                      style: const TextStyle(<br>                                        color: Color(0xFF5E35B1),<br>                                        fontSize: 11,<br>                                        fontWeight:<br>                                            FontWeight.w700,<br>                                      ),<br>                                    ),<br>                                  ),<br>                                  const SizedBox(height: 8),<br>                                  Text(<br>                                    product.name,<br>                                    maxLines: 1,<br>                                    overflow:<br>                                        TextOverflow.ellipsis,<br>                                    style: const TextStyle(<br>                                      fontSize: 15,<br>                                      fontWeight:<br>                                          FontWeight.bold,<br>                                    ),<br>                                  ),<br>                                  const SizedBox(height: 4),<br>                                  Text(<br>                                    product.description,<br>                                    maxLines: 2,<br>                                    overflow:<br>                                        TextOverflow.ellipsis,<br>                                    style: const TextStyle(<br>                                      fontSize: 12,<br>                                      color: Colors.black54,<br>                                    ),<br>                                  ),<br>                                  const SizedBox(height: 10),<br>                                  Text(<br>                                    product.price,<br>                                    style: const TextStyle(<br>                                      color: Color(0xFF5E35B1),<br>                                      fontSize: 16,<br>                                      fontWeight:<br>                                          FontWeight.bold,<br>                                    ),<br>                                  ),<br>                                ],<br>                              ),<br>                            ),<br>                          ],<br>                        ),<br>                      );<br>                    },<br>                  ),<br>              ],<br>            ),<br>          );<br>        },<br>      ),<br>    );<br>  }&quot;&quot;&quot;<br><br>text = (<br>    text[:method_start]<br>    + new_build_method<br>    + text[method_end:]<br>)<br><br>file_path.write_text(text)<br><br>print(&quot;Searchable and filterable product grid created.&quot;)<br>print(&quot;The catalog now uses all 20 local product images.&quot;)<br>PY</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/819/1*V5vGxIv_qIOMDQmF24tN-Q.png" /><figcaption>The terminal replaces the old vertical list with a searchable, filterable, and responsive grid powered by twenty local product images.</figcaption></figure><p>The patch finishes successfully, so I open `main.dart` in Visual Studio Code and inspect the new screen structure.</p><p>The page now stores the selected category and search query as state.</p><p>The product list is filtered before the grid is built.</p><p>Each card reads its own local image path instead of displaying a generic Flutter icon.</p><p>This is the first version of the catalog where the interface, product data, and local assets are finally working as one system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/878/1*ULD-sTGYNBDW14lX3h4xUg.png" /><figcaption>Visual Studio Code shows the search query, selected category, and filtering logic that control which products appear.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/878/1*8WWpx_z_RoKkFxPfBNEgNA.png" /><figcaption>The new grid builder creates responsive product cards and loads every image directly from the local asset folder.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/878/1*dRG1_HA6Y-PAFmz0iUBfUw.png" /><figcaption>The catalog interface now includes a working search field and interactive category chips.</figcaption></figure><p>The screen has been rewritten, but I do not open Chrome immediately.</p><p>First, I format the updated file and let Flutter inspect the complete search, filter, image, and grid implementation.</p><p>This is a large enough change that optimism alone would be irresponsible.</p><pre>dart format lib/main.dart<br>flutter analyze</pre><p>The first analysis does not pass.</p><p>Flutter reports fourteen issues, but the pattern is more useful than the number.</p><p>The analyzer cannot find `_searchQuery` or `_selectedCategory`.</p><p>It also says that `widget` is undefined and that `setState()` does not exist for `MyApp`.</p><p>Those names only make sense inside the State class that controls the catalog screen.</p><p>The searchable grid code was inserted into `MyApp`, which is a StatelessWidget, instead of `_MyHomePageState`.</p><p>The feature itself is not broken.</p><p>It simply walked into the wrong room and started rearranging the furniture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/829/1*YK9Xrq1qN4utRb8Z4Ojlfg.png" /><figcaption>Flutter reports that the search state, selected category, `widget`, and `setState()` are being used outside the catalog’s State class.</figcaption></figure><p>The package update messages are only informational.</p><p>The real problem is structural.</p><p>`MyApp` creates the application, but `_MyHomePageState` controls the changing catalog screen.</p><p>Search and category filters need `setState()`, so their variables and interface must live inside `_MyHomePageState`.</p><pre>grep -nE \<br>&quot;^class MyApp|^class MyHomePage|^class _MyHomePageState|String _selectedCategory|String _searchQuery|Widget build&quot; \<br>lib/main.dart</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/829/1*-d-nCy7v9YFKTRGLbPoBkw.png" /><figcaption>The terminal inspection reveals that the searchable interface was inserted into the wrong Flutter class.</figcaption></figure><p>Before repairing the file, I inspect the class boundaries.</p><p>The terminal reveals that the new build method and its state variables were separated.</p><p>The interface landed inside `MyApp`, while the state variables remained inside `_MyHomePageState`.</p><p>Flutter was essentially handed a light switch in one room and the lamp in another.</p><p>Instead of patching fourteen symptoms individually, I return to the clean backup created immediately before the UI rebuild.</p><p>The backup already contains twenty products and their local image paths.</p><p>I only need to apply the searchable grid again, this time inside the correct State class.</p><p>This is exactly why the backup was created.</p><p>It has been waiting quietly for its heroic entrance.</p><pre>python3 - &lt;&lt;&#39;PY&#39;<br>from pathlib import Path<br>import re<br><br>file_path = Path(&quot;lib/main.dart&quot;)<br>backup_path = Path(<br>    &quot;lib/main.dart.backup_before_searchable_grid&quot;<br>)<br><br>if not backup_path.exists():<br>    raise SystemExit(<br>        &quot;Backup not found: &quot;<br>        &quot;lib/main.dart.backup_before_searchable_grid&quot;<br>    )<br><br>text = backup_path.read_text()<br><br>image_path_count = text.count(<br>    &quot;imagePath: &#39;assets/products/&quot;<br>)<br><br>if image_path_count != 20:<br>    raise SystemExit(<br>        &quot;The backup does not contain all 20 image paths. &quot;<br>        f&quot;Found: {image_path_count}&quot;<br>    )<br><br>class_pattern = re.compile(<br>    r&quot;class _MyHomePageState &quot;<br>    r&quot;extends State&lt;MyHomePage&gt;\s*\{&quot;<br>)<br><br>class_match = class_pattern.search(text)<br><br>if not class_match:<br>    raise SystemExit(<br>        &quot;_MyHomePageState was not found.&quot;<br>    )<br><br>class_open = text.find(&quot;{&quot;, class_match.start())<br><br>def find_matching_brace(source, opening_index):<br>    depth = 0<br><br>    for index in range(opening_index, len(source)):<br>        if source[index] == &quot;{&quot;:<br>            depth += 1<br>        elif source[index] == &quot;}&quot;:<br>            depth -= 1<br><br>            if depth == 0:<br>                return index<br><br>    raise RuntimeError(&quot;Matching brace was not found.&quot;)<br><br>class_close = find_matching_brace(<br>    text,<br>    class_open,<br>)<br><br>class_body = text[<br>    class_open + 1 : class_close<br>]<br><br>build_pattern = re.compile(<br>    r&quot;  @override\s*\n&quot;<br>    r&quot;  Widget build\(BuildContext context\)\s*\{&quot;<br>)<br><br>build_match = build_pattern.search(class_body)<br><br>if not build_match:<br>    raise SystemExit(<br>        &quot;The build method inside &quot;<br>        &quot;_MyHomePageState was not found.&quot;<br>    )<br><br>build_start = (<br>    class_open<br>    + 1<br>    + build_match.start()<br>)<br><br>build_open = text.find(&quot;{&quot;, build_start)<br>build_close = find_matching_brace(<br>    text,<br>    build_open,<br>)<br><br>new_build_method = r&quot;&quot;&quot;  @override<br>  Widget build(BuildContext context) {<br>    const categories = [<br>      &#39;All&#39;,<br>      &#39;Audio&#39;,<br>      &#39;Wearables&#39;,<br>      &#39;Photography&#39;,<br>      &#39;Computers&#39;,<br>      &#39;Accessories&#39;,<br>    ];<br><br>    final normalizedQuery =<br>        _searchQuery.trim().toLowerCase();<br><br>    final filteredProducts = products.where((product) {<br>      final matchesCategory =<br>          _selectedCategory == &#39;All&#39; ||<br>          product.category == _selectedCategory;<br><br>      final matchesSearch =<br>          normalizedQuery.isEmpty ||<br>          product.name<br>              .toLowerCase()<br>              .contains(normalizedQuery) ||<br>          product.description<br>              .toLowerCase()<br>              .contains(normalizedQuery);<br><br>      return matchesCategory &amp;&amp; matchesSearch;<br>    }).toList();<br><br>    return Scaffold(<br>      appBar: AppBar(<br>        backgroundColor:<br>            Theme.of(context).colorScheme.inversePrimary,<br>        title: Text(widget.title),<br>      ),<br>      body: LayoutBuilder(<br>        builder: (context, constraints) {<br>          final width = constraints.maxWidth;<br><br>          final crossAxisCount = width &gt;= 1100<br>              ? 4<br>              : width &gt;= 700<br>                  ? 3<br>                  : 2;<br><br>          final childAspectRatio =<br>              width &gt;= 700 ? 0.78 : 0.67;<br><br>          return SingleChildScrollView(<br>            padding: const EdgeInsets.all(20),<br>            child: Column(<br>              crossAxisAlignment:<br>                  CrossAxisAlignment.start,<br>              children: [<br>                const Text(<br>                  &#39;Our Products&#39;,<br>                  style: TextStyle(<br>                    fontSize: 28,<br>                    fontWeight: FontWeight.bold,<br>                  ),<br>                ),<br>                const SizedBox(height: 6),<br>                const Text(<br>                  &#39;Browse products available offline.&#39;,<br>                  style: TextStyle(fontSize: 16),<br>                ),<br>                const SizedBox(height: 20),<br>                TextField(<br>                  onChanged: (value) {<br>                    setState(() {<br>                      _searchQuery = value;<br>                    });<br>                  },<br>                  decoration: InputDecoration(<br>                    hintText: &#39;Search products...&#39;,<br>                    prefixIcon:<br>                        const Icon(Icons.search),<br>                    border: OutlineInputBorder(<br>                      borderRadius:<br>                          BorderRadius.circular(14),<br>                    ),<br>                  ),<br>                ),<br>                const SizedBox(height: 18),<br>                SingleChildScrollView(<br>                  scrollDirection: Axis.horizontal,<br>                  child: Row(<br>                    children:<br>                        categories.map((category) {<br>                      final isSelected =<br>                          category ==<br>                              _selectedCategory;<br><br>                      return Padding(<br>                        padding:<br>                            const EdgeInsets.only(<br>                          right: 10,<br>                        ),<br>                        child: ChoiceChip(<br>                          label: Text(category),<br>                          selected: isSelected,<br>                          selectedColor:<br>                              const Color(<br>                            0xFF5E35B1,<br>                          ),<br>                          labelStyle: TextStyle(<br>                            color: isSelected<br>                                ? Colors.white<br>                                : Colors.black87,<br>                            fontWeight:<br>                                FontWeight.w600,<br>                          ),<br>                          onSelected: (_) {<br>                            setState(() {<br>                              _selectedCategory =<br>                                  category;<br>                            });<br>                          },<br>                        ),<br>                      );<br>                    }).toList(),<br>                  ),<br>                ),<br>                const SizedBox(height: 22),<br>                Text(<br>                  &#39;${filteredProducts.length} products&#39;,<br>                  style: const TextStyle(<br>                    fontWeight: FontWeight.w600,<br>                    color: Colors.black54,<br>                  ),<br>                ),<br>                const SizedBox(height: 12),<br>                if (filteredProducts.isEmpty)<br>                  const Padding(<br>                    padding:<br>                        EdgeInsets.symmetric(<br>                      vertical: 60,<br>                    ),<br>                    child: Center(<br>                      child: Column(<br>                        children: [<br>                          Icon(<br>                            Icons.search_off,<br>                            size: 52,<br>                            color: Colors.black38,<br>                          ),<br>                          SizedBox(height: 12),<br>                          Text(<br>                            &#39;No products found.&#39;,<br>                            style: TextStyle(<br>                              fontSize: 17,<br>                              fontWeight:<br>                                  FontWeight.w600,<br>                            ),<br>                          ),<br>                        ],<br>                      ),<br>                    ),<br>                  )<br>                else<br>                  GridView.builder(<br>                    shrinkWrap: true,<br>                    physics:<br>                        const NeverScrollableScrollPhysics(),<br>                    itemCount:<br>                        filteredProducts.length,<br>                    gridDelegate:<br>                        SliverGridDelegateWithFixedCrossAxisCount(<br>                      crossAxisCount:<br>                          crossAxisCount,<br>                      crossAxisSpacing: 14,<br>                      mainAxisSpacing: 14,<br>                      childAspectRatio:<br>                          childAspectRatio,<br>                    ),<br>                    itemBuilder: (<br>                      context,<br>                      index,<br>                    ) {<br>                      final product =<br>                          filteredProducts[index];<br><br>                      return Card(<br>                        clipBehavior:<br>                            Clip.antiAlias,<br>                        elevation: 1,<br>                        shape:<br>                            RoundedRectangleBorder(<br>                          borderRadius:<br>                              BorderRadius.circular(<br>                            16,<br>                          ),<br>                        ),<br>                        child: Column(<br>                          crossAxisAlignment:<br>                              CrossAxisAlignment<br>                                  .start,<br>                          children: [<br>                            Expanded(<br>                              child: Container(<br>                                width:<br>                                    double.infinity,<br>                                color:<br>                                    const Color(<br>                                  0xFFF7F5FA,<br>                                ),<br>                                child: Image.asset(<br>                                  product.imagePath,<br>                                  fit:<br>                                      BoxFit.contain,<br>                                  errorBuilder: (<br>                                    context,<br>                                    error,<br>                                    stackTrace,<br>                                  ) {<br>                                    return const Center(<br>                                      child: Icon(<br>                                        Icons<br>                                            .broken_image_outlined,<br>                                        size: 44,<br>                                      ),<br>                                    );<br>                                  },<br>                                ),<br>                              ),<br>                            ),<br>                            Padding(<br>                              padding:<br>                                  const EdgeInsets<br>                                      .fromLTRB(<br>                                12,<br>                                12,<br>                                12,<br>                                14,<br>                              ),<br>                              child: Column(<br>                                crossAxisAlignment:<br>                                    CrossAxisAlignment<br>                                        .start,<br>                                children: [<br>                                  Container(<br>                                    padding:<br>                                        const EdgeInsets<br>                                            .symmetric(<br>                                      horizontal: 8,<br>                                      vertical: 3,<br>                                    ),<br>                                    decoration:<br>                                        BoxDecoration(<br>                                      color:<br>                                          const Color(<br>                                        0xFFEDE7F6,<br>                                      ),<br>                                      borderRadius:<br>                                          BorderRadius<br>                                              .circular(<br>                                        20,<br>                                      ),<br>                                    ),<br>                                    child: Text(<br>                                      product.category,<br>                                      style:<br>                                          const TextStyle(<br>                                        color: Color(<br>                                          0xFF5E35B1,<br>                                        ),<br>                                        fontSize: 11,<br>                                        fontWeight:<br>                                            FontWeight<br>                                                .w700,<br>                                      ),<br>                                    ),<br>                                  ),<br>                                  const SizedBox(<br>                                    height: 8,<br>                                  ),<br>                                  Text(<br>                                    product.name,<br>                                    maxLines: 1,<br>                                    overflow:<br>                                        TextOverflow<br>                                            .ellipsis,<br>                                    style:<br>                                        const TextStyle(<br>                                      fontSize: 15,<br>                                      fontWeight:<br>                                          FontWeight<br>                                              .bold,<br>                                    ),<br>                                  ),<br>                                  const SizedBox(<br>                                    height: 4,<br>                                  ),<br>                                  Text(<br>                                    product<br>                                        .description,<br>                                    maxLines: 2,<br>                                    overflow:<br>                                        TextOverflow<br>                                            .ellipsis,<br>                                    style:<br>                                        const TextStyle(<br>                                      fontSize: 12,<br>                                      color:<br>                                          Colors.black54,<br>                                    ),<br>                                  ),<br>                                  const SizedBox(<br>                                    height: 10,<br>                                  ),<br>                                  Text(<br>                                    product.price,<br>                                    style:<br>                                        const TextStyle(<br>                                      color: Color(<br>                                        0xFF5E35B1,<br>                                      ),<br>                                      fontSize: 16,<br>                                      fontWeight:<br>                                          FontWeight<br>                                              .bold,<br>                                    ),<br>                                  ),<br>                                ],<br>                              ),<br>                            ),<br>                          ],<br>                        ),<br>                      );<br>                    },<br>                  ),<br>              ],<br>            ),<br>          );<br>        },<br>      ),<br>    );<br>  }&quot;&quot;&quot;<br><br>text = (<br>    text[:build_start]<br>    + new_build_method<br>    + text[build_close + 1 :]<br>)<br><br>class_match = class_pattern.search(text)<br>class_open = text.find(&quot;{&quot;, class_match.start())<br><br>state_fields = &quot;&quot;&quot;<br>  String _selectedCategory = &#39;All&#39;;<br>  String _searchQuery = &#39;&#39;;<br><br>&quot;&quot;&quot;<br><br>current_class_close = find_matching_brace(<br>    text,<br>    class_open,<br>)<br><br>current_class_body = text[<br>    class_open + 1 : current_class_close<br>]<br><br>if &quot;String _selectedCategory&quot; not in current_class_body:<br>    text = (<br>        text[:class_open + 1]<br>        + state_fields<br>        + text[class_open + 1 :]<br>    )<br><br>file_path.write_text(text)<br><br>print(&quot;Restored the clean pre-grid backup.&quot;)<br>print(<br>    &quot;Search state added to &quot;<br>    &quot;_MyHomePageState.&quot;<br>)<br>print(<br>    &quot;The searchable grid was inserted &quot;<br>    &quot;into the correct build method.&quot;<br>)<br>PY</pre><p>Restored the clean pre-grid backup.<br>Search state added to _MyHomePageState.<br>The searchable grid was inserted into the correct build method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/829/1*v9sBsAZDYoA90syhvVonww.png" /><figcaption>The clean backup is restored, and the searchable grid is inserted into the correct `_MyHomePageState` class.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/829/1*uKDL2mi-krs8MRES9YhGzQ.png" /><figcaption>No issues found! After moving the interactive catalog into the correct State class, Flutter completes the analysis with no issues.</figcaption></figure><p>I format the repaired file and run the analyzer again.</p><p>This time, Flutter finds the search variables, `widget.title`, and `setState()` inside the correct State class.</p><p>The fourteen issues disappear.</p><p>The mistake was not hidden or deleted from the story.</p><p>It became part of the story, because understanding why a fix works is far more useful than pretending the first attempt was flawless.</p><p>The analyzer is clean, but I do not use a normal hot reload this time.</p><p>During the previous steps, I added twenty new image files and registered their directory inside `pubspec.yaml`.</p><p>A lowercase `r` is excellent for ordinary Dart and widget changes, but this update also changes the assets packaged with the application.</p><p>To make sure Flutter rebuilds the asset bundle and includes every product image, I stop the current session and run the app again from the beginning.</p><p>Hot reload can repaint the store.</p><p>This time, I also changed what arrived in the delivery truck.</p><p>The running Flutter session closes, but the project and all of its files remain exactly where they are.</p><p>I am not rebuilding the project from scratch.</p><p>I am only starting a fresh development session so Flutter can collect the newly registered assets and package them correctly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/829/1*caXxvsNy73BWqDVHig5GVw.png" /><figcaption>The previous Flutter session is stopped so the newly added product assets can be included in a fresh build.</figcaption></figure><pre>flutter run -d chrome</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*BF9A4LGcKHRK0jTXTnziCA.png" /><figcaption>The terminal replaces the old vertical list with a searchable, filterable, and responsive grid powered by twenty local product images.</figcaption></figure><p>The patch finishes successfully, so I open `main.dart` in Visual Studio Code and inspect the new screen structure.</p><p>The page now stores the selected category and search query as state.</p><p>The product list is filtered before the grid is built.</p><p>Each card reads its own local image path instead of displaying a generic Flutter icon.</p><p>This is the first version of the catalog where the interface, product data, and local assets are finally working as one system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/869/1*fn16up1qNUnktEZhd4LsUw.png" /><figcaption>Visual Studio Code shows the search query, selected category, and filtering logic that control which products appear.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/869/1*h4FqAACt8EgUq2V7IEef6Q.png" /><figcaption>The new grid builder creates responsive product cards and loads every image directly from the local asset folder.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/869/1*m54gCy_Vh9EHvVv7CnM3WQ.png" /><figcaption>The catalog interface now includes a working search field and interactive category chips.</figcaption></figure><p>The screen has been rewritten, but I do not open Chrome immediately.</p><p>First, I format the updated file and let Flutter inspect the complete search, filter, image, and grid implementation.</p><p>This is a large enough change that optimism alone would be irresponsible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/819/1*Kgzu1GHQ1qkxoRTiKYMo6g.png" /><figcaption>Dart formats the rebuilt catalog screen, and Flutter confirms that the search, filters, local images, and responsive grid contain no code issues.</figcaption></figure><p>Flutter finishes the fresh build and opens the catalog in Chrome.</p><p>This is the first moment when all the work from Episode 18 appears on one screen.</p><p>The old vertical list is gone.</p><p>In its place, the app now has a search field, category filters, a responsive product grid, and local images for all twenty items.</p><p>The catalog reports “20 products,” confirming that the complete inventory has reached the interface.</p><p>What began as three polite cards now looks much closer to an actual storefront.</p><p>The delivery truck did not merely arrive.</p><p>It brought shelves.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/1*H_O_YA0ndsYHKM83nk3AmA.png" /><figcaption>The rebuilt catalog opens with twenty local product images, a responsive grid, working search, and interactive category filters.</figcaption></figure><p>The full catalog looks correct, but the category buttons still need to prove that they are more than decorative pills.</p><p>I select Audio.</p><p>The grid immediately shrinks from twenty products to four:</p><p>Wireless Headphones <br>Bluetooth Speaker <br>Wireless Earbuds <br>Portable Soundbar</p><p>The product counter also changes from “20 products” to “4 products.”</p><p>Flutter is not hiding cards with visual tricks. It is rebuilding the grid from the filtered product data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*6eMp7L6UjqwmViRaDHqhvw.png" /><figcaption>Selecting Audio reduces the catalog to four matching products and updates the product counter immediately.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/657/1*Q-SwmBAwOIbjSF2Xdw-VRA.png" /><figcaption>Searching for “camera” instantly narrows the twenty-product inventory to four relevant results.</figcaption></figure><p>Next, I return to All and test the search field.</p><p>I type “camera.”</p><p>The catalog narrows the inventory to camera-related products, including Digital Camera, Action Camera, Instant Camera, and Camera Lens.</p><p>This is why expanding the inventory before building search was worth the effort.</p><p>Searching three products would have felt like asking a librarian to locate one of three books sitting on the same table.</p><p>With twenty products, the feature finally earns its place on the screen.</p><p>With the filters cleared, I scroll through the complete catalog.</p><p>The grid moves from Audio products into Wearables, Photography, Computers, and finally Accessories.</p><p>At the bottom, I find Minimal Backpack, Power Bank, USB-C Hub, and Phone Stand.</p><p>All twenty products remain accessible, and every image stays attached to the correct name, category, and price.</p><p>Scrolling has finally stopped being ceremonial.</p><p>It now has twenty products worth carrying.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/657/1*WzpRQGEvWvLgWt6fgF9Ijw.png" /><figcaption>The bottom of the grid confirms that all twenty products remain accessible and correctly matched with their local images.</figcaption></figure><p>Episode 18 began with three products arranged in a simple vertical list.</p><p>It ends with twenty products displayed in a responsive, image-based grid.</p><p>Along the way, I expanded the inventory across five categories, created twenty local image assets from one master sheet, connected every image to its matching product, and rebuilt the catalog interface.</p><p>The app now includes:</p><p>- twenty offline product images,<br>- a responsive product grid,<br>- working category filters,<br>- real-time product search,<br>- an updated product counter,<br>- and a clear empty state when no results are found.</p><p>The transformation is difficult to miss.</p><p>This no longer feels like a Flutter starter project wearing a catalog costume.</p><p>It feels like the beginning of a real offline product application.</p><p>The most satisfying part of this episode was watching one master image become twenty organized product assets through the Linux terminal.</p><p>Each image now travels with its own name, category, description, and price.</p><p>Search works.</p><p>Filters work.</p><p>Scrolling finally has enough inventory to justify the exercise.</p><p>There is still more to build, but the catalog has crossed an important line.</p><p>It is no longer waiting to become useful.</p><p>It already is.</p><p>In Episode 19, I will make every product card interactive.</p><p>Selecting a product will open a dedicated detail page with a larger image, complete product information, and a proper back-navigation flow.</p><p>The storefront is ready.</p><p>Next, I am opening the product boxes.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d55eddb3168f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Episode 17: Adding Categories to the Flutter Product Catalog]]></title>
            <link>https://medium.com/@lenakendari/episode-17-adding-categories-to-the-flutter-product-catalog-8a939d60f1aa?source=rss-932b58a7a66a------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a939d60f1aa</guid>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[ui-design]]></category>
            <dc:creator><![CDATA[Atelier Flutter]]></dc:creator>
            <pubDate>Fri, 17 Jul 2026 05:40:18 GMT</pubDate>
            <atom:updated>2026-07-17T05:40:18.409Z</atom:updated>
            <content:encoded><![CDATA[<p>I extend the Product model with category labels and display them on every card without rebuilding the catalog layout.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bvJphRZBdSZBYmTY0xsvBw.png" /></figure><p>Episode 17 begins with a catalog that is cleaner underneath, but still a little quiet on the screen.</p><p>The product data now lives inside one organized list, and Flutter builds every card automatically. That was an important step, but all three products still look almost identical.</p><p>A pair of headphones, a smart watch, and a digital camera should not feel like they came from the same anonymous cardboard box.</p><p>So in this episode, I will give every product a category and display that category directly on the card.</p><p>I will extend the `Product` model, add category information to the product list, and update the card layout so the new labels are easy to notice.</p><p>I will also improve the spacing inside each card and make the product information feel more organized.</p><p>The catalog will still use the same reusable structure from Episode 16, but the result on the screen should feel more informative and more alive.</p><p>The stockroom is organized.</p><p>Now it is time to put labels on the shelves.</p><p>Before adding category labels, I first locate the three parts of `main.dart` that need to change:</p><p>- the `Product` model,<br>- the product list,<br>- and the card builder.</p><p>The structure from Episode 16 is already working, so I do not need to rebuild anything. I only need to extend it carefully.</p><p>A good refactor should grow like a bookshelf, not collapse like furniture assembled without the manual.</p><pre>cd ~/offline_product_catalog<br>grep -nE &quot;class Product|const products|products\.map&quot; lib/main.dart</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/765/1*00lMdRZ76x1nvNYvczq-_w.png" /><figcaption>The terminal locates the product model, product list, and reusable card builder that will be updated with category information.</figcaption></figure><p>The three important sections are now identified, so I can update the data and the interface together.</p><p>First, I will extend the `Product` model with a category field.</p><p>Then I will give each product its own category:</p><p>Wireless Headphones belongs to Audio.</p><p>Smart Watch belongs to Wearables.</p><p>Digital Camera belongs to Photography.</p><p>I will also redesign the cards with clearer spacing, a category label, a dedicated icon box, and a stronger price style.</p><p>The reusable catalog structure will stay intact. It is simply getting better clothes.</p><pre>cp lib/main.dart lib/main.dart.backup_episode17<br><br>python3 - &lt;&lt;&#39;PY&#39;<br>from pathlib import Path<br><br>file_path = Path(&quot;lib/main.dart&quot;)<br>text = file_path.read_text()<br><br>old_constructor = &quot;&quot;&quot;  const Product({<br>    required this.name,<br>    required this.description,<br>    required this.price,<br>    required this.icon,<br>  });&quot;&quot;&quot;<br><br>new_constructor = &quot;&quot;&quot;  const Product({<br>    required this.name,<br>    required this.description,<br>    required this.price,<br>    required this.icon,<br>    required this.category,<br>  });&quot;&quot;&quot;<br><br>old_fields = &quot;&quot;&quot;  final String price;<br>  final IconData icon;&quot;&quot;&quot;<br><br>new_fields = &quot;&quot;&quot;  final String price;<br>  final IconData icon;<br>  final String category;&quot;&quot;&quot;<br><br>product_updates = {<br>    &quot;&quot;&quot;    icon: Icons.headphones,<br>  ),&quot;&quot;&quot;: &quot;&quot;&quot;    icon: Icons.headphones,<br>    category: &#39;Audio&#39;,<br>  ),&quot;&quot;&quot;,<br>    &quot;&quot;&quot;    icon: Icons.watch,<br>  ),&quot;&quot;&quot;: &quot;&quot;&quot;    icon: Icons.watch,<br>    category: &#39;Wearables&#39;,<br>  ),&quot;&quot;&quot;,<br>    &quot;&quot;&quot;    icon: Icons.camera_alt,<br>  ),&quot;&quot;&quot;: &quot;&quot;&quot;    icon: Icons.camera_alt,<br>    category: &#39;Photography&#39;,<br>  ),&quot;&quot;&quot;,<br>}<br><br>old_builder = &quot;&quot;&quot;            ...products.map(<br>              (product) =&gt; Padding(<br>                padding: const EdgeInsets.only(bottom: 12),<br>                child: Card(<br>                  child: ListTile(<br>                    leading: Icon(product.icon),<br>                    title: Text(product.name),<br>                    subtitle: Text(product.description),<br>                    trailing: Text(product.price),<br>                  ),<br>                ),<br>              ),<br>            ),&quot;&quot;&quot;<br><br>new_builder = &quot;&quot;&quot;            ...products.map(<br>              (product) =&gt; Padding(<br>                padding: const EdgeInsets.only(bottom: 16),<br>                child: Card(<br>                  elevation: 1,<br>                  shape: RoundedRectangleBorder(<br>                    borderRadius: BorderRadius.circular(16),<br>                  ),<br>                  child: Padding(<br>                    padding: const EdgeInsets.all(16),<br>                    child: Row(<br>                      crossAxisAlignment: CrossAxisAlignment.start,<br>                      children: [<br>                        Container(<br>                          width: 52,<br>                          height: 52,<br>                          decoration: BoxDecoration(<br>                            color: const Color(0xFFEDE7F6),<br>                            borderRadius: BorderRadius.circular(14),<br>                          ),<br>                          child: Icon(<br>                            product.icon,<br>                            size: 28,<br>                            color: const Color(0xFF5E35B1),<br>                          ),<br>                        ),<br>                        const SizedBox(width: 16),<br>                        Expanded(<br>                          child: Column(<br>                            crossAxisAlignment: CrossAxisAlignment.start,<br>                            children: [<br>                              Container(<br>                                padding: const EdgeInsets.symmetric(<br>                                  horizontal: 10,<br>                                  vertical: 4,<br>                                ),<br>                                decoration: BoxDecoration(<br>                                  color: const Color(0xFF5E35B1),<br>                                  borderRadius: BorderRadius.circular(20),<br>                                ),<br>                                child: Text(<br>                                  product.category,<br>                                  style: const TextStyle(<br>                                    color: Colors.white,<br>                                    fontSize: 12,<br>                                    fontWeight: FontWeight.w600,<br>                                  ),<br>                                ),<br>                              ),<br>                              const SizedBox(height: 8),<br>                              Text(<br>                                product.name,<br>                                style: const TextStyle(<br>                                  fontSize: 17,<br>                                  fontWeight: FontWeight.bold,<br>                                ),<br>                              ),<br>                              const SizedBox(height: 4),<br>                              Text(product.description),<br>                            ],<br>                          ),<br>                        ),<br>                        const SizedBox(width: 12),<br>                        Text(<br>                          product.price,<br>                          style: const TextStyle(<br>                            fontWeight: FontWeight.bold,<br>                            color: Color(0xFF5E35B1),<br>                          ),<br>                        ),<br>                      ],<br>                    ),<br>                  ),<br>                ),<br>              ),<br>            ),&quot;&quot;&quot;<br><br>required_blocks = [<br>    old_constructor,<br>    old_fields,<br>    old_builder,<br>]<br><br>for block in required_blocks:<br>    if block not in text:<br>        raise SystemExit(&quot;A required Episode 16 code block was not found.&quot;)<br><br>text = text.replace(old_constructor, new_constructor, 1)<br>text = text.replace(old_fields, new_fields, 1)<br><br>for old, new in product_updates.items():<br>    if old not in text:<br>        raise SystemExit(f&quot;Product entry was not found:\n{old}&quot;)<br>    text = text.replace(old, new, 1)<br><br>text = text.replace(old_builder, new_builder, 1)<br><br>file_path.write_text(text)<br>print(&quot;Categories and redesigned product cards added successfully.&quot;)<br>PY</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/765/1*s6QNQeCH5-iktRgwIaJo_g.png" /><figcaption>The terminal confirms that category data and the redesigned product cards were added successfully.</figcaption></figure><p>After the patch finishes, I open `main.dart` in Visual Studio Code.</p><p>The `Product` model now includes a category field, and every item in the product list has its own label.</p><p>The product data is becoming more descriptive without returning to repeated card code.</p><pre>required this.category,</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/910/1*DPdfNQp0isnMNEG5iOJmvg.png" /><figcaption>Visual Studio Code shows the new category field and the category assigned to every product.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/609/1*Tox_Jx2kdtSF1728LX0zXQ.png" /><figcaption>The reusable card builder now displays a category label, a styled icon, and clearer product information.</figcaption></figure><pre>dart format lib/main.dart<br>flutter analyze</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/609/1*6JfCw3dpeoggWZCTb5eABQ.png" /><figcaption>Dart formats the updated layout, and Flutter confirms that the new category system has no code issues.</figcaption></figure><p>The code is clean, so I run the app in Chrome to see whether the new category system appears correctly on the screen.</p><p>I return to the terminal and start the Flutter web app:</p><pre>flutter run -d chrome</pre><p>Flutter builds the project and opens the catalog in the browser.</p><p>This time, the change is immediately visible.</p><p>Each product card now has a category label above the product name.</p><p>Wireless Headphones is marked as Audio.</p><p>Smart Watch is marked as Wearables.</p><p>Digital Camera is marked as Photography.</p><p>The icons also sit inside their own styled containers, while the prices stand out more clearly on the right side.</p><p>The catalog still uses the same product list from Episode 16, but the interface now communicates much more information.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/609/1*iR-ECantkQBdD6nbe2ctEQ.png" /><figcaption>The redesigned catalog appears in Chrome with category labels, styled icons, clearer spacing, and stronger price text.</figcaption></figure><p>I check each card to make sure Flutter is displaying the correct category from the product list.</p><p>Wireless Headphones shows Audio.</p><p>Smart Watch shows Wearables.</p><p>Digital Camera shows Photography.</p><p>This confirms that the category labels are not fixed text copied into the layout. Each label comes directly from its own product data.</p><p>The reusable card builder is doing the work, while the product list remains the single source of truth.</p><p>The interface looks more detailed, but the code behind it is still organized.</p><p>Episode 17 began with three products using the same simple card layout.</p><p>I extended the Product model with a category field, assigned a different category to every product, and updated the reusable card builder.</p><p>The catalog now displays more useful information without returning to repeated widget code.</p><p>I also improved the icons, spacing, card shape, and price styling.</p><p>The shelves were already organized.</p><p>Now they finally have labels.</p><p>In Episode 18, I will turn those category labels into an interactive filter.</p><p>Instead of only reading Audio, Wearables, and Photography, the user will be able to select a category and control which products appear on the screen.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a939d60f1aa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Episode 16: Moving Product Data Out of the Flutter Layout]]></title>
            <link>https://medium.com/@lenakendari/episode-16-moving-product-data-out-of-the-flutter-layout-5720261dd929?source=rss-932b58a7a66a------2</link>
            <guid isPermaLink="false">https://medium.com/p/5720261dd929</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programing]]></category>
            <dc:creator><![CDATA[Atelier Flutter]]></dc:creator>
            <pubDate>Fri, 17 Jul 2026 05:20:03 GMT</pubDate>
            <atom:updated>2026-07-17T05:20:03.502Z</atom:updated>
            <content:encoded><![CDATA[<p>I replace repeated product details with a cleaner data structure, making the catalog easier to expand without copying the same widget again and again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nqMonpQXgLCOeLbBopxhhw.png" /></figure><p>Episode 16 begins with a catalog that already works.</p><p>Three products appear on the screen, the page can scroll, and the layout is finally starting to feel useful.</p><p>But there is one problem hiding behind the clean interface.</p><p>Every product is still written directly inside the Flutter layout.</p><p>That works for three items. It becomes much less charming at thirty.</p><p>So in this episode, I will separate the product data from the page design.</p><p>The catalog should keep looking the same, but the code underneath it will become cleaner, easier to read, and much easier to expand.</p><p>The shelves are staying. I am only reorganizing the stockroom.</p><p>Before changing the structure, I first inspect the part of `main.dart` that currently contains the three product cards.</p><p>I want to see the exact section that needs to be cleaned up, rather than replacing code blindly and hoping Flutter forgives me.</p><p>From the terminal, I search for the product names:</p><pre>cd ~/offline_product_catalog<br>grep -nE &quot;Wireless Headphones|Smart Watch|Digital Camera&quot; lib/main.dart</pre><p>The terminal shows where each product is written inside the layout.</p><p>This confirms the problem: the product data and the user interface are still mixed together in the same block of code.</p><p>The next step is to separate them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*A3FCoBNpAx1DzroBf0GQew.png" /><figcaption>The terminal locates all three product entries inside `main.dart`, showing exactly where the data is still mixed with the layout.</figcaption></figure><p>The search gives me the line numbers, but I need to see the complete block before changing its structure.</p><p>So I print the surrounding section of `main.dart` directly in the terminal.</p><p>This lets me inspect the current layout from the catalog heading down to the final product card.</p><p>No guessing. No code surgery with the lights turned off.</p><pre>nl -ba lib/main.dart | sed -n &#39;55,115p&#39;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sMVn1FNC901GTwp0xaxrRg.png" /><figcaption>The terminal displays the complete catalog section, giving me a clear view of the repeated product cards before I refactor them.</figcaption></figure><pre>cp lib/main.dart lib/main.dart.backup_episode16</pre><pre>python3 - &lt;&lt;&#39;PY&#39;<br>from pathlib import Path<br><br>file_path = Path(&quot;lib/main.dart&quot;)<br>text = file_path.read_text()<br><br>class_marker = &quot;class MyApp extends StatelessWidget {&quot;<br><br>product_model = &quot;&quot;&quot;class Product {<br>  const Product({<br>    required this.name,<br>    required this.description,<br>    required this.price,<br>    required this.icon,<br>  });<br><br>  final String name;<br>  final String description;<br>  final String price;<br>  final IconData icon;<br>}<br><br>const products = [<br>  Product(<br>    name: &#39;Wireless Headphones&#39;,<br>    description: &#39;Compact audio for everyday use&#39;,<br>    price: &#39;\\$49.00&#39;,<br>    icon: Icons.headphones,<br>  ),<br>  Product(<br>    name: &#39;Smart Watch&#39;,<br>    description: &#39;Track activity and stay connected&#39;,<br>    price: &#39;\\$89.00&#39;,<br>    icon: Icons.watch,<br>  ),<br>  Product(<br>    name: &#39;Digital Camera&#39;,<br>    description: &#39;Capture memories in high quality&#39;,<br>    price: &#39;\\$299.00&#39;,<br>    icon: Icons.camera_alt,<br>  ),<br>];<br><br>&quot;&quot;&quot;<br><br>old_cards = &quot;&quot;&quot;            Card(<br>              child: ListTile(<br>                leading: Icon(Icons.headphones),<br>                title: Text(&#39;Wireless Headphones&#39;),<br>                subtitle: Text(&#39;Compact audio for everyday use&#39;),<br>                trailing: Text(&#39;\\$49.00&#39;),<br>              ),<br>            ),<br>            SizedBox(height: 12),<br>            Card(<br>              child: ListTile(<br>                leading: Icon(Icons.watch),<br>                title: Text(&#39;Smart Watch&#39;),<br>                subtitle: Text(&#39;Track activity and stay connected&#39;),<br>                trailing: Text(&#39;\\$89.00&#39;),<br>              ),<br>            ),<br>            SizedBox(height: 12),<br>            Card(<br>              child: ListTile(<br>                leading: Icon(Icons.camera_alt),<br>                title: Text(&#39;Digital Camera&#39;),<br>                subtitle: Text(&#39;Capture memories in high quality&#39;),<br>                trailing: Text(&#39;\\$299.00&#39;),<br>              ),<br>            ),&quot;&quot;&quot;<br><br>new_cards = &quot;&quot;&quot;            ...products.map(<br>              (product) =&gt; Padding(<br>                padding: const EdgeInsets.only(bottom: 12),<br>                child: Card(<br>                  child: ListTile(<br>                    leading: Icon(product.icon),<br>                    title: Text(product.name),<br>                    subtitle: Text(product.description),<br>                    trailing: Text(product.price),<br>                  ),<br>                ),<br>              ),<br>            ),&quot;&quot;&quot;<br><br>if class_marker not in text:<br>    raise SystemExit(&quot;Could not find MyApp class.&quot;)<br><br>if old_cards not in text:<br>    raise SystemExit(&quot;Could not find the repeated product cards.&quot;)<br><br>text = text.replace(class_marker, product_model + class_marker, 1)<br>text = text.replace(old_cards, new_cards, 1)<br><br>file_path.write_text(text)<br>print(&quot;Product model and product list created successfully.&quot;)<br>PY</pre><p>Product model and product list created successfully.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/969/1*WULoiYohaKx-vp56HrRfcg.png" /><figcaption>The terminal confirms that the repeated product cards have been replaced with a reusable product model and an organized product list.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/969/1*KrIfttorlgKdvLYNe2bH-A.png" /><figcaption>Visual Studio Code shows the new `Product` model and the organized list containing all three products.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/969/1*Loqj_5bxJx0QEjdgaGNDiw.png" /><figcaption>The catalog layout now builds each card automatically from the product list instead of repeating the same widget three times.</figcaption></figure><p>The product cards are now generated from a list with `products.map()`.</p><p>Because that list is built dynamically, the page body can no longer remain inside a constant widget tree.</p><p>Before checking the refactor, I remove `const` from `SingleChildScrollView`.</p><p>It is a tiny change, but Flutter is very particular about these things. One misplaced `const`, and the compiler starts writing strongly worded letters.</p><pre>python3 - &lt;&lt;&#39;PY&#39;<br>from pathlib import Path<br><br>file_path = Path(&quot;lib/main.dart&quot;)<br>text = file_path.read_text()<br><br>old_code = &quot;body: const SingleChildScrollView(&quot;<br>new_code = &quot;body: SingleChildScrollView(&quot;<br><br>if old_code not in text:<br>    raise SystemExit(&quot;The const SingleChildScrollView line was not found.&quot;)<br><br>file_path.write_text(text.replace(old_code, new_code, 1))<br>print(&quot;Const removed from SingleChildScrollView successfully.&quot;)<br>PY</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/969/1*iTrTY0loQpxBaAhzLy8G_Q.png" /><figcaption>The terminal confirms that the old constant boundary has been removed, allowing Flutter to build product cards from the list dynamically.</figcaption></figure><p>I now open `lib/main.dart` in Visual Studio Code and inspect the new structure.</p><p>At the top of the file, the `Product` model defines the information every product needs: a name, description, price, and icon.</p><p>Below it, one organized list stores the three products.</p><p>The product information finally has its own home instead of camping inside the page layout.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/969/1*3W3v39Z10X9vRSY9oZiA7A.png" /><figcaption>The catalog layout now generates every product card automatically from the product list instead of repeating the same widget code.</figcaption></figure><p>The new structure is in place, so I format the file and ask Flutter to inspect the complete refactor.</p><p>Formatting keeps the code readable, while `flutter analyze` checks whether the model, product list, and generated cards work together correctly.</p><pre>dart format lib/main.dart<br>flutter analyze</pre><pre>No issues found!</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/969/1*vA0OoX5-gXzF9SNQST6qzw.png" /><figcaption>Dart formats the refactored file, and Flutter confirms that the cleaner product structure has no code issues.</figcaption></figure><p>The code is now cleaner, but a successful refactor should not change what the user sees.</p><p>The catalog should still display the same three products, with the same names, descriptions, icons, and prices.</p><p>I return to the terminal and run the app in Chrome:</p><pre>flutter run -d chrome</pre><p>Flutter builds the project and opens the catalog in the browser.</p><p>I check the screen carefully.</p><p>Wireless Headphones is still there.</p><p>Smart Watch is still there.</p><p>Digital Camera is still there.</p><p>The interface looks the same, but the code behind it is now much easier to expand.</p><p>That is the quiet beauty of refactoring: the room looks unchanged, but the wiring behind the walls is finally organized.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*ECWOgUGa3uT_Eisxa7NBsg.png" /><figcaption>The refactored catalog still displays all three products correctly, even though the data is now stored in a cleaner structure.</figcaption></figure><p>The unchanged interface confirms that the refactor worked.</p><p>Before this episode, every product card contained its own hard-coded name, description, price, and icon.</p><p>Now those details live inside one organized product list.</p><p>The layout simply reads the list and creates each card automatically.</p><p>The catalog looks familiar on the outside, but underneath, it has learned some manners.</p><p>Episode 16 did not add a new visual feature.</p><p>Instead, it improved the structure that future features will depend on.</p><p>I created a reusable `Product` model, moved the product information into one list, and replaced the repeated cards with `products.map()`.</p><p>The catalog still shows the same three items, but adding another product will now require only one new entry in the product list.</p><p>No extra card block. No copy-and-paste tower. No widget archaeology.</p><p>In Episode 17, I will use the new product structure to add another catalog item and introduce category information without rebuilding the layout.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5720261dd929" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Episode 15: Expanding One Product Card Into a Scrollable Catalog]]></title>
            <link>https://medium.com/@lenakendari/episode-15-expanding-one-product-card-into-a-scrollable-catalog-61d1333dd928?source=rss-932b58a7a66a------2</link>
            <guid isPermaLink="false">https://medium.com/p/61d1333dd928</guid>
            <category><![CDATA[ubuntu]]></category>
            <category><![CDATA[programmer]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[aplikasi-android]]></category>
            <dc:creator><![CDATA[Atelier Flutter]]></dc:creator>
            <pubDate>Thu, 16 Jul 2026 04:58:56 GMT</pubDate>
            <atom:updated>2026-07-16T04:58:56.997Z</atom:updated>
            <content:encoded><![CDATA[<p>I add more products, make the catalog scrollable, and give the app enough inventory to finally look like a real list.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hB1WJNPDREehAmFuLj8-6Q.png" /></figure><p>Episode 15 begins with one working product card.</p><p>That was enough for the previous episode, but a catalog with only one item still feels a little underfed.</p><p>So this time, I will add more products and make the page scrollable.</p><p>The goal is simple: turn a single card into a small catalog that can keep growing without the layout getting cramped.</p><p>No database yet. No search bar yet.</p><p>Just a cleaner structure, more products, and enough room for the app to breathe.</p><p>Before adding more products, I first locate the product card that already exists in `main.dart`.</p><p>This gives me the exact section to expand, without rebuilding the page or guessing where the new code should go.</p><p>The first card is already working. Now I only need to give it company.</p><pre>cd ~/offline_product_catalog<br>grep -nE &quot;Wireless Headphones|Card\\(|ListTile\\(&quot; lib/main.dart</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/815/1*882UhPgc3LzohEbGlhuAYA.png" /><figcaption>The terminal locates the existing product card inside `main.dart`, ready to be expanded into a larger catalog.</figcaption></figure><p>The current product card is working, so I will keep it and add two more products beneath it.</p><p>I will also make the page scrollable. That way, the catalog can grow without pushing content beyond the screen.</p><p>One product was a beginning. Three products start to look like inventory.</p><pre>cp lib/main.dart lib/main.dart.backup_episode15<br><br>python3 - &lt;&lt;&#39;PY&#39;<br>from pathlib import Path<br><br>file_path = Path(&quot;lib/main.dart&quot;)<br>text = file_path.read_text()<br><br>old_start = &quot;&quot;&quot;      body: const Padding(<br>        padding: EdgeInsets.all(24),<br>        child: Column(&quot;&quot;&quot;<br>new_start = &quot;&quot;&quot;      body: const SingleChildScrollView(<br>        padding: EdgeInsets.all(24),<br>        child: Column(&quot;&quot;&quot;<br><br>old_card = &quot;&quot;&quot;            Card(<br>              child: ListTile(<br>                leading: Icon(Icons.headphones),<br>                title: Text(&#39;Wireless Headphones&#39;),<br>                subtitle: Text(&#39;Compact audio for everyday use&#39;),<br>                trailing: Text(&#39;\\$49.00&#39;),<br>              ),<br>            ),&quot;&quot;&quot;<br><br>new_card = &quot;&quot;&quot;            Card(<br>              child: ListTile(<br>                leading: Icon(Icons.headphones),<br>                title: Text(&#39;Wireless Headphones&#39;),<br>                subtitle: Text(&#39;Compact audio for everyday use&#39;),<br>                trailing: Text(&#39;\\$49.00&#39;),<br>              ),<br>            ),<br>            SizedBox(height: 12),<br>            Card(<br>              child: ListTile(<br>                leading: Icon(Icons.watch),<br>                title: Text(&#39;Smart Watch&#39;),<br>                subtitle: Text(&#39;Track activity and stay connected&#39;),<br>                trailing: Text(&#39;\\$89.00&#39;),<br>              ),<br>            ),<br>            SizedBox(height: 12),<br>            Card(<br>              child: ListTile(<br>                leading: Icon(Icons.camera_alt),<br>                title: Text(&#39;Digital Camera&#39;),<br>                subtitle: Text(&#39;Capture memories in high quality&#39;),<br>                trailing: Text(&#39;\\$299.00&#39;),<br>              ),<br>            ),&quot;&quot;&quot;<br><br>if old_start not in text:<br>    raise SystemExit(&quot;The current page body was not found.&quot;)<br><br>if old_card not in text:<br>    raise SystemExit(&quot;The existing product card was not found.&quot;)<br><br>text = text.replace(old_start, new_start, 1)<br>text = text.replace(old_card, new_card, 1)<br><br>file_path.write_text(text)<br>print(&quot;Scrollable catalog with three products added successfully.&quot;)<br>PY</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/815/1*kpfY2K6HKUop8At-nhoNrA.png" /><figcaption>The terminal confirms that the catalog is now scrollable and contains three product cards.</figcaption></figure><p>After the terminal confirms the change, I open `lib/main.dart` in Visual Studio Code.</p><p>I check two things:</p><p>First, the page body now uses `SingleChildScrollView`.</p><p>Second, the original product card has two new neighbors: a smart watch and a digital camera.</p><p>The catalog is still simple, but it now has enough inventory to stop looking like a one-item menu.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/815/1*jQWThImmSDMtpaT7VAUQ-w.png" /><figcaption>Visual Studio Code shows the catalog wrapped in `SingleChildScrollView` with three product cards ready to display.</figcaption></figure><pre>flutter analyze</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/815/1*dM0CPrUeixMQYzXCdY4M7w.png" /><figcaption>Flutter confirms that the expanded scrollable catalog has no code issues.</figcaption></figure><p>The code is clean, so I run the app in Chrome and check the expanded catalog.</p><p>The screen should now display three products instead of one, and the page should remain usable even as the list grows.</p><p>This is the first moment when the app begins to feel like a real catalog rather than a single product wearing a large amount of confidence.</p><pre>flutter run -d chrome</pre><p>The code has passed `flutter analyze`, so the next step is to see whether the catalog actually works on the screen.</p><p>I return to the terminal and run the app in Chrome:</p><p>flutter run -d chrome</p><p>Flutter builds the project and opens the browser.</p><p>When the app appears, I check the catalog carefully.</p><p>The heading is still in place, and the original Wireless Headphones card is no longer alone. Two new products now appear beneath it:</p><p>Wireless Headphones <br>Smart Watch <br>Digital Camera</p><p>This confirms that the terminal patch successfully changed the interface.</p><p>The catalog has moved from one product to three, and the screen finally begins to feel like a real product list.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/815/1*xCYfKWWPDvOfMQ05QqbSiQ.png" /><figcaption>The updated catalog appears in Chrome with all three product cards displayed successfully.</figcaption></figure><p>Because the catalog is now wrapped in `SingleChildScrollView`, I also test the page by scrolling downward.</p><p>The movement is smooth, and the lower product cards remain accessible.</p><p>This small test matters. Adding more products is useful only if the page can still handle them without pushing content outside the visible screen.</p><p>The catalog is growing, and this time the layout is prepared for it.</p><p>The three products are now visible in Chrome, but I do not stop at the first successful screen.</p><p>I scroll down to check whether the page can still display the lower cards without cutting them off.</p><p>The catalog moves smoothly, and every product remains easy to reach.</p><p>This confirms that `SingleChildScrollView` is doing its job. The screen is no longer tied to one fixed height, so the catalog can keep growing without immediately causing a layout problem.</p><p>The app is still small, but its structure is beginning to think ahead.</p><p>Episode 15 began with one product card and ended with a small scrollable catalog.</p><p>I added two new products, kept the original card, and wrapped the page in `SingleChildScrollView`.</p><p>The catalog now contains:</p><p>Wireless Headphones <br>Smart Watch <br>Digital Camera</p><p>More importantly, the layout can handle a longer list without trapping products below the screen.</p><p>Three products are still a tiny inventory, but the app finally looks ready to grow instead of merely hoping for it.</p><p>In Episode 16, I will stop writing every product card directly inside the page.</p><p>Instead, I will begin moving product data into a cleaner structure so the catalog becomes easier to expand and maintain.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=61d1333dd928" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>