<?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 Bigpeak Chen on Medium]]></title>
        <description><![CDATA[Stories by Bigpeak Chen on Medium]]></description>
        <link>https://medium.com/@vkuie0823?source=rss-d55366f09031------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*XZUyQnOx-7_V4YR7.jpg</url>
            <title>Stories by Bigpeak Chen on Medium</title>
            <link>https://medium.com/@vkuie0823?source=rss-d55366f09031------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 00:59:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vkuie0823/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[Fluttering Through Colors: A Tale of Widgets and States]]></title>
            <link>https://medium.com/@vkuie0823/fluttering-through-colors-a-tale-of-widgets-and-states-a7252a526694?source=rss-d55366f09031------2</link>
            <guid isPermaLink="false">https://medium.com/p/a7252a526694</guid>
            <category><![CDATA[apple]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[state]]></category>
            <category><![CDATA[design]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Bigpeak Chen]]></dc:creator>
            <pubDate>Sun, 17 Dec 2023 15:56:43 GMT</pubDate>
            <atom:updated>2023-12-17T15:56:43.080Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*1pbWKHWXJyHzFMv-xDGB6A.png" /></figure><p>Flutter development is an art form, akin to painting with code. As a Dart connoisseur and Flutter enthusiast, I’ve had my share of colorful adventures — and misadventures. Today, I’ll take you on a journey through the creation of a seemingly simple widget, its subsequent debacle, and the insights gained from debugging the mess. Buckle up; it’s going to be a whimsical ride through the Flutter-verse!</p><h3>The Spark of Idea</h3><p>Imagine a canvas, a row of colors waiting to be picked. Our goal? Craft a row of CircleAvatar widgets, each representing a color. The twist? The last avatar isn&#39;t a color but a &#39;+&#39; sign, beckoning users to add more hues to their palette. Simple in theory, but as any seasoned developer knows, the devil&#39;s in the details.</p><h3>The Initial Brushstroke</h3><p>I started with the basic structure, drawing inspiration from the Flutter framework’s building blocks. Here’s the first dab of code:</p><pre>Widget buildBottomSection() {<br>  // A rainbow of preset colors<br>  List&lt;Color&gt; presetColors = [<br>    Colors.black, Colors.blue, Colors.green, Colors.yellow, Colors.red,<br>  ];<br>  return Row(<br>    // A row of evenly spaced CircleAvatars<br>    children: List.generate(<br>      6,<br>      (index) =&gt; CircleAvatar(<br>        backgroundColor: index &lt; presetColors.length<br>            ? presetColors[index]<br>            : Colors.grey,<br>        radius: 10,<br>        child: index == 5<br>            ? Text(&#39;+&#39;, style: TextStyle(fontSize: 24))<br>            : null,<br>      ),<br>    ),<br>  );<br>}</pre><h3>The Bug That Painted Over My Canvas</h3><p>Upon the first run, it seemed perfect. However, upon tapping the avatars, nothing happened. They were unresponsive, static — a still life with no life at all. The canvas needed interaction. Each tap should wrap the tapped color in a bold outline, distinguishing it as the selected one.</p><h3>The Debugging Dance</h3><p>Debugging is like detective work, where the clues are scattered across your code. The culprit? A missing state management that would remember the selected color. Flutter’s StatefulWidget came to the rescue, offering a way to rebuild our widget with new state information on each tap.</p><h3>Adding Interaction</h3><p>With the StatefulWidget in place, I introduced a variable selectedIndex to keep track of the chosen color. Here’s the snippet:</p><pre>class ColorSelector extends StatefulWidget {<br>  @override<br>  _ColorSelectorState createState() =&gt; _ColorSelectorState();<br>}<br><br>class _ColorSelectorState extends State&lt;ColorSelector&gt; {<br>  int selectedIndex = -1; // No color selected initially<br>  // ... rest of the code<br>}</pre><h3>The Aha-Moment</h3><p>Each CircleAvatar needed to be wrapped with a GestureDetector to sense taps, and a Container to draw the border. When tapped, the state needed to update, and voila, the border would appear.</p><pre>return GestureDetector(<br>  onTap: () {<br>    setState(() {<br>      selectedIndex = index;<br>    });<br>  },<br>  child: Container(<br>    margin: EdgeInsets.all(4),<br>    decoration: BoxDecoration(<br>      color: Colors.transparent,<br>      border: Border.all(<br>        color: selectedIndex == index ? Colors.black : Colors.transparent,<br>        width: 2,<br>      ),<br>      shape: BoxShape.circle,<br>    ),<br>    child: CircleAvatar(<br>      backgroundColor: presetColors[index],<br>      radius: 10,<br>    ),<br>  ),<br>);</pre><h3>The Palette of Knowledge</h3><p>As the widget took shape, several insights emerged:</p><ol><li><strong>State Management</strong>: It’s crucial for interactivity. Without it, your widgets are mere statues in a digital garden.</li><li><strong>User Feedback</strong>: Visual cues, such as borders, provide immediate feedback, enhancing user experience.</li><li><strong>The Power of </strong><strong>setState</strong>: It&#39;s the magic spell that redraws your widgets, reflecting the changes in state.</li></ol><h3>The Final Masterpiece</h3><p>After several iterations and bug fixes, the widget was complete. A row of colors, each tap bringing a border to life, with a ‘+’ sign beckoning at the end. Here’s the grand reveal:</p><pre>// ...imports and other code<br>class ColorSelector extends StatefulWidget {<br>  @override<br>  _ColorSelectorState createState() =&gt; _ColorSelectorState();<br>}<br>class _ColorSelectorState extends State&lt;ColorSelector&gt; {<br>  int selectedIndex = -1;<br>  @override<br>  Widget build(BuildContext context) {<br>    return Row(<br>      mainAxisAlignment: MainAxisAlignment.spaceEvenly,<br>      children: _buildColorAvatars(),<br>    );<br>  }<br>  List&lt;Widget&gt; _buildColorAvatars() {<br>    List&lt;Color&gt; presetColors = [<br>      Colors.black, Colors.blue, Colors.green, Colors.yellow, Colors.red,<br>    ];<br>    List&lt;Widget&gt; avatars = List.generate(<br>      presetColors.length,<br>      (index) =&gt; _buildColorAvatar(presetColors, index),<br>    );<br>    // Add the special &#39;+&#39; avatar at the end<br>    avatars.add(<br>      GestureDetector(<br>        onTap: () {<br>          // Logic to add a new color<br>        },<br>        child: CircleAvatar(<br>          backgroundColor: Colors.grey,<br>          radius: 10,<br>          child: Text(&#39;+&#39;, style: TextStyle(fontSize: 24)),<br>        ),<br>      ),<br>    );<br>    return avatars;<br>  }<br>  Widget _buildColorAvatar(List&lt;Color&gt; colors, int index) {<br>    return GestureDetector(<br>      onTap: () {<br>        setState(() {<br>          selectedIndex = index;<br>        });<br>      },<br>      child: Container(<br>        margin: EdgeInsets.all(4),<br>        decoration: BoxDecoration(<br>          color: Colors.transparent,<br>          border: Border.all(<br>            color: selectedIndex == index ? Colors.black : Colors.transparent,<br>            width: 2,<br>          ),<br>          shape: BoxShape.circle,<br>        ),<br>        child: CircleAvatar(<br>          backgroundColor: colors[index],<br>          radius: 10,<br>        ),<br>      ),<br>    );<br>  }<br>}<br>void main() {<br>  runApp(MaterialApp(<br>    home: Scaffold(<br>      body: Center(<br>        child: ColorSelector(),<br>      ),<br>    ),<br>  ));<br>}</pre><p>And with that, the application was a symphony of interactivity and color. Users could now tap and select their color with a delightful ring encircling their choice.</p><h3>Conclusion</h3><p>Flutter’s beauty lies in its flexibility and the richness of widgets at your disposal. Like an artist with a palette of paints, you mix and match until the picture is just right. This journey taught me that even the simplest of widgets can hold complexities, and the solution often lies in understanding the state and user interactions. May your Flutter endeavors be just as colorful and insightful!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a7252a526694" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fluttering Through Colors: A Tale of Widgets and Wonders]]></title>
            <link>https://medium.com/@vkuie0823/fluttering-through-colors-a-tale-of-widgets-and-wonders-1b43d8262e5a?source=rss-d55366f09031------2</link>
            <guid isPermaLink="false">https://medium.com/p/1b43d8262e5a</guid>
            <category><![CDATA[state]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[design]]></category>
            <category><![CDATA[apple]]></category>
            <dc:creator><![CDATA[Bigpeak Chen]]></dc:creator>
            <pubDate>Sun, 17 Dec 2023 14:22:32 GMT</pubDate>
            <atom:updated>2023-12-17T14:22:32.380Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eL7xzIOV9_1LLKdNyWxYWg.png" /></figure><p>In the universe of Flutter development, where widgets reign supreme, a daring coder embarked on a quest to craft an interface so vibrant, it would make rainbows pale in comparison. This is not just the story of how I built a widget, but the journey of discovery, pitfalls, and the triumph of code that followed.</p><h3>The Spark of Creation</h3><p>It all started with a simple idea: a user interface that allows you to mix and match colors with the flick of a slider — a symphony of reds, greens, and blues. But not just any symphony, one where the instruments are sliders and the conductor is you.</p><p>The heart of this fluttering venture was a Row widget, a linear runway where the colorful avatars—our little circular widgets—would take the stage. Each avatar held a promise: to turn into a vibrant hue at the slide of a finger.</p><h3>The First Draft</h3><p>With a flutter of my fingertips, the initial code flowed into my editor:</p><pre>Widget buildBottomSection() {<br>  String hexColor = &quot;#ffcc00&quot;; // A golden start<br>  double alphaValue = sliderValues[3] * 255;<br>  Color color = Color(int.parse(hexColor.substring(1, 7), radix: 16) + (alphaValue.toInt() &lt;&lt; 24));<br>  // ... rest of the code<br>}</pre><p>Ah, the beauty of a freshly created function! But as every seasoned developer knows, the first draft is but a whisper of the final chorus.</p><h3>The Bug Appears</h3><p>As I proudly ran the app, I noticed something was amiss. The colors weren’t quite right. “Why does this look like a palette from a dull, rainy day?” I mused. It was time to face the music: I had a bug.</p><h3>The Detective Work</h3><p>Debugging is an art, and like any good detective, I retraced my steps. I poured over the code, and there it was — a glaring mistake:</p><pre>Color color = Color(int.parse(hexColor.substring(1, 7), radix: 16) + (alphaValue.toInt() &lt;&lt; 24));</pre><p>The hexColor needed to be dynamic, reflecting the user’s choice. And the alphaValue? It was a ghost, a mere placeholder that needed life breathed into it.</p><h3>The Eureka Moment</h3><p>In a burst of inspiration, the solution revealed itself. I needed to bind the color to the sliders and give the user control over the alpha channel. And so, the code was reborn:</p><pre>Widget buildBottomSection() {<br>  double alphaValue = sliderValues[3] * 255;<br>  Color color = colorFromHex(hexColor, alphaValue);<br>  // ... rest of the code<br>}</pre><p>But wait! I needed a colorFromHex function that could dance with alphaValue. A quick tango of keys, and:</p><pre>Color colorFromHex(String hexColor, double alphaValue) {<br>  return Color(int.parse(hexColor.substring(1, 7), radix: 16) + (alphaValue.toInt() &lt;&lt; 24));<br>}</pre><h3>The Final Act</h3><p>With the bug squashed, the app sang! Sliders slid, colors changed, and the user was the maestro of a visual orchestra. Here’s the final symphony:</p><pre>Widget buildBottomSection() {<br>  // ... initialization code<br>  double alphaValue = sliderValues[3] * 255;<br>  Color color = colorFromHex(&quot;#ffcc00&quot;, alphaValue);<br>  <br>  List&lt;Color&gt; presetColors = [Colors.black, Colors.blue, Colors.green, Colors.yellow, Colors.red];  return Row(<br>    children: [<br>      Expanded(<br>        flex: 2,<br>        child: Container(<br>          height: double.infinity,<br>          color: color,<br>        ),<br>      ),<br>      Expanded(<br>        flex: 6,<br>        child: Column(<br>          children: [<br>            Row(<br>              mainAxisAlignment: MainAxisAlignment.spaceEvenly,<br>              children: List.generate(<br>                6,<br>                (index) =&gt; CircleAvatar(<br>                  backgroundColor: index &lt; presetColors.length ? presetColors[index] : Colors.grey,<br>                  radius: index == 5 ? 20 : 10,<br>                  child: index == 5 ? Icon(Icons.add) : null,<br>                ),<br>              ),<br>            ),<br>          ],<br>        ),<br>      ),<br>    ],<br>  );<br>}</pre><h3>The Takeaways</h3><p>The journey taught me more than just fixing a bug — it was a lesson in the dance of UI and logic, the play of colors, and the user’s role in the creative process. Flutter’s widget tree is not just a structure; it’s a canvas for the imagination.</p><p>As for you, dear reader, may your code be bug-free and your widgets vibrant. Remember, behind every great app, there’s a story of trial, error, and triumphant code.</p><p>Flutter forth and create!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b43d8262e5a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Alchemy of Colors: Crafting a MaterialColor in Flutter’s Enchanted Workshop]]></title>
            <link>https://medium.com/@vkuie0823/the-alchemy-of-colors-crafting-a-materialcolor-in-flutters-enchanted-workshop-ed87c1063418?source=rss-d55366f09031------2</link>
            <guid isPermaLink="false">https://medium.com/p/ed87c1063418</guid>
            <category><![CDATA[design]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[apple]]></category>
            <category><![CDATA[state]]></category>
            <dc:creator><![CDATA[Bigpeak Chen]]></dc:creator>
            <pubDate>Sun, 17 Dec 2023 14:18:19 GMT</pubDate>
            <atom:updated>2023-12-17T15:52:09.091Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LlDoa0KbrtsWzpxSrahQGQ.png" /></figure><h3>Prelude: The Idea Spark</h3><p>In the grand tapestry of application development, the invocation of color is akin to a wizard selecting potions for their spells. As a Flutter alchemist, the quest for crafting a dynamic MaterialColor from a basic Color is a tale as old as time, or at least as old as the framework itself.</p><p>Our saga begins with the vision of a mystical app where users can create their own theme by manipulating RGB sliders, a veritable cauldron bubbling with primary colors awaiting transmutation into a majestic MaterialColor.</p><h3>Act I: The Enchantment Begins</h3><p>As the enchantment of code breathed life into the app, we laid out the sacred scrolls of Flutter widgets and painted our canvas with the following incantation:</p><pre>Color newColor = Color.fromRGBO(<br>  sliderValues[0].toInt(),<br>  sliderValues[1].toInt(),<br>  sliderValues[2].toInt(),<br>  1,<br>);<br>colors[index] = newColor;</pre><p>With this spell, the wizard hoped to fill the colors array with vibrant hues, but alas, the array was destined for MaterialColor objects, not mere Color sprites.</p><h3>Act II: The Bug Appears</h3><p>As any seasoned sorcerer knows, the path of coding is fraught with bugs, like gremlins waiting to feast on your logic. The app, in its initial glory, failed to compile, with the console spewing cryptic verses:</p><pre>Error: A value of type &#39;Color&#39; can&#39;t be assigned to a variable of type &#39;MaterialColor&#39;.</pre><p>This perplexing message was the digital equivalent of a dragon guarding its treasure. The colors array was not a chest for simple Color objects; it demanded the richer, more complex MaterialColor.</p><h3>Act III: The Quest for the MaterialColor</h3><p>To appease the colors array and banish the error message back to the nether, a new spell was required. A MaterialColor is not merely a Color, but a map of shades, each a paler or darker whisper of the main hue. It demanded a concoction of shadows and light.</p><p>Thus, we invoked the ancient rite of createMaterialColor:</p><pre>MaterialColor createMaterialColor(Color color) {<br>  List&lt;double&gt; strengths = &lt;double&gt;[.05];<br>  Map&lt;int, Color&gt; swatch = {};<br>  final int r = color.red, g = color.green, b = color.blue;<br>  for (int i = 1; i &lt; 10; i++) {<br>    strengths.add(0.1 * i);<br>  }<br>  strengths.forEach((strength) {<br>    final double ds = 0.5 - strength;<br>    swatch[(strength * 1000).round()] = Color.fromRGBO(<br>      r + ((r - 255) * ds).round(),<br>      g + ((g - 255) * ds).round(),<br>      b + ((b - 255) * ds).round(),<br>      1,<br>    );<br>  });<br>  return MaterialColor(color.value, swatch);<br>}</pre><p>This arcane function was the heart of our solution, taking a Color and brewing a MaterialColor with ten shades of wizardry.</p><h3>Act IV: The Bug is Vanquished</h3><p>With the createMaterialColor spell in hand, we refactored our initial incantation:</p><pre>int r = sliderValues[0].toInt();<br>int g = sliderValues[1].toInt();<br>int b = sliderValues[2].toInt();<br>MaterialColor newMaterialColor = createMaterialColor(Color.fromRGBO(r, g, b, 1));<br>colors[index] = newMaterialColor;</pre><p>This spellbinding block of code was the key, turning RGB values into a full-fledged MaterialColor, thus filling the colors array with the treasures it desired.</p><h3>Epilogue: The Wisdom Gained</h3><p>Lo and behold, the app compiled with nary a complaint, and the error dragon was no more. The sorcerer had learned valuable lessons:</p><ol><li><strong>Know Thy Types</strong>: In the kingdom of Flutter, Color and MaterialColor are kin, but not twins.</li><li><strong>Craft Thy Functions</strong>: Sometimes, you must brew your own potions rather than rely on pre-made spells.</li><li><strong>Embrace Thy Errors</strong>: For within every error message lies the seed of knowledge, waiting to sprout.</li></ol><p>The wizard’s journey had ended, but the app’s journey had just begun. The users would now be able to create themes as varied as the stars in the sky, and the colors array would always welcome new MaterialColor with open arms.</p><h3>The Wisdom Gathered</h3><p>In our quest, we learned that every error is but a stepping stone to greater understanding. We discovered the power of custom functions and the importance of Flutter’s type system. But above all, we found joy in the journey, the beauty of building something that brings color to the world.</p><p>Now, dear reader, take these incantations and craft your own chromatic wonders. May the colors you weave be as vibrant as your imagination, and may your apps reflect the richness of the palette you’ve mastered.</p><h3>The Grand Finale: A Complete Spell</h3><p>For those brave souls eager to embark on their own color-crafting adventure, here is the full enchantment:</p><pre>import &#39;package:flutter/material.dart&#39;;<br><br>void main() {<br>  runApp(MyApp());<br>}<br><br>class MyApp extends StatelessWidget {<br>  @override<br>  Widget build(BuildContext context) {<br>    // Your app&#39;s root widget comes here<br>  }<br>}<br><br>class ColorfulSlider extends StatefulWidget {<br>  @override<br>  _ColorfulSliderState createState() =&gt; _ColorfulSliderState();<br>}<br><br>class _ColorfulSliderState extends State&lt;ColorfulSlider&gt; {<br>  List&lt;double&gt; sliderValues = [0, 0, 0]; // Initial RGB values<br>  Map&lt;int, MaterialColor&gt; colors = {};<br>@override<br>  Widget build(BuildContext context) {<br>    return SliderTheme(<br>      data: SliderTheme.of(context).copyWith(<br>        // Custom slider themes go here<br>      ),<br>      child: Column(<br>        children: [<br>          Slider(<br>            value: sliderValues[0],<br>            onChanged: (newValue) {<br>              setState(() {<br>                sliderValues[0] = newValue;<br>   // Red Slider<br>          Slider(<br>            value: sliderValues[0],<br>            min: 0,<br>            max: 255,<br>            divisions: 255,<br>            label: &#39;Red: ${sliderValues[0].round()}&#39;,<br>            activeColor: Colors.red,<br>            onChanged: (newValue) {<br>              setState(() {<br>                sliderValues[0] = newValue;<br>                updateMaterialColor();<br>              });<br>            },<br>          ),<br>          // Green Slider<br>          Slider(<br>            value: sliderValues[1],<br>            min: 0,<br>            max: 255,<br>            divisions: 255,<br>            label: &#39;Green: ${sliderValues[1].round()}&#39;,<br>            activeColor: Colors.green,<br>            onChanged: (newValue) {<br>              setState(() {<br>                sliderValues[1] = newValue;<br>                updateMaterialColor();<br>              });<br>            },<br>          ),<br>          // Blue Slider<br>          Slider(<br>            value: sliderValues[2],<br>            min: 0,<br>            max: 255,<br>            divisions: 255,<br>            label: &#39;Blue: ${sliderValues[2].round()}&#39;,<br>            activeColor: Colors.blue,<br>            onChanged: (newValue) {<br>              setState(() {<br>                sliderValues[2] = newValue;<br>                updateMaterialColor();<br>              });<br>            },<br>          ),<br>          // This Widget shows the selected color<br>          Container(<br>            height: 100,<br>            width: 100,<br>            color: colors[500], // The primary color of the MaterialColor<br>          ),<br>        ],<br>      ),<br>    );<br>  }<br><br>  // Helper function to update the MaterialColor<br>  void updateMaterialColor() {<br>    final color = Color.fromRGBO(<br>      sliderValues[0].round(),<br>      sliderValues[1].round(),<br>      sliderValues[2].round(),<br>      1,<br>    );<br>    colors = {500: createMaterialColor(color)};<br>  }<br><br>  // The createMaterialColor function from the previous segment<br>  MaterialColor createMaterialColor(Color color) {<br>    List&lt;double&gt; strengths = &lt;double&gt;[.05];<br>    Map&lt;int, Color&gt; swatch = {};<br>    final int r = color.red, g = color.green, b = color.blue;<br><br>    for (int i = 1; i &lt; 10; i++) {<br>      strengths.add(0.1 * i);<br>    }<br>    strengths.forEach((strength) {<br>      final double ds = 0.5 - strength;<br>      swatch[(strength * 1000).round()] = Color.fromRGBO(<br>        r + ((r - 255) * ds).round(),<br>        g + ((g - 255) * ds).round(),<br>        b + ((b - 255) * ds).round(),<br>        1,<br>      );<br>    });<br>    return MaterialColor(color.value, swatch);<br>  }<br>}<br><br>void main() =&gt; runApp(MaterialApp(home: ColorfulSlider()));</pre><p>This code snippet includes three sliders, one each for the red, green, and blue components of a color. As the user moves each slider, the onChanged callback updates the corresponding value in the sliderValues list and then calls updateMaterialColor to refresh the displayed MaterialColor. The createMaterialColor function remains the same as before, creating a MaterialColor with varying shades from the given Color.</p><p>Note also the addition of a Container widget that shows the currently selected color. It uses the primary color (the 500 shade) from the colors map, which is updated every time the sliders are adjusted.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed87c1063418" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter Fumbles: A Tale of Taming the Colorful Bug]]></title>
            <link>https://medium.com/@vkuie0823/flutter-fumbles-a-tale-of-taming-the-colorful-bug-506aa1e93241?source=rss-d55366f09031------2</link>
            <guid isPermaLink="false">https://medium.com/p/506aa1e93241</guid>
            <category><![CDATA[state]]></category>
            <category><![CDATA[design]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[dart]]></category>
            <dc:creator><![CDATA[Bigpeak Chen]]></dc:creator>
            <pubDate>Sun, 17 Dec 2023 07:17:48 GMT</pubDate>
            <atom:updated>2023-12-17T07:17:48.202Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/589/1*APx5eDX9YtgowEykoxNtSg.png" /></figure><p>In the realm of app development, the journey from concept to deployment is often littered with bugs and errors, much like a path in an enchanted forest is with mischievous sprites. Today, let’s embark on a whimsical tale, one where we transform a Flutter flub into a prismatic triumph.</p><h3>🎨 The Spark of Creation</h3><p>Imagine a world where selecting the perfect color is but a tap away. That was the vision for our latest app, a color picker that could make artists and designers swoon. Flutter, with its rich widgets and reactive framework, was the chosen vessel for this burst of creativity.</p><h3>🐛 The Unwelcome Guest</h3><p>As the app began to take shape, we encountered an unwelcome guest: a bug. The console, usually a river of mundane logs, now bore a glaring error.</p><pre>A value of type &#39;Color&#39; can&#39;t be assigned to a variable of type &#39;MaterialColor&#39;.<br>Try changing the type of the variable, or casting the right-hand type to &#39;MaterialColor&#39;.dartinvalid_assignment</pre><p>The creation of the color display widget, buildColorDisplay, and the bottom section, buildBottomSection, was hindered by this mismatch of types.</p><h3>🕵️‍♂️ The Investigation</h3><p>Why, you ask, did this happen? In Flutter’s colorful world, Color is the essence of simplicity, while MaterialColor is its more versatile cousin, boasting an array of shades. The bug had made its lair here, in the misunderstanding between these two.</p><h3>🔧 The Fix</h3><p>To evict our bug, we had to choose the right tool. If MaterialColor was a necessity, we&#39;d have to craft it with care, imbuing it with shades as a painter would their palette. Here&#39;s the incantation:</p><pre>int primaryValue = 0xFF9E9E9E; // The chosen primary color<br>Map&lt;int, Color&gt; colorSwatch = {<br>  50: Color(primaryValue).withOpacity(0.1),<br>  // ... More shades<br>  900: Color(primaryValue).withOpacity(1),<br>};<br>MaterialColor customMaterialColor = MaterialColor(primaryValue, colorSwatch);</pre><p>But if a simple Color would suffice, then the declaration must be changed, a trivial yet vital tweak:</p><pre>Color newColor = Color.fromRGBO(255, 0, 0, 1); // A pure, unadulterated color</pre><p>And ensure the declaration is not asking for a MaterialColor:</p><pre>Color newColor; // Not MaterialColor newColor;</pre><h3>🎓 Lessons Learned</h3><p>Through this ordeal, the wisdom gained was threefold:</p><ol><li><strong>Know Thy Widgets</strong>: Understanding the nature of Flutter’s widgets and types is paramount.</li><li><strong>Read Thy Error Messages</strong>: They are cryptic scrolls that hold the secrets to the bugs within.</li><li><strong>Embrace Thy Documentation</strong>: Flutter’s tomes are rich with knowledge, awaiting those who seek.</li></ol><h3>🏰 The Final Structure</h3><p>Here’s the blueprint of our fixed widget, a castle built with stronger types and a moat to keep bugs at bay:</p><pre>class ColorPickerWidget extends StatefulWidget {<br>  @override<br>  _ColorPickerWidgetState createState() =&gt; _ColorPickerWidgetState();<br>}<br><br>class _ColorPickerWidgetState extends State&lt;ColorPickerWidget&gt; {<br>  Color selectedColor = Colors.red; // A variable of type Color, not MaterialColor<br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(<br>        title: Text(&#39;Choose Thy Color&#39;),<br>      ),<br>      body: Column(<br>        children: &lt;Widget&gt;[<br>          buildColorDisplay(selectedColor), // Now returns a proper Color<br>          buildBottomSection(),<br>        ],<br>      ),<br>    );<br>  }<br>  // The method that builds the color display, corrected with the right types<br>  Widget buildColorDisplay(Color color) {<br>    // Imagine a beautiful widget that displays our chosen color<br>    return Container(color: color);<br>  }<br>  // The bottom section where users can adjust the color, free of type errors<br>  Widget buildBottomSection() {<br>    // Details omitted for brevity - imagine sliders and buttons galore<br>    return Container();<br>  }<br>}</pre><h3>🌈 The Palette of Wisdom</h3><p>As the app took its final form, so did the knowledge within us. Flutter’s vibrant ecosystem requires precision and understanding, much like the art of painting. Remember, the right color (or type) can bring a masterpiece to life, just as the wrong one can lead to a canvas of confusion.</p><p>Dear reader, may your code be bug-free and your apps colorful. Until the next code compile, flutter on!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=506aa1e93241" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Flutter: From Idea to Bug Fix with a Colorful Example]]></title>
            <link>https://medium.com/@vkuie0823/mastering-flutter-from-idea-to-bug-fix-with-a-colorful-example-f136d1d34a69?source=rss-d55366f09031------2</link>
            <guid isPermaLink="false">https://medium.com/p/f136d1d34a69</guid>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[state]]></category>
            <category><![CDATA[design]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Bigpeak Chen]]></dc:creator>
            <pubDate>Sun, 17 Dec 2023 07:15:11 GMT</pubDate>
            <atom:updated>2023-12-17T07:15:11.771Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*Hq_v-vFHy-CzN36zqlVzLQ.png" /></figure><p>Ah, the joy of coding! It’s a journey that takes you through the highs of creation and the lows of debugging. But fear not, for every bug squashed is a lesson learned, and every app shipped is a dream realized. Today, we’ll embark on such a journey with Flutter, Google’s UI toolkit for crafting beautiful, natively compiled applications. Are you ready to ride the rollercoaster of coding emotions? Let’s dive in!</p><h3>The Spark of Creation</h3><p>Imagine a world where you control the shades of the universe with just a slide. That’s the idea that sparked our latest Flutter project: a simple application with four sliders, each commanding the red, green, blue, and alpha values of a color. Imagine the power at your fingertips! Or, well, under your thumbs.</p><p>Here’s the plan: We’ll create a MyApp class, a heart of any Flutter application, that houses our main page with the sliders. The MyHomePage stateful widget will respond to slider movements, and with a dash of state management, the background color will dance to our tune. Sounds magical, doesn&#39;t it?</p><h3>The Unforeseen Twist</h3><p>In every coder’s tale, there’s a twist. For us, it came in the form of a bug, a type mismatch to be precise. Our hero, the Color type, was masquerading as a MaterialColor. Alas, the compiler did not appreciate this deception.</p><p>Here’s the culprit:</p><pre>A value of type &#39;Color&#39; can&#39;t be assigned to a variable of type &#39;MaterialColor&#39;.</pre><p>The error was a sign that our variable, which we intended to store plain Color values, was expecting a MaterialColor instead. MaterialColor is a special kind of Color that includes shades, typically used in material design for theme colors. But we don&#39;t need shades; we need a simple Color.</p><h3>The Enlightening Fix</h3><p>The fix was straightforward yet enlightening. We changed the expected type from MaterialColor to Color, aligning our variables with reality. It was a small change with a big impact, allowing us to proceed with our colorful plans.</p><p>Here’s the corrected code snippet:</p><pre>List&lt;Color&gt; colors = [<br>  Colors.red,<br>  Colors.green,<br>  Colors.blue,<br>  Colors.grey,<br>];</pre><p>And with that, our sliders were back in business, each one adjusting the intensity of its respective color channel.</p><h3>Building the Color Symphony</h3><p>We constructed our sliders with the finesse of a maestro, using SliderTheme to customize the look and feel. Each slider adjusted a value in our sliderValues list, which in turn updated our dynamic color.</p><p>Let’s take a closer look at the slider-building function:</p><pre>Widget buildSlider(Color startColor, Color endColor, double sliderValue, int index) {<br>  return Expanded(<br>    child: SliderTheme(<br>      data: SliderTheme.of(context).copyWith(<br>        activeTrackColor: endColor,<br>        // ... other properties<br>      ),<br>      child: Slider(<br>        value: sliderValue,<br>        // ... remaining properties and onChanged callback<br>      ),<br>    ),<br>  );<br>}</pre><p>Each slider is an artist, painting the canvas of our app’s background with its movements.</p><h3>The Grand Finale</h3><p>After a symphony of coding, debugging, and learning, we reached the grand finale: a fully functional Flutter application that’s as vibrant as a painter’s palette.</p><p>Here’s the complete, bug-free code for our color-adjusting masterpiece:</p><pre>import &#39;package:flutter/material.dart&#39;;<br><br>void main() {<br>  runApp(MyApp());<br>}<br><br>class MyApp extends StatelessWidget {<br>  @override<br>  Widget build(BuildContext context) {<br>    return MaterialApp(<br>      title: &#39;Slider Demo&#39;,<br>      theme: ThemeData(<br>        primarySwatch: Colors.blue,<br>      ),<br>      home: MyHomePage(),<br>    );<br>  }<br>}<br><br>class MyHomePage extends StatefulWidget {<br>  @override<br>  _MyHomePageState createState() =&gt; _MyHomePageState();<br>}<br><br>class _MyHomePageState extends State&lt;MyHomePage&gt; {<br>  List&lt;double&gt; sliderValues = [128, 128, 128, 1];<br><br>  @override<br>  Widget build(BuildContext context) {<br>    Color dynamicEndColor = Color.fromRGBO(<br>      sliderValues[0].toInt(),<br>      sliderValues[1].toInt(),<br>      sliderValues[2].toInt(),<br>      sliderValues[3],<br>    );<br><br>    return Scaffold(<br>      appBar: AppBar(<br>        title: Text(&#39;Color Sliders&#39;),<br>      ),<br>      body: Column(<br>        children: buildColorSliders(dynamicEndColor),<br>      ),<br>    );<br>  }<br><br>  List&lt;Widget&gt; buildColorSliders(Color dynamicEndColor) {<br>    return List.generate(4, (index) {<br>      Color startColor = (index &lt; 3) ? colors[index] : Colors.grey;<br>      Color endColor = (index &lt; 3)```dart<br>      ? dynamicEndColor.withAlpha(255) : dynamicEndColor;<br><br>      return buildSlider(startColor, endColor, sliderValues[index], index);<br>    });<br>  }<br><br>  Widget buildSlider(Color startColor, Color endColor, double sliderValue, int index) {<br>    return Expanded(<br>      child: SliderTheme(<br>        data: SliderTheme.of(context).copyWith(<br>          activeTrackColor: endColor,<br>          thumbColor: endColor,<br>          overlayColor: endColor.withAlpha(32),<br>          thumbShape: RoundSliderThumbShape(enabledThumbRadius: 15.0),<br>          overlayShape: RoundSliderOverlayShape(overlayRadius: 30.0),<br>        ),<br>        child: Slider(<br>          min: 0,<br>          max: (index &lt; 3) ? 255 : 1,<br>          divisions: (index &lt; 3) ? 255 : 1,<br>          value: sliderValue,<br>          onChanged: (newValue) {<br>            setState(() {<br>              sliderValues[index] = newValue;<br>            });<br>          },<br>        ),<br>      ),<br>    );<br>  }<br>}</pre><p>With this final snippet in place, our Flutter app is now complete. Users can interact with the sliders, dynamically changing the background color of the app in real-time. Each slider corresponds to one of the RGBA color values, allowing for a wide range of colors to be created.</p><p>And thus, we conclude our coding odyssey. We started with an idea, encountered an unexpected bug, and through a process of debugging and learning, we emerged triumphant with a delightful Flutter application. Remember, the path to coding mastery is paved with bugs, each one an opportunity to learn and grow as a developer.</p><p>Happy Fluttering! 🎨📱</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f136d1d34a69" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fluttering Through Colors: A Dart Journey]]></title>
            <link>https://medium.com/@vkuie0823/fluttering-through-colors-a-dart-journey-6cb99bcdbc39?source=rss-d55366f09031------2</link>
            <guid isPermaLink="false">https://medium.com/p/6cb99bcdbc39</guid>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[state]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[design]]></category>
            <dc:creator><![CDATA[Bigpeak Chen]]></dc:creator>
            <pubDate>Sun, 17 Dec 2023 07:11:23 GMT</pubDate>
            <atom:updated>2023-12-17T07:11:23.980Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/588/1*t5EzDSsIb8t-DUMAAfT0pw.png" /></figure><p>In the vibrant landscape of mobile app development, Flutter emerges as a palette of endless possibilities. Embarking on this colorful adventure, I’m thrilled to share my recent escapade with Flutter’s widgets, specifically the Slider. It’s a tale of unexpected twists, bug hunts, and ultimately, triumph — punctuated by the rich hues of Dart and Flutter knowledge.</p><h3>The Genesis of Colorful Ideas</h3><p>The initial concept was straightforward: create a series of Sliders that adjust their color gradient dynamically — a visual symphony orchestrated by user interaction. The app’s soul was to be vibrant and reactive, a harmonious blend of form and function. Flutter’s widget tree was the canvas, and Dart was my brush.</p><h3>The Unexpected Twist</h3><p>As every artist encounters, my masterpiece hit an unexpected snag. When one Slider was adjusted, not only did its colors transform, but so did the others. This conundrum was like a stray brushstroke across a near-perfect canvas.</p><pre>// Initial Slider Widget that caused the unexpected entanglement of colors<br>Slider(<br>  value: sliderValue,<br>  onChanged: (newValue) {<br>    setState(() {<br>      sliderValues[index] = newValue;<br>    });<br>  },<br>)</pre><h3>Debugging: The Bug Hunt</h3><p>The first suspect was setState(). It&#39;s the maestro of the state symphony, but it can be overzealous, redrawing more than necessary. Each Slider&#39;s movement called setState(), causing a full rebuild. The culprit was clear: a shared state.</p><pre>// Shared state array that was being updated by all Sliders<br>List&lt;double&gt; sliderValues = [0, 0, 0];</pre><h3>The Plot Twist: A Flutter of Enlightenment</h3><p>The solution was to isolate state changes. Each Slider needed autonomy, a private stage to perform its color-changing act. I refactored the code to give each Slider its own stateful presence, using a custom widget to encapsulate the behavior.</p><pre>// A custom widget that encapsulates the slider and its state<br>class ColorSlider extends StatefulWidget {<br>  final int index;<br>  final Color startColor;<br>  final Color endColor;<br>  // ... Other required parameters<br>  ColorSlider({<br>    Key? key,<br>    required this.index,<br>    required this.startColor,<br>    required this.endColor,<br>    // ... Initialization of other parameters<br>  }) : super(key: key);<br>  @override<br>  _ColorSliderState createState() =&gt; _ColorSliderState();<br>}</pre><h3>Eureka! The Correction</h3><p>The refactoring was a success. The Sliders sang in harmony, each responding only to its conductor’s baton. The solution lay in using local state updates and a calculated end color for each Slider individually.</p><pre>// Updated onChanged callback within our custom ColorSlider<br>onChanged: (double value) {<br>  setState(() {<br>    sliderValues[index] = value;<br>    if (index &lt; 3) { // Only the first three sliders affect the color<br>      Color newColor = Color.fromRGBO(<br>        sliderValues[0].toInt(),<br>        sliderValues[1].toInt(),<br>        sliderValues[2].toInt(),<br>        1,<br>      );<br>      endColor = newColor; // Update the end color based on the new values<br>    }<br>  });<br>},</pre><h3>The Grand Finale: Painting with Code</h3><p>Now, the Sliders moved with grace, each slide a brushstroke on the canvas, painting a world of color that responded to touch with precision and beauty.</p><p>Here’s the grand reveal, a Flutter page painted with the full spectrum of our journey:</p><pre>// The complete Flutter page with our custom ColorSlider widgets<br>class MyPage extends StatelessWidget {<br>  @override<br>  Widget build(BuildContext context) {<br>    // ... Scaffold, AppBar, and other necessary widgets<br>    // The dynamic end color derived from the first three sliders<br>    Color dynamicEndColor = Color.fromRGBO(<br>      sliderValues[0].toInt(),<br>      sliderValues[1].toInt(),<br>      sliderValues[2].toInt(),<br>      1,<br>    );<br>    return Column(<br>      children: &lt;Widget&gt;[<br>        // ... Possible additional widgets or content</pre><pre>        Expanded(<br>          child: ColorSlider(<br>            index: 0,<br>            startColor: Colors.red,<br>            endColor: dynamicEndColor,<br>            // ... Other necessary parameters<br>          ),<br>        ),<br>        // Repeat for other sliders<br>      ],<br>    );<br>  }<br>}</pre><h3>Knowledge and Gains: A Colorful Conclusion</h3><p>Through this journey, I’ve unraveled the threads of Flutter’s state management and the importance of isolating state changes. I’ve learned that setState() is a powerful yet indiscriminate tool—like wielding a hammer when sometimes you need a scalpel.</p><p>The key takeaway? Understand the scope of your state changes. Flutter’s performance and your app’s responsiveness rely on it.</p><pre>import &#39;package:flutter/material.dart&#39;;<br>void main() {<br>runApp(MyApp());<br>}<br>class MyApp extends StatelessWidget {<br>@override<br>Widget build(BuildContext context) {<br>return MaterialApp(<br>home: MyPage(),<br>);<br>}<br>}<br>class MyPage extends StatefulWidget {<br>@override<br>_MyPageState createState() =&gt; _MyPageState();<br>}<br>class _MyPageState extends State&lt;MyPage&gt; {<br>List&lt;double&gt; sliderValues = [128, 128, 128];<br>@override<br>Widget build(BuildContext context) {<br>Color dynamicEndColor = Color.fromRGBO(<br>sliderValues[0].toInt(),<br>sliderValues[1].toInt(),<br>sliderValues[2].toInt(),<br>1,<br>);<br>return Scaffold(<br>  appBar: AppBar(<br>    title: Text(&#39;Colorful Sliders&#39;),<br>    backgroundColor: dynamicEndColor,<br>  ),<br>  body: Column(<br>    children: [<br>      ColorSlider(<br>        index: 0,<br>        startColor: Colors.red,<br>        endColor: dynamicEndColor,<br>        sliderValue: sliderValues[0],<br>        onColorChanged: (value) =&gt; _updateColor(value, 0),<br>      ),<br>      ColorSlider(<br>        index: 1,<br>        startColor: Colors.green,<br>        endColor: dynamicEndColor,<br>        sliderValue: sliderValues[1],<br>        onColorChanged: (value) =&gt; _updateColor(value, 1),<br>      ),<br>      ColorSlider(<br>        index: 2,<br>        startColor: Colors.blue,<br>        endColor: dynamicEndColor,<br>        sliderValue: sliderValues[2],<br>        onColorChanged: (value) =&gt; _updateColor(value, 2),<br>      ),<br>    ],<br>  ),<br>);<br>}<br><br>void _updateColor(double value, int index) {<br>setState(() {<br>sliderValues[index] = value;<br>});<br>}<br>}<br><br>class ColorSlider extends StatelessWidget {<br>final int index;<br>final Color startColor;<br>final Color endColor;<br>final double sliderValue;<br>final ValueChanged&lt;double&gt; onColorChanged;<br><br>ColorSlider({<br>Key? key,<br>required this.index,<br>required this.startColor,<br>required this.endColor,<br>required this.sliderValue,<br>required this.onColorChanged,<br>}) : super(key: key);<br><br>@override<br>Widget build(BuildContext context) {<br>return SliderTheme(<br>data: SliderTheme.of(context).copyWith(<br>activeTrackColor: startColor,<br>inactiveTrackColor: endColor.withAlpha(100),<br>trackShape: RectangularSliderTrackShape(),<br>trackHeight: 4.0,<br>thumbColor: startColor,<br>thumbShape: RoundSliderThumbShape(enabledThumbRadius: 12.0),<br>overlayColor: startColor.withAlpha(32),<br>overlayShape: RoundSliderOverlayShape(overlayRadius: 28.0),<br>),<br>child: Slider(<br>min: 0,<br>max: 255,<br>divisions: 255,<br>value: sliderValue,<br>onChanged: onColorChanged,<br>),<br>);<br>}<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6cb99bcdbc39" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter Colors: A Journey from Hex Strings to Widgets]]></title>
            <link>https://medium.com/@vkuie0823/flutter-colors-a-journey-from-hex-strings-to-widgets-3481d1a0e4c4?source=rss-d55366f09031------2</link>
            <guid isPermaLink="false">https://medium.com/p/3481d1a0e4c4</guid>
            <category><![CDATA[design]]></category>
            <category><![CDATA[state]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Bigpeak Chen]]></dc:creator>
            <pubDate>Sun, 17 Dec 2023 07:06:06 GMT</pubDate>
            <atom:updated>2023-12-17T07:06:06.661Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/587/1*fYzqzkdAoCRNGY6nReKLqA.png" /></figure><p>Welcome to the canvas of Flutter, where the art of painting UIs comes alive with a rich palette of widgets and a sprinkle of Dart code. Today, we embark on a journey that begins with a simple idea — a user interface that uses computed hexadecimal color strings. But as with all great adventures, we encounter trials, bugs, and ultimately, triumphs.</p><h3>The Spark of Creation</h3><p>We start with a spark: a Row widget that cradles a colorful Container and a Column of grey circle avatars—simplistic yet promising. Here’s the original vision:</p><pre>Widget buildBottomSection() {<br>  return Row(<br>    children: [<br>      Expanded(<br>        flex: 2,<br>        child: Container(<br>          margin: EdgeInsets.symmetric(horizontal: 10, vertical: 20),<br>          color: Colors.yellow, // A placeholder color<br>        ),<br>      ),<br>      // ... rest of the original code<br>    ],<br>  );<br>}</pre><h3>The Unwelcome Plot Twist</h3><p>As we integrate a computed hex color into our Flutter app, we hit a snag. The Container color, instead of reflecting the dynamic hex value, remains stubbornly static. Something&#39;s amiss!</p><h3>The Debugging Odyssey</h3><p>Our hex color string is not behaving. So, we don our detective hats and dive into the code. The culprit? Our method of converting hex strings to Color objects is flawed. Flutter needs more than a string—it craves an int.</p><h3>The Heroic Fix</h3><p>We craft a function, colorFromHex, a magical incantation that transforms hex strings into Flutter-understandable Color objects. Witness the alchemy:</p><pre>Color colorFromHex(String hexColor) {<br>  final hexCode = hexColor.padLeft(6, &#39;0&#39;);<br>  return Color(int.parse(&#39;0xff$hexCode&#39;));<br>}</pre><p>With our new function in hand, we update the buildBottomSection to breathe life into our hex color string:</p><pre>Widget buildBottomSection(String hexColor) { // Now takes a hexColor string<br>  Color color = colorFromHex(hexColor); // The transformation<br>  return Row(<br>    children: [<br>      Expanded(<br>        flex: 2,<br>        child: Container(<br>          margin: EdgeInsets.symmetric(horizontal: 10, vertical: 20),<br>          color: color, // The dynamic hex color takes the stage<br>        ),<br>      ),<br>      // ... rest of the updated code<br>    ],<br>  );<br>}</pre><h3>The Enlightened Path</h3><p>Triumph! The Container now radiates the color of the hex string, a dynamic symphony of RGB. But the journey doesn&#39;t end here.</p><h3>The Treasures Gained</h3><p>From our odyssey, we harvest golden nuggets of knowledge:</p><ul><li>The significance of Flutter’s Color class and its romance with int values.</li><li>The power of string manipulation methods like padLeft, ensuring our hex values are always dressed to impress.</li><li>The importance of debugging with purpose, understanding the problem deeply before attempting to solve it.</li></ul><h3>The Final Masterpiece</h3><p>Bringing it all together, the final code stands tall, a testament to our journey:</p><pre>Widget buildBottomSection(String hexColor) {<br>  Color color = colorFromHex(hexColor);<br>  return Row(<br>    children: [<br>      Expanded(<br>        flex: 2,<br>        child: Container(<br>          margin: EdgeInsets.symmetric(horizontal: 10, vertical: 20),<br>          color: color,<br>        ),<br>      ),<br>      Expanded(<br>        flex: 6,<br>        child: Column(<br>          children: [<br>            Row(<br>              mainAxisAlignment: MainAxisAlignment.spaceEvenly,<br>              children: List.generate(<br>                5,<br>                (index) =&gt; CircleAvatar(<br>                  backgroundColor: Colors.grey,<br>                  foregroundColor: Colors.white,<br>                  child: Text(<br>                    &#39;+&#39;,<br>                    style: TextStyle(fontSize: 24),<br>                  ),<br>                ),<br>              ),<br>            ),<br>          ],<br>        ),<br>      ),<br>    ],<br>  );<br>}</pre><p>The app now a vibrant beacon, changing hues with the ebb and flow of user interactions. Each slider movement, a brushstroke on the canvas.</p><h3>The Art of Flutter and Beyond</h3><p>In the realm of Flutter, we are both the artist and the engineer. Through trial and error, persistence and insight, we harness the power of Dart to create something beautiful, something functional.</p><p>So, dear reader, take this tale as a beacon of hope in your coding quests. May your bugs be few, your UIs vibrant, and your journey through the colorful world of Flutter as enlightening as it is delightful. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3481d1a0e4c4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fluttering Through Colors: A Tale of Widgets and Hex Strings]]></title>
            <link>https://medium.com/@vkuie0823/fluttering-through-colors-a-tale-of-widgets-and-hex-strings-d7fc36bce340?source=rss-d55366f09031------2</link>
            <guid isPermaLink="false">https://medium.com/p/d7fc36bce340</guid>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[state]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[design]]></category>
            <category><![CDATA[apple]]></category>
            <dc:creator><![CDATA[Bigpeak Chen]]></dc:creator>
            <pubDate>Sun, 17 Dec 2023 07:03:43 GMT</pubDate>
            <atom:updated>2023-12-17T07:03:43.455Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/587/1*TDAqhzhmisRWxlXZUobuEw.png" /></figure><p>Oh, Flutter! You whimsical framework of widgets and wonders, you’ve caught us in your unyielding embrace once again. Today, let’s embark on a chromatic adventure where we paint our app with the colors of the wind — or at least the colors of the RGB sliders.</p><h3>The Eureka Moment</h3><p>Picture this: a simple Flutter app that displays a dynamic text field showing the hexadecimal value of a color. This color is determined by three sliders representing red, green, and blue (RGB) values. It’s an idea as clear as the Caribbean sky. Simple, right? Well, as with all great tales, our journey was rife with bugs and learnings.</p><h3>The Set-Up</h3><p>We start with a flutter of activity: setting up our project. Our main characters are the Slider widgets for the RGB values, and the Text widget that will proudly display our hexadecimal marvel. Let&#39;s set the stage with some code:</p><pre>Widget buildColorDisplay() {<br>  // Imagine sliderValues being a list of doubles: [red, green, blue]<br>  String redHex = sliderValues[0].toInt().toRadixString(16).padLeft(2, &#39;0&#39;);<br>  String greenHex = sliderValues[1].toInt().toRadixString(16).padLeft(2, &#39;0&#39;);<br>  String blueHex = sliderValues[2].toInt().toRadixString(16).padLeft(2, &#39;0&#39;);  // Concatenate the strings to get the full hex color<br>  String hexColor = redHex + greenHex + blueHex;<br>  return Column(<br>    children: [<br>      Center(<br>        child: Text(&#39;Display P3 Hex颜色#&#39;,<br>            style: TextStyle(color: Colors.blue)),<br>      ),<br>      Container(<br>        margin: EdgeInsets.symmetric(vertical: 10),<br>        padding: EdgeInsets.symmetric(horizontal: 10),<br>        decoration: BoxDecoration(<br>          color: Colors.white,<br>          borderRadius: BorderRadius.circular(25),<br>        ),<br>        child: Text(hexColor.toUpperCase(), style: TextStyle(fontSize: 24)), // Display the hex color<br>      ),<br>    ],<br>  );<br>}</pre><h3>The Plot Twist</h3><p>But what’s this? A bug in our app? Indeed, it’s a classic tale of “It looked simple at first.” When we ran our code, we found that direct string concatenation does indeed give us a hex string, but wait — when the RGB values are less than 16, our string doesn’t pad with zeros as it should. A hex color misrepresentation!</p><h3>The Heroic Debug</h3><p>Our hero, .padLeft(2, &#39;0&#39;), was supposed to ensure two digits for each color value, yet our screen showed &quot;82AB&quot; instead of &quot;0082AB&quot;. Time for a bug hunt! We reviewed our code and found that the .toInt() method was working just fine, but the .toRadixString(16) method wasn&#39;t padding single-digit hex values.</p><p>The fix was simple. Our .padLeft(2, &#39;0&#39;) was shining armor ready to be worn. We just needed to ensure it was applied after the conversion to a hex string.</p><h3>The Knowledge Gained</h3><p>In the world of coding, especially with Flutter, the devil is in the details. Each widget, each function, each method call can affect the outcome. It’s not just about making it work; it’s about understanding why it works (or doesn’t).</p><p>The .padLeft(2, &#39;0&#39;) method is a knight in shining armor for string formatting, ensuring that our strings always looked the part, even when our numbers were fashionably slim.</p><h3>The Grand Finale</h3><p>With our bug squashed, our app now proudly displays the correct hex color value, no matter what the RGB values are. And here it is, our final act:</p><pre>Widget buildColorDisplay() {<br>  // sliderValues is now a list of integers: [red, green, blue]<br>  String redHex = sliderValues[0].toRadixString(16).padLeft(2, &#39;0&#39;);<br>  String greenHex = sliderValues[1].toRadixString(16).padLeft(2, &#39;0&#39;);<br>  String blueHex = sliderValues[2].toRadixString(16).padLeft(2, &#39;0&#39;);<br>  // Concatenate the strings to get the full hex color<br>  String hexColor = &#39;#${redHex + greenHex + blueHex}&#39;.toUpperCase();<br>  return Column(<br>    children: [<br>      Center(<br>        child: Text(&#39;Display P3 Hex颜色#&#39;,<br>            style: TextStyle(color: Colors.blue, fontWeight: FontWeight.bold)),<br>      ),<br>      Container(<br>        margin: EdgeInsets.all(10),<br>        padding: EdgeInsets.all(15),<br>        decoration: BoxDecoration(<br>          color: Colors.white,<br>          borderRadius: BorderRadius.circular(25),<br>        ),<br>        child: Text(hexColor, style:TextStyle(fontSize: 24, fontWeight: FontWeight.bold, fontFamily: &#39;Monospace&#39;)),<br>      ),<br>    ],<br>  );<br>}</pre><p>And with that, our tale comes to a close. Our app, a cavalcade of colors, now dances with digits in perfect hexadecimal harmony. Flutter, once again, you’ve taught us that sometimes, the most vibrant lessons come in the quietest of types — like a gentle padLeft in a world of loud bugs.</p><p>Until our next coding chronicle, may your apps be bug-free, and your colors never clash.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d7fc36bce340" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fluttering Through Bugs: The Journey of a Widget’s Evolution]]></title>
            <link>https://medium.com/@vkuie0823/fluttering-through-bugs-the-journey-of-a-widgets-evolution-8f97a7d47366?source=rss-d55366f09031------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f97a7d47366</guid>
            <category><![CDATA[design]]></category>
            <category><![CDATA[apple]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[state]]></category>
            <dc:creator><![CDATA[Bigpeak Chen]]></dc:creator>
            <pubDate>Sun, 17 Dec 2023 07:01:08 GMT</pubDate>
            <atom:updated>2023-12-17T07:01:08.373Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/589/1*cru0_5kiRCDXjKIq4krvIw.png" /></figure><h3>The Spark of Creation</h3><p>Picture this: you’re cozied up with your favorite cup of tea, and an idea strikes. “Let’s build a Flutter widget,” you muse, “Something simple yet elegant that can resize and rotate, much like life’s ever-changing canvas.”</p><p>And so, the journey begins. You fire up your trusty IDE and begin sketching the skeleton of your Flutter app. The widget you’re crafting is a ResizableRotatableContainer, a container that can change its borders, size, and orientation. Sounds simple, right?</p><h3>The Stumble</h3><p>As in life, the path of coding is never free from obstacles. You deploy your initial code, full of hope. But alas, the widget does not behave as expected. Here’s a snippet of the code you’ve lovingly typed out:</p><pre>final isBorderVisible =<br>ref.watch(containerBorderProvider(widget.id).notifier).state;<br>// ... Other state watches</pre><p>Your widget’s supposed to be a visual chameleon, adapting to the user’s whims. But instead, it’s more like a stubborn mule, refusing to budge. You’ve used ref.watch to listen for state changes, and yet, the widget stays static. Puzzling, indeed!</p><h3>The “Aha!” Moment</h3><p>After some head-scratching, you realize that the devil’s in the details — or in this case, in the Future. You&#39;ve placed a state change inside a Future callback, a classic rookie mistake:</p><pre>if (isselectfont) {<br>  Future(() {<br>    ref<br>        .read(selectedFontProvider_ResizableRotatableContainer(widget.id)<br>            .notifier)<br>        .state = ref.watch(selectedFontProvider.notifier).state;<br>  });<br>}</pre><p>This code is like trying to catch a fish with your bare hands; it’s slippery and unpredictable. You chuckle at the oversight and proceed to refactor.</p><h3>Refactoring with Grace</h3><p>You rewrite the if block, removing the Future and directly updating the state. The change is immediate and synchronous, reflecting on the UI without delay:</p><pre>if (isselectfont) {<br>  ref<br>      .read(selectedFontProvider_ResizableRotatableContainer(widget.id)<br>          .notifier)<br>      .state = ref.read(selectedFontProvider.notifier).state;<br>}</pre><p>You now have a widget that’s responsive and dynamic, much like a dancer to music. You’ve also learned a valuable lesson about the event loop and state management in Flutter.</p><h3>The Finishing Touches</h3><p>To ensure your widget rebuilds with every state change, you sprinkle your build method with ref.watch:</p><pre>@override<br>Widget build(BuildContext context, WidgetRef ref) {<br>  final selectedFont = ref.watch(selectedFontProvider_ResizableRotatableContainer(widget.id)).state;<br>  // ... Other state watches<br>  // Use selectedFont to build your widget<br>}</pre><p>The widget is now a sight to behold, adapting to each state change with the grace of a gazelle. You’ve not only fixed the bug but also optimized the widget’s performance.</p><h3>The Grand Finale</h3><p>After several hours of coding and debugging, you lean back in your chair, a satisfied smile playing on your lips. You’ve transformed your simple idea into a fully functional, adaptable widget. Here’s a look at the final, bug-free code:</p><pre>@override<br>Widget build(BuildContext context, WidgetRef ref) {<br>  final isBorderVisible =<br>  ref.watch(containerBorderProvider(widget.id).notifier).state;<br>  final isCurrentContainer = ref.watch(currentContainerProvider) == widget.id;<br>  // ... Other state watches<br>  if (isselectfont) {<br>    ref<br>        .read(selectedFontProvider_ResizableRotatableContainer(widget.id)<br>            .notifier)<br>        .state = ref.read(selectedFontProvider.notifier).state;<br>  }<br>  return ResizableRotatableContainer(<br>    border: isBorderVisible ? Border.all() : null,<br>    child: Text(<br>      isCurrentContainer ? &#39;Current&#39; : &#39;Not Current&#39;,<br>      style: TextStyle(<br>        font: selectedFont,<br>        // ... Additional styling<br>      ),<br>    ),<br>  );<br>}</pre><h3>The Takeaways</h3><p>In this journey, you’ve encountered the quirks of asynchronous programming and the importance of state management in Flutter. You’ve learned that:</p><ul><li>ref.watch is your compass, guiding the widget through the stormy seas of state changes.</li><li>Future callbacks can be tricksters, leading you astray if not handled with care.</li><li>Synchronous state updates are the bread and butter of responsive UIs.</li></ul><p>And perhaps, most importantly, you’ve discovered that every bug is a hidden gem, waiting to be polished into a lesson.</p><p>So go forth and code, dear reader, with the confidence of one who has fluttered through the bugs and emerged victorious on the other side.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f97a7d47366" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fluttering Through Code: The Art of Bug Squashing and Elegant Widgets]]></title>
            <link>https://medium.com/@vkuie0823/fluttering-through-code-the-art-of-bug-squashing-and-elegant-widgets-489e3aff08b8?source=rss-d55366f09031------2</link>
            <guid isPermaLink="false">https://medium.com/p/489e3aff08b8</guid>
            <category><![CDATA[design]]></category>
            <category><![CDATA[state]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Bigpeak Chen]]></dc:creator>
            <pubDate>Sun, 17 Dec 2023 06:56:24 GMT</pubDate>
            <atom:updated>2023-12-17T06:56:24.769Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/588/1*ZbqKR6OddAaln6obW7ZClA.png" /></figure><p>Welcome, brave souls, to the whimsical world of Flutter development, where the widgets are plentiful, and the bugs are just opportunities in disguise. Our journey begins with an ambition, a dash of code, and a sprinkle of bugs, culminating in the sweet victory of knowledge.</p><h3>The Genesis of an Idea</h3><p>Once upon a time in the serene valleys of Flutter, an idea was born. A widget, not just any widget, but one that knew its size — a font size, to be precise. And so, with a heart full of hope, we embark on crafting a StateProvider that does just that.</p><pre>import &#39;package:flutter_riverpod/flutter_riverpod.dart&#39;;<br><br>final fontSizeProvider = StateProvider.family&lt;int, String&gt;(<br>  (ref, widgetId) =&gt; 14, // Let&#39;s start with a standard size, shall we?<br>);</pre><p>In the serene start of our tale, our fontSizeProvider is a beacon of simplicity. But as every seasoned developer knows, simplicity is a prelude to complexity.</p><h3>The Plot Twist</h3><p>In the midst of our coding saga, something unexpected occurred. Our widget was indeed changing sizes, but alas, not independently. When one widget grew bold, so did the others. A bug? No, a challenge!</p><p>After some pondering, it became clear — our StateProvider.family needed a unique identifier for each widget to dance to the beat of its own drum. And so, a refactor was in order.</p><h3>The Heroic Refactor</h3><p>With the wisdom of the ancients (and a little help from Stack Overflow), we refactored our provider to accept a unique widgetId. Each widget would now proudly bear its size, unaffected by its neighbors.</p><pre>final fontSizeProvider = StateProvider.family&lt;int, String&gt;(<br>  (ref, widgetId) {<br>    // A place for future logic that might adjust the initial size<br>    return 14; // The magic number for now<br>  },<br>);</pre><p>But as any good tale goes, the refactor was not the end. It was the beginning of a new chapter.</p><h3>The Bug Hunt</h3><p>Our widgets were now independent, but alas, the bug was tenacious. The sizes were stubbornly static. Wherefore art thou, dynamism?</p><p>In a moment of eureka, it dawned upon us. The widget’s builder function was the scene of the crime. It was not enough to simply watch the provider; one must also wield the power of ConsumerWidget.</p><h3>The Bug Squashing</h3><p>With a flick of the wrist and a stroke of the key, we transformed our widgets into ConsumerWidgets. And lo, the bug was vanquished.</p><pre>class MyWidget extends ConsumerWidget {<br>  final String id;<br>  MyWidget({Key? key, required this.id}) : super(key: key);<br>  @override<br>  Widget build(BuildContext context, WidgetRef ref) {<br>    final fontSize = ref.watch(fontSizeProvider(id));<br>    return Text(<br>      &#39;Hello, Flutter!&#39;,<br>      style: TextStyle(<br>        fontSize: fontSize.toDouble(),<br>      ),<br>    );<br>  }<br>}</pre><p>Triumphantly, we watched as each widget claimed its size with pride. The bug was no more, and our widgets were a symphony of sizes.</p><h3>The Moral of the Code</h3><p>In the aftermath of our adventure, we basked in the glow of our monitors, our hearts swelling with newfound wisdom. We learned the art of StateProvider.family, the significance of unique identifiers, and the power of ConsumerWidget.</p><p>And so, dear reader, remember this: In the realm of Flutter, every bug is but a stepping stone to mastery. Embrace the challenge, refactor with gusto, and squash those bugs with a smile.</p><h3>The Grand Finale: A Code Complete</h3><pre>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:flutter_riverpod/flutter_riverpod.dart&#39;;<br><br>void main() {<br>  runApp(<br>    ProviderScope(<br>      child: MaterialApp(<br>        home: Scaffold(<br>          body: Center(<br>            child: MyWidget(id: &#39;unique-font-size-1&#39;),<br>          ),<br>        ),<br>      ),<br>    ),<br>  );<br>}<br><br>final fontSizeProvider = StateProvider.family&lt;int, String&gt;(<br>  (ref, widgetId) =&gt; 14,<br>);<br><br>class MyWidget extends ConsumerWidget {<br>  final String id;<br><br>  MyWidget({Key? key, required this.id}) : super(key: key);<br><br>  @override<br>  Widget build(BuildContext context, WidgetRef ref) {<br>    final fontSize = ref.watch(fontSizeProvider(id));<br>    return Text(<br>      &#39;Hello, Flutter!&#39;,<br>      style: TextStyle(<br>        fontSize: fontSize.toDouble(),<br>      ),<br>    );<br>  }<br>}</pre><p>There you have it, folks. A tale of code, full of twists, turns, bugs, and knowledge. May your Flutter journey be as enlightening and bug-free as possible. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=489e3aff08b8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>