<?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 Gajendra Pandeya on Medium]]></title>
        <description><![CDATA[Stories by Gajendra Pandeya on Medium]]></description>
        <link>https://medium.com/@gajendrapandeya6?source=rss-73cfafe26097------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*53CvP_4X713LhFfr.jpg</url>
            <title>Stories by Gajendra Pandeya on Medium</title>
            <link>https://medium.com/@gajendrapandeya6?source=rss-73cfafe26097------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 05:43:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gajendrapandeya6/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Flutter SearchBar: An Ultimate Guide]]></title>
            <link>https://blog.stackademic.com/flutter-searchbar-an-ultimate-guide-011a8ae0aa9a?source=rss-73cfafe26097------2</link>
            <guid isPermaLink="false">https://medium.com/p/011a8ae0aa9a</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[search]]></category>
            <category><![CDATA[generics]]></category>
            <category><![CDATA[ui]]></category>
            <dc:creator><![CDATA[Gajendra Pandeya]]></dc:creator>
            <pubDate>Mon, 01 Jan 2024 17:09:19 GMT</pubDate>
            <atom:updated>2024-01-02T06:59:05.489Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>In the realm of mobile app development, a well-designed search feature is not just a convenience — it’s a vital component that significantly enhances user engagement and accessibility. This is particularly true for applications dealing with extensive data. Flutter, with its growing popularity among mobile developers, stands out as an excellent framework for building natively compiled applications. In this article, we embark on a journey to design a versatile search widget in Flutter, culminating in the creation of a generic widget akin to the CustomSearchDelegate. We will make use of theshowSearch method to implement searching. First, we will make a basic search bar and later we will customize it so that it can be used within any project.</p><p>The result will look like this.</p><p><a href="https://youtube.com/shorts/NIbL93h8qBg?feature=share">Flutter Search</a></p><h3>showSearch:</h3><p><a href="https://docs.flutter.io/flutter/material/showSearch.html">ShowSearch </a>is a method in the material library in Flutter. Because of this, it can be accessed from anywhere in your widget tree.</p><pre>Future&lt;T?&gt; showSearch&lt;T&gt;({<br>  required BuildContext context,<br>  required SearchDelegate&lt;T&gt; delegate,<br>  String? query = &#39;&#39;,<br>  bool useRootNavigator = false,<br>})</pre><p>This method requires a BuildContext and SearchDelegate which is an abstract class that takes in parameter of type T.</p><p>Example:</p><pre> showSearch(context: context, delegate: CustomSearchDelegate());</pre><p>So to implement a search functionality we just need to create a class that extends a SearchDelegate. Let’s see how that can be done.</p><pre>class CustomSearchDelegate extends SearchDelegate {<br>  @override<br>  List&lt;Widget&gt;? buildActions(BuildContext context) {<br>    // TODO: implement buildActions<br>    throw UnimplementedError();<br>  }<br><br>  @override<br>  Widget? buildLeading(BuildContext context) {<br>    // TODO: implement buildLeading<br>    throw UnimplementedError();<br>  }<br><br>  @override<br>  Widget buildResults(BuildContext context) {<br>    // TODO: implement buildResults<br>    throw UnimplementedError();<br>  }<br><br>  @override<br>  Widget buildSuggestions(BuildContext context) {<br>    // TODO: implement buildSuggestions<br>    throw UnimplementedError();<br>  }<br><br>}</pre><p>SearchDelegate require us to implement 4 methods.</p><ul><li>buildActions: Manages actions like clearing the search query. Resembles to action parameter of AppBar .</li><li>buildLeading: Typically includes a back button for navigation.</li><li>buildResults: Displays the search results.</li><li>buildSuggestions: Offers suggestions as users type their queries.</li></ul><p>Let’s implement a basic search using this delegate.</p><pre>class CustomSearchDelegate extends SearchDelegate {<br>  List&lt;String&gt; searchables = List.generate(100, (index) =&gt; &#39;Item ${index + 1}&#39;);<br><br>  @override<br>  List&lt;Widget&gt;? buildActions(BuildContext context) {<br>    return [<br>      IconButton(<br>        onPressed: () {<br>          query = &#39;&#39;;<br>        },<br>        icon: const Icon(Icons.clear),<br>      ),<br>    ];<br>  }<br><br>  @override<br>  Widget? buildLeading(BuildContext context) {<br>    return IconButton(<br>      onPressed: () {<br>        close(context, []);<br>      },<br>      icon: Icon(<br>        Platform.isAndroid ? Icons.arrow_back : Icons.arrow_back_ios,<br>        size: 22,<br>      ),<br>    );<br>  }<br><br>  @override<br>  Widget buildResults(BuildContext context) {<br>    return SuggestionOrResultWidget(searchables: searchables, query: query);<br>  }<br><br>  @override<br>  Widget buildSuggestions(BuildContext context) {<br>    return SuggestionOrResultWidget(searchables: searchables, query: query);<br>  }<br>}</pre><pre>class SuggestionOrResultWidget extends StatelessWidget {<br>  const SuggestionOrResultWidget({<br>    super.key,<br>    required this.searchables,<br>    required this.query,<br>  });<br><br>  final List&lt;String&gt; searchables;<br>  final String query;<br><br>  @override<br>  Widget build(BuildContext context) {<br>    final List&lt;String&gt; suggestions = query.isEmpty<br>        ? searchables<br>        : searchables.where((element) =&gt; element.toLowerCase().contains(query.toLowerCase())).toList();<br><br>    if (suggestions.isEmpty) return const NoResultWidget();<br><br>    return ListView.separated(<br>      itemBuilder: (context, index) =&gt; ListTile(<br>        title: Text(suggestions[index]),<br>      ),<br>      separatorBuilder: (context, index) =&gt; const Divider(),<br>      itemCount: suggestions.length,<br>    );<br>  }<br>}</pre><pre>class NoResultWidget extends StatelessWidget {<br>  const NoResultWidget({super.key});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return const Center(<br>      child: Text(&#39;No Result Found&#39;),<br>    );<br>  }<br>}</pre><p>The result will look like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/376/1*06CrNqmR7P5yqvzpGdtdXw.gif" /></figure><h3>Customizing the ThemeData of your search page AppBar</h3><p>One thing you may notice is that when the search page is shown, the theme is not the same as the app’s theme. You can see this specifically in the AppBar’s colors. The code below will just pass the ThemeData from your app directly to the AppBar on the search page.</p><pre><br>class CustomSearchDelegate extends SearchDelegate {<br>  List&lt;String&gt; searchables = List.generate(100, (index) =&gt; &#39;Item ${index + 1}&#39;);<br><br>  @override<br>  ThemeData appBarTheme(BuildContext context) {<br>    return ThemeData(<br>      // Customize appbar theme<br>      appBarTheme: const AppBarTheme(<br>        backgroundColor: Colors.blue,<br>        foregroundColor: Colors.white,<br>      ),<br>      // Customize input decoration theme<br>      inputDecorationTheme: const InputDecorationTheme(<br>        isDense: true,<br>        isCollapsed: true,<br>        contentPadding: EdgeInsets.only(left: 12, top: 6, bottom: 6),<br>        enabledBorder: OutlineInputBorder(<br>            borderSide: BorderSide(<br>          color: Colors.white,<br>        )),<br>        focusedBorder: OutlineInputBorder(<br>            borderSide: BorderSide(<br>          color: Colors.white,<br>        )),<br>        border: OutlineInputBorder(<br>          borderSide: BorderSide(<br>            color: Colors.white,<br>          ),<br>        ),<br>      ),<br>    );<br>  }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uwlQBItzHnD09R7Di7V9Hw.png" /><figcaption>Change appbar theme</figcaption></figure><h3>Creating a Generic Search Widget:</h3><p>Moving towards a more advanced implementation, let’s delve into the CustomSearchDelegate . This generic widget stands out for its reusability and adaptability across different data types.</p><pre>/// Generic Search Delegate which can be used anywhere<br>class CustomSearchDelegate&lt;T&gt; extends SearchDelegate&lt;List&lt;T&gt;&gt; {<br>  CustomSearchDelegate({<br>    required this.searchables,<br>    required this.suggestionOrResult,<br>    required this.itemMatcher,<br>    this.onTap,<br>  });<br>  <br>  // Items to be searched<br>  final List&lt;T&gt; searchables;<br>  <br>  // Widget that needs to be displayed when getting suggestion or result. <br>  // If you want sepearate widget for suggestion and result, you can add<br>  // 2 arguments, suggestionWidget and resultWidget to build differently.<br>  final Widget Function(List&lt;T&gt;, String) suggestionOrResult;<br><br>  // Query against which matching will run<br>  final bool Function(T item, String query) itemMatcher;<br><br>  // Callback when item is tapped<br>  final ValueChanged&lt;T&gt;? onTap;<br><br>  @override<br>  List&lt;Widget&gt;? buildActions(BuildContext context) {<br>    return [<br>      IconButton(<br>        onPressed: () {<br>          query = &#39;&#39;;<br>        },<br>        icon: const Icon(Icons.clear),<br>      ),<br>    ];<br>  }<br><br>  @override<br>  Widget buildLeading(BuildContext context) {<br>    return IconButton(<br>      onPressed: () {<br>        close(context, []);<br>      },<br>      icon: Icon(<br>        Platform.isAndroid ? Icons.arrow_back : Icons.arrow_back_ios,<br>        size: 22,<br>      ),<br>    );<br>  }<br><br>  @override<br>  Widget buildResults(BuildContext context) {<br>    return _buildSuggestionOrResult();<br>  }<br><br>  @override<br>  Widget buildSuggestions(BuildContext context) {<br>    if (searchables.isEmpty) return const SizedBox();<br>    return _buildSuggestionOrResult();<br>  }<br><br>  Widget _buildSuggestionOrResult() {<br>    final List&lt;T&gt; suggestionList =<br>        query.isEmpty ? searchables : searchables.where((item) =&gt; itemMatcher(item, query)).toList();<br><br>    if (suggestionList.isEmpty) {<br>      return NoResultFoundWidget();<br>    }<br><br>    return suggestionOrResult(suggestionList, query);<br>  }<br><br>}</pre><p>This generic delegate can be used as:</p><pre>showSearch(<br>              context: context,<br>              delegate: CustomSearchDelegate&lt;List&lt;String&gt;&gt;(<br>                searchables: searchables,<br>                suggestionOrResult: (List&lt;String&gt; suggestions,String query) =&gt; ListWidget(<br>                  suggestionsList: searchables,<br>                  query: query,<br>                ),<br>                itemMatcher: (String item,String query) =&gt; item.toLowerCase().contains(query.toLowerCase()),<br>              ),<br>            )</pre><h3>Bonus:</h3><p>If you want to highlight the typed-in letter from the suggestion list and scroll to the result you can use the following widget.</p><pre>class ListWidget extends StatefulWidget {<br>  const ListWidget({<br>    super.key,<br>    required this.suggestionsList,<br>    required this.query,<br>  });<br><br>  final List&lt;String&gt; suggestionsList;<br>  final String query;<br><br>  @override<br>  State&lt;ListWidget&gt; createState() =&gt; _ListWidgetState();<br>}<br><br>class _ListWidgetState extends State&lt;ListWidget&gt; {<br>  late List&lt;String&gt; filteredList;<br>  final ScrollController scrollController = ScrollController();<br><br>  @override<br>  void initState() {<br>    super.initState();<br>    filterList();<br>  }<br><br>  @override<br>  void didUpdateWidget(ListWidget oldWidget) {<br>    super.didUpdateWidget(oldWidget);<br>    if (widget.query != oldWidget.query) {<br>      filterList();<br>    }<br>  }<br><br>  void filterList() {<br>    filteredList =<br>        widget.suggestionsList.where((item) =&gt; item.toLowerCase().contains(widget.query.toLowerCase())).toList();<br><br>    if (filteredList.isNotEmpty) {<br>      if (filteredList.isNotEmpty) {<br>        WidgetsBinding.instance.addPostFrameCallback((_) =&gt; scrollToFirstMatch());<br>      }<br>    }<br>  }<br><br>  void scrollToFirstMatch() {<br>    int index = widget.suggestionsList.indexOf(filteredList.first);<br>    if (index != -1 &amp;&amp; scrollController.hasClients) {<br>      scrollController.animateTo(<br>        index * 32.0, // Assuming each item has a height of 32<br>        duration: const Duration(milliseconds: 100),<br>        curve: Curves.easeInOut,<br>      );<br>    }<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return ListView.separated(<br>      controller: scrollController,<br>      itemCount: filteredList.length,<br>      itemBuilder: (context, index) {<br>        final String suggestionText = filteredList[index];<br>        return ListTile(<br>          title: RichText(<br>            text: highlightMatch(suggestionText, widget.query),<br>          ),<br>          onTap: () {<br>            // Your onTap functionality here<br>          },<br>        );<br>      },<br>      separatorBuilder: (context, index) =&gt; const Divider(),<br>    );<br>  }<br><br>  TextSpan highlightMatch(String text, String query) {<br>    if (query.isEmpty || !text.toLowerCase().contains(query.toLowerCase())) {<br>      return TextSpan(<br>        text: text,<br>        style: const TextStyle(color: Colors.black),<br>      );<br>    }<br><br>    List&lt;TextSpan&gt; spans = [];<br>    int start = 0;<br>    int indexOfHighlight = text.toLowerCase().indexOf(query.toLowerCase());<br><br>    while (indexOfHighlight != -1) {<br>      spans.add(TextSpan(<br>        text: text.substring(start, indexOfHighlight),<br>        style: const TextStyle(color: Colors.black),<br>      ));<br>      spans.add(TextSpan(<br>        text: text.substring(indexOfHighlight, indexOfHighlight + query.length),<br>        style: const TextStyle(backgroundColor: Colors.yellow, color: Colors.black),<br>      ));<br><br>      start = indexOfHighlight + query.length;<br>      indexOfHighlight = text.toLowerCase().indexOf(query.toLowerCase(), start);<br>    }<br><br>    spans.add(TextSpan(<br>      text: text.substring(start),<br>      style: const TextStyle(color: Colors.black),<br>    ));<br>    return TextSpan(children: spans);<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/234/1*8xf8nCjiihJQ-XUSlLe5MA.gif" /></figure><h3>Conclusion:</h3><p>An effective search feature is a critical element in mobile app design, impacting user satisfaction and engagement. This CustomSearchDelegate is a testament to this, offering a template for creating customizable and versatile search functionalities in Flutter apps.</p><p>Thanks for reading. Happy Coding :)</p><h3>Stackademic</h3><p><em>Thank you for reading until the end. Before you go:</em></p><ul><li><em>Please consider </em><strong><em>clapping</em></strong><em> and </em><strong><em>following</em></strong><em> the writer! 👏</em></li><li><em>Follow us on </em><a href="https://twitter.com/stackademichq"><strong><em>Twitter(X)</em></strong></a><em>, </em><a href="https://www.linkedin.com/company/stackademic"><strong><em>LinkedIn</em></strong></a><em>, and </em><a href="https://www.youtube.com/c/stackademic"><strong><em>YouTube</em></strong></a><strong><em>.</em></strong></li><li><em>Visit </em><a href="http://stackademic.com/"><strong><em>Stackademic.com</em></strong></a><em> to find out more about how we are democratizing free programming education around the world.</em></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=011a8ae0aa9a" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/flutter-searchbar-an-ultimate-guide-011a8ae0aa9a">Flutter SearchBar: An Ultimate Guide</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Demystifying Streams in Flutter: A Beginner’s Guide]]></title>
            <link>https://blog.stackademic.com/demystifying-streams-in-flutter-a-beginners-guide-593cde00cd5e?source=rss-73cfafe26097------2</link>
            <guid isPermaLink="false">https://medium.com/p/593cde00cd5e</guid>
            <category><![CDATA[bloc]]></category>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[future]]></category>
            <category><![CDATA[stream]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Gajendra Pandeya]]></dc:creator>
            <pubDate>Mon, 25 Sep 2023 09:31:47 GMT</pubDate>
            <atom:updated>2023-09-26T10:50:20.093Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a9iIprORfq36oUX69cFYdg.png" /></figure><p>Asynchronous programming is a fundamental concept in Flutter, allowing developers to perform non-blocking operations efficiently. One of the essential tools for handling asynchronous data in Flutter is Streams. In this guide, we will explore what streams are, how to work with them, and their significance in Flutter app development.</p><h3>Understanding Asynchronous Programming in Dart</h3><p>Before diving into streams, it’s crucial to grasp the basics of asynchronous programming in Dart, the language behind Flutter. Dart is inherently synchronous, which means code executes sequentially by default. For eg:</p><pre>void main() {<br>  print(&#39;1&#39;);<br>  print(&#39;2&#39;);<br>  print(&#39;3&#39;);<br>}<br><br>// Output<br>// 1 2 3</pre><blockquote>Here, we can see that the statements are executed sequentially one after another. The problem arises if statement 2 is actually a long-running task, might be an API call or reading a file or reading data from database. The statement 3 will have to wait till the statement 2 is excuted.</blockquote><p>To handle this scenario where the code should be able to run asynchronously, Dart offers a powerful construct called <strong>Futures</strong> and <strong>Streams</strong>.</p><p><strong>Futures</strong> represent values or errors that will be available at some point in the future. They allow you to execute code asynchronously, preventing your application from freezing during time-consuming operations. Consider the example:</p><pre>void main() {<br>  print(&#39;1&#39;);<br>  // Creating a future<br>  Future.delayed(const Duration(seconds: 1), () {<br>  print(&#39;2&#39;);<br>  });<br>  print(&#39;3&#39;);<br> }<br><br>// Output<br>// 1 3 2</pre><blockquote>Here, we can see the execution order of statements. Statment 1 is excuted first, followed by statment 3 and after waiting for 1 seconds, statment 2 is excuted.</blockquote><h3>What is a Stream?</h3><p>“Let’s have an analogy that helps us to understand stream better”.</p><p>Suppose, we have a pipe through which water flows. It has two ends, a start and an end. The restriction is that water can pass through the pipe only from the start and we can collect water from the end only.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4FaRyBMykAdBZSjQjU53KA.png" /></figure><p>Let’s map the above analogy with the Stream itself:</p><ul><li>The pipe represents a StreamController. An object that manages the streams from its creation to destruction.</li><li>The start of the pipe is comparable to the sink. The sink is where we add the data or events.</li><li>The end of the pipe is the actual stream of events/data.</li><li>In order to actually collect water, that is to collect events/data, we have to subscribe/listen to the stream itself. Once the <strong>active</strong> listener is found, the stream starts its execution.</li></ul><p>In essence, a <strong>stream</strong> is a continuous flow of data that can be processed as it arrives. In Flutter, streams are extensively used for handling user interactions, network requests, and real-time updates.</p><blockquote>A <strong>Future</strong> completes with a single value or an error once, and then it cannot emit more values while A <strong>Stream</strong> can keep emitting events as long as the source is producing them.</blockquote><p>Streams can emit various types of data, such as integers, strings, or custom objects, and you can subscribe to them to receive and react to data as it becomes available.</p><p>As now we understand what a stream is, let’s start exploring the ways to create, read, and manage the stream.</p><h3>Creating and manipulating stream:</h3><p>A stream can be created in one of two ways:</p><ul><li>By using “StreamController”(suggested method):</li><li>By using the “Stream” class.</li></ul><p><strong>Method 1: </strong>The StreamController provides methods to add data to a stream and allows you to create subscriptions to listen for that data.</p><pre>import &#39;dart:async&#39;;<br><br>void main() {<br>  // STEP 1: Create a stream controller and specify it&#39;s type.<br>  // The type may be a premitive or any user defined class.<br>  final controller = StreamController&lt;int&gt;();<br><br>  // STEP 2: Start listening to the [stream] getter available on <br>  // StreamController. Here data argument is the data received from the <br>  // stream. It will be of the type we specified while creating the stream.<br>  controller.stream.listen((data) {<br>  print(&#39;Received data: $data&#39;);<br>  }<br><br>  // STEP 3: Start adding data to the [sink] gettter available on <br>  // StreamController. You can only add data of the type you specified<br>  // while creating a StreamController.<br>  controller.sink.add(1);<br>  controller.sink.add(2);<br>  controller.sink.add(3);<br>  <br>  // STEP 4: Close the stream<br>  controller.close();<br>}</pre><p><strong>Method 2: </strong>We can also create a stream using the Stream abstract class.</p><pre>import &#39;dart:async&#39;;<br><br>void main() {<br>  // STEP 1: Create Stream using the static method available on<br>  // Stream abstract class. It provides us static method like<br>  // fromFuture(), fromFutures(), fromIterable().<br>  // Here, we created and added data into stream.<br>  final intStream = Stream.fromIterable([1,2,3]);<br><br>  // Subscribe to the stream<br>  controller.stream.listen((data) {<br>  print(&#39;Received data: $data&#39;);<br>  }<br><br>  // STEP 4: Close the stream<br>  controller.close();<br>}</pre><blockquote>The difference between these two methods is that while using method2 we cannot add data into the stream once created. Also drain doesn’t actually close the stream rather it discards all data on this stream, but signals when it is done or an error occurred. So it is rather prefferred to create Streams using controller.</blockquote><h3>StreamSubscription:</h3><p>Once we listen to a stream, it returns us a StreamSubscription object which can be used to manage the lifecycle of the stream.</p><pre>import &#39;dart:async&#39;;<br><br>void main() {<br>  final controller = StreamController&lt;int&gt;();<br>  <br>  // Upon listening to a stream, we get StreamSubscription object<br>  final subscription = controller.stream.listen((_) {});<br>  <br>  // Will be called when data is received by the stream<br>  subscription.onData((data) {<br>  print(&#39;data received: $data&#39;);<br>  }<br><br>  // If any error occurs, this will be called<br>  subscription.onError((error) {<br>  print(&#39;error occurred: $error&#39;);<br>  }<br>  <br>  // Called when there are no more data or events to be processed<br>  subscription.onDone(() {<br>  print(&#39;Done receiving data&#39;);<br>  }<br>  <br>  controller..add(1)..add(2)..add(3);<br><br>  // Cancel the subscription<br>  subscription.cancel();<br>  <br>  controller.close();<br>}</pre><h3>Common stream error:</h3><p>When working with streams, it’s easy to encounter common pitfalls. One of the most frequent mistakes is subscribing to a stream multiple times, which results in a “<strong>Bad state: Stream has already been listened to</strong>” error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0bIYMUzX-qoPa6yBhVAq5Q.png" /></figure><p>One solution that we might think of is closing the existing controller and again listening to that stream.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MHPTeK8gfZL-ra98XT7Lmg.png" /></figure><p>We still will get the same error. In order to understand this, we need to understand the types of streams.</p><h3>Types of Stream:</h3><ul><li><strong>Single Subscription Stream</strong>: As the name suggests, this type of stream allows us to subscribe to the stream only once. By default when we create a Stream, we are creating a single subscription stream. The reason for the above error is due to this.</li><li><strong>Broadcast Stream</strong>: This type of stream allows us to subscribe to the same stream multiple times. So in order to remove the exisiting error, we can do this:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CIJ3Y8ESGEsNFzM1fliWiw.png" /></figure><h3>Common Stream Operation:</h3><p>We can perform various stream operations on the stream. Steam typically allows us various collection methods such as map, asyncMap, expand, asyncExpand, <strong>transform, </strong>and so on. Let’s see some of the commonly used stream operations:</p><ul><li><strong>map</strong>: The map operation is used to transform one type of stream into another type. Let’s say we have Stream&lt;String&gt; representing numbers and we want to convert it into Stream&lt;int&gt;, we can do that using the <strong>map </strong>operation: <br>Stream&lt;S&gt; map&lt;S&gt;(S Function(int) convert): The map function accepts a convert function that returns Stream of type S. <br>Eg:</li></ul><pre>import &quot;dart:async&quot;;<br><br>void main() {<br>final controller = StreamController&lt;String&gt;.broadcast();<br><br>// Apply map function to convert Stream&lt;String&gt; -&gt; Stream&lt;int&gt; <br>controller.stream.map((data) =&gt; int.tryParse(data));<br><br>controller.stream.listen((data) {<br>print(&#39;data received from  $data&#39;);<br>}); <br><br>controller.add(&quot;1&quot;);<br>controller.add(&quot;2&quot;);<br>controller.add(&quot;3&quot;);<br>}</pre><p>. <strong>asyncMap</strong>: An Async map is similar to a map except that it maps every data item asynchronously. So let’s say if any data/event is a future, then it will wait for that future to complete before processing other events/data in the stream.</p><pre>import &#39;dart:async&#39;;<br><br>Future&lt;void&gt; main() async{<br>  Stream&lt;int&gt; myStream = Stream.fromIterable([1, 2, 3, 4, 5]);<br><br>  // Use asyncMap to double each number asynchronously<br>  Stream&lt;int&gt; doubledStream = myStream.asyncMap((number) =&gt; doubleAsync(number));<br><br>  await for (int result in doubledStream) {<br>    print(result); // This will print each doubled number after waiting for 1 second.<br>  }<br><br>}<br><br>Future&lt;int&gt; doubleAsync(int number) async {<br>  // Simulate an asynchronous operation (e.g., fetching data from the internet)<br>  await Future.delayed( const Duration(seconds: 1));<br>  <br>  // Double the number<br>  return number * 2;<br>}</pre><p>. <strong>transform</strong>: The transform method is one of the most used methods on stream. It allows us to transform Stream into a custom type as we require.<br>Let’s say we are getting Stream&lt;List&lt;Map&lt;String, dynamic&gt;&gt;&gt; (assuming that it’s the response from API) and want to convert it into our own List&lt;User&gt; type. Then we can apply the transform method to do so. Let’s see the step-by-step method to do this.</p><blockquote>1. Create a StreamTransformer. The transformer will requires us to provide the input and output of the stream. Since in our case, we want to convert List&lt;Map&lt;String, dynamic&gt;&gt; to List&lt;User&gt; model, we can do following.</blockquote><pre>final transformer = StreamTransformer&lt;List&lt;Map&lt;String, dynamic&gt;&gt;, List&lt;User&gt;&gt;<br>                      .fromHandlers(handleData: (data, sink) {<br>                        final userData = data.map((e) =&gt; User.fromJson(e)).toList();<br>                        sink.add(userData);<br>                        });</pre><p>Let’s see a complete example:</p><pre>import &#39;dart:async&#39;;<br><br>void main() {<br>  <br>  // Data we are getting from api<br>  final List&lt;Map&lt;String, dynamic&gt;&gt; userJsonString = [<br>    {<br>      &#39;id&#39;: 0,<br>      &#39;name&#39;: &#39;Ram&#39;,<br>      &#39;age&#39;: 20<br>    },<br>    {<br>      &#39;id&#39;: 1,<br>      &#39;name&#39;: &#39;Shyam&#39;,<br>      &#39;age&#39;: 32<br>    }<br>  ];<br>  <br>  // Create a controller<br>  final streamController = StreamController&lt;List&lt;Map&lt;String, dynamic&gt;&gt;&gt;();<br>   <br>  // Create a transformer to convert Stream -&gt; custom type<br>  final transformer = StreamTransformer&lt;List&lt;Map&lt;String, dynamic&gt;&gt;, List&lt;User&gt;&gt;.fromHandlers(handleData: (data, sink) {<br>    // Convert data into custom model<br>    final usersList = data.map((json) =&gt; User.fromJson(json)).toList();<br>    // Add it to the sink<br>    sink.add(usersList);<br>  });<br>  <br>  // Add the created transformer to the stream<br>  streamController.stream.transform(transformer).listen((userList) {<br>    print(&#39;user: $userList&#39;);<br>  });<br>  <br>  <br>  streamController.add(userJsonString);<br><br>}<br><br>class User {<br>  final int id;<br>  final String name;<br>  final int age;<br>  <br>  User({required this.id, required this.name, required this.age});<br>  <br>  factory User.fromJson(json) =&gt; User(id: json[&#39;id&#39;], name: json[&#39;name&#39;], age: json[&#39;age&#39;]);<br>  <br>  @override<br>  String toString() =&gt; &#39;id: $id, name: $name, age: $age&#39;;<br>}</pre><p>In a similar way, we have various other methods available on streams.</p><h3>A complete state management solution using streams only:</h3><p>We can even manage the state of our application using Streams only. <br>Let’s see a demo where we will build a real app and manage the state using Streams only. We will be using <a href="https://jsonplaceholder.typicode.com/">jsonplaceholderapi</a> to fetch a list of articles from api and we will show it on the screen. Our app will look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dd_jHcC-JidjwQeguBjc6w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6zAQmET-TPP9Y5l4boWR8w.png" /></figure><blockquote><strong>Service Layer</strong>: We have fetchArticles() method in service that returns Future&lt;List&lt;Article&gt;&gt;.<br><strong>Repository layer</strong>: Here we are calling the service method.</blockquote><p>Let’s see how we can implement a controller to fetch data from the repository and manage it’s state.</p><pre>// We are creating NetworkState sealed class that represents the possible<br>// states.<br>sealed class NetworkState {}<br><br>class NetworkStateLoading extends NetworkState {}<br><br>class NetworkStateSuccess&lt;T&gt; extends NetworkState {<br>  final T data;<br>  NetworkStateSuccess({required this.data});<br>}<br><br>class NetworkStateError extends NetworkState {<br>  final String errorMessage;<br><br>  NetworkStateError({required this.errorMessage});<br>}</pre><pre>class HomeController {<br><br>  final HomeRepository homeRepository;<br>  <br>  // STEP 1: Create a streamController of type NetworkState so that we can <br>  // display UI according to the state.<br>  final StreamController&lt;NetworkState&gt; articleState = StreamController&lt;NetworkState&gt;();<br><br>  HomeController({required this.homeRepository});<br>  <br>  // Method to fetch article from repository<br>  Future&lt;void&gt; fetchArticles() async {<br>    articleState.add(NetworkStateLoading());<br>    try {<br>      final articlesList = await homeRepository.getArticles();<br>      articleState.add(NetworkStateSuccess(data: articlesList));<br>    } catch (ex) {<br>      articleState.add(NetworkStateError(errorMessage: ex.toString()));<br>    }<br>  }<br><br>  void dispose() {<br>    articleState.close();<br>  }<br>}</pre><p>Inside our screen, we can use the <strong>StreamBuilder </strong>widget to build the UI provided by Flutter.</p><pre> @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(<br>        title: const Text(&#39;Article List&#39;),<br>        centerTitle: false,<br>        actions: [<br>          Padding(<br>            padding: const EdgeInsets.all(8),<br>            child: CartBadge(<br>              cartController: _cartController,<br>            ),<br>          ),<br>        ],<br>      ),<br>      // use the stream provided by articleState<br>      body: StreamBuilder(<br>        stream: homeController.articleState.stream,<br>        builder: (context, snapShot) {<br>          if (snapShot.hasData) {<br>            final homeState = snapShot.data as NetworkState;<br>            // build UI according to the state.<br>            return switch (homeState) {<br>              NetworkStateLoading() =&gt;<br>                const Center(child: CircularProgressIndicator.adaptive()),<br>              NetworkStateSuccess() =&gt; _buildArticleList(homeState.data),<br>              NetworkStateError() =&gt;<br>                Center(child: Text(&#39;Error: ${homeState.errorMessage}&#39;)),<br>            };<br>          } else {<br>            return const Center(<br>              child: CircularProgressIndicator.adaptive(),<br>            );<br>          }<br>        },<br>      ),<br>    );<br>  }</pre><p>Refer to this repo for the complete code:</p><p><a href="https://github.com/gazzu18/kss-streams">GitHub - gazzu18/kss-streams: Application of Streams</a></p><h3>How bloc is implemented?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pmsRxHBsDzjcRnQ_axFgfw.png" /></figure><p>Bloc under the hood uses Streams for creating events and providing states.<br>We can see that when we perform any interaction from UI, we simply add that event to StreamController, and We listen from UI to build the widget, based on the state.</p><h3>Conclusion</h3><p>Streams are a powerful tool in Flutter for handling asynchronous data and events. They enable you to build responsive and real-time applications. In this guide, we’ve covered the basics of streams, how to create and manage them, common pitfalls to avoid, and the different types of streams. Armed with this knowledge, you can harness the full potential of streams in your Flutter applications.</p><p>Thanks for reading the article. Happy coding!</p><h3>Stackademic</h3><p><em>Thank you for reading until the end. Before you go:</em></p><ul><li><em>Please consider </em><strong><em>clapping</em></strong><em> and </em><strong><em>following</em></strong><em> the writer! 👏</em></li><li><em>Follow us on </em><a href="https://twitter.com/stackademichq"><strong><em>Twitter(X)</em></strong></a><em>, </em><a href="https://www.linkedin.com/company/stackademic"><strong><em>LinkedIn</em></strong></a><em>, and </em><a href="https://www.youtube.com/c/stackademic"><strong><em>YouTube</em></strong></a><strong><em>.</em></strong></li><li><em>Visit </em><a href="http://stackademic.com/"><strong><em>Stackademic.com</em></strong></a><em> to find out more about how we are democratizing free programming education around the world.</em></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=593cde00cd5e" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/demystifying-streams-in-flutter-a-beginners-guide-593cde00cd5e">Demystifying Streams in Flutter: A Beginner’s Guide</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build a Custom Paint Flutter App Widget]]></title>
            <link>https://medium.com/better-programming/custompaint-in-flutter-ff2e1d6f8309?source=rss-73cfafe26097------2</link>
            <guid isPermaLink="false">https://medium.com/p/ff2e1d6f8309</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Gajendra Pandeya]]></dc:creator>
            <pubDate>Sat, 30 Apr 2022 12:50:12 GMT</pubDate>
            <atom:updated>2022-05-01T15:15:40.441Z</atom:updated>
            <content:encoded><![CDATA[<h4>Wanna create a highly customized user interface with awesome animation? Fear not, Flutter CustomPaint Widget has got you covered</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B4DWmLCv4c4bwcyUOWEIjw.gif" /></figure><p>In this article, we will be covering both explicit animation as well as how to work with CustomPaint widget in a flutter.</p><p>You can check out the code sample at from my <a href="https://github.com/gajendrapandeya/CustomPaint.git">GitHub Repository</a>.</p><blockquote><strong>Custom Paint : </strong>A widget that provides a canvas on which to draw during the paint phase.</blockquote><p>Simply add CustomPaint widget to your widget tree and provide <strong>painter<em> </em></strong>to it which is a subclass of CustomPainter abstract class.</p><p>Since CustomPainter is an abstract class, it forces us to implement two important methods i.e. paint() and shouldRepaint(). The size<strong><em> </em></strong>spcifies the size of the drawn widget. Let’s get our hands dirty:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dbdf73698fab365666eb22e8f4e8d9ce/href">https://medium.com/media/dbdf73698fab365666eb22e8f4e8d9ce/href</a></iframe><p>The paint() method provides us with two important parameters:</p><ol><li>Canvas: Canvas is the area on the screen where we draw our widget. It has various method to draw custom widget. Some of them are: canvas.drawLine(), canvas.drawCircle(), canvas.drawArc(), canvas.drawOval() etc.</li><li>Size: How big should be the drawing. By default, it takes the size of the wrapper widget i.e the widget wrapping our CustomPaint widget. Also, we can provide size parameters inside our CustomPaint widget. Since we want to draw a circle so we passed the same value for both the width and height.</li></ol><p>The shouldRepaint() method is called whenever CustomPainter needs to be rebuilt. This would get clear when we implement our project.</p><p>Now that we understand CustomPainter class, let’s draw something on the canvas. Our goal is to draw a circle with some stroke width.</p><p>Let’s see how we do this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b5f3d17cda90fb0f7146e2b3730a679b/href">https://medium.com/media/b5f3d17cda90fb0f7146e2b3730a679b/href</a></iframe><p>Since we wanna draw a circle, so we used the prebuilt canvas.drawCircle() the method that expects three parameters i.e. center of the circle, radius of the circle and a paint object. We calculated the circle center and radius from size<strong><em> the </em></strong>parameter. The Paint() class provides us various properties like the color of the paint, storkeWidth, style of the paint i.e whether it should be stroked or filled. The current implementation will result in this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*kIqpPe1jIp7PUKa2AZFAgg.png" /></figure><p>Our next goal is to draw an arc over the same circle that would animate around the stroke. In order to achieve this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d1f978054b6a7e8fbd6178afcb2db701/href">https://medium.com/media/d1f978054b6a7e8fbd6178afcb2db701/href</a></iframe><p>Since we wanna draw an arc, so we used canvas.drawArc() method that expects five parameters i.e. Rect object , startAngle in radian, sweepAngle in radian, useCenter boolean and paint object.</p><p>Also, we want to draw arc around the circle, so we used Rect.fromCircle() the method as the first parameter. The second parameter is the start angle which we have applied to -pi/2 as we want to start the angle from top of the circle.</p><p>The sweep angle specifies where should the arc end and we have applied 40% of the total angle i.e our arc will draw from -pi/2 to 40% of the total 360 radian.</p><p>If useCenter<strong> </strong>boolean is true, the arc is closed back to the center, forming a circle sector. Otherwise, the arc is not closed, forming a circle segment. And the final argument is our paint object which we are already familiar with.</p><p>The current implementation with useCenter set to true will result in this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*C4427kqezZ2E0_up5ymFWg.png" /></figure><p>But we don’t want that circle sector, so setting it false would result in this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/323/1*KV_jhGVoa7GUcZ01JbAYxw.png" /></figure><p>You can tweak the startAngle, endAngle to see the various effects.</p><p>Now we are almost close to what we want to achieve. The only part remaining is to animate the progress. In order to do this, we have to use explicit animation i.e. we have to create AnimationController and pass its value down the RingPainter class:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a73bc1a546372c7f127cdac6950fad86/href">https://medium.com/media/a73bc1a546372c7f127cdac6950fad86/href</a></iframe><p>The various things we have done now are:</p><ol><li>Converted our RingPainter StatelessWidget to Stateful widget in order to rebuild the UI whenever the value of animation changes.</li><li>Created AnimationController _controller by mixing our _RingPainterState class with SingleTickerProviderStateMixin and initilized it within initState() method.</li><li>Started the animation with _controller.forward()</li><li>Added listener to the controller and a setState((){}) is called so that our entire UI rebuilds whenever value of our _controller changes.</li><li>Now our MyPainter<strong> </strong>class expects three required arguments: progress, defaultColor of the circle stroke and fill color. It is done so in order to pass the various values from outside of this class and to make this component reusable. Note that shouldRepaint() method is updated such that our Circle should only be drawn whenever the progress value differs from the previous value.</li><li>Finally passed these three arguments to the MyPainter<strong> </strong>class with progress value being the current value of the animation.</li></ol><p>With the current implementation, we are successful to achieve this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7Cw_N40IXk8IUCxUiTMFUg.gif" /></figure><p>Woah, we are almost to the end! The only thing remaining is to add an Icon at the middle of the circle and change its color depending upon whether the animation is completed or not.</p><p>In order to achieve this update your build method like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9bac5289c3d5d2f4be55a24a3cf82ac1/href">https://medium.com/media/9bac5289c3d5d2f4be55a24a3cf82ac1/href</a></iframe><p>The following implementation would result in this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IJ3k4iAr9xiZEBYxlB6YEw.gif" /></figure><p>So now successfully achieved what we desired.</p><p>I hope you have learned something about the CustomPaint widget. Now you can explore on your own to achieve various other effects.</p><p>Thanks for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ff2e1d6f8309" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/custompaint-in-flutter-ff2e1d6f8309">Build a Custom Paint Flutter App Widget</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Popup Menu Customization in Flutter]]></title>
            <link>https://medium.com/better-programming/popup-menu-customization-in-flutter-aa8827f6ce39?source=rss-73cfafe26097------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa8827f6ce39</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Gajendra Pandeya]]></dc:creator>
            <pubDate>Tue, 08 Feb 2022 16:39:08 GMT</pubDate>
            <atom:updated>2022-02-17T08:27:48.096Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>Do more than just dropdown</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rLAcZIAbA3iSrjhv" /><figcaption>Photo by <a href="https://unsplash.com/@clarktibbs?utm_source=medium&amp;utm_medium=referral">Clark Tibbs</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Today we will look at one of the most used widgets on any app i.e. Popup Menu.</p><p>By the end of this read, we would be creating something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/324/1*XxI7V3_VyBZKWSbUKrTJoA.png" /></figure><p>If you want the code checkout <a href="https://github.com/gajendrapandeya/PoupMenuCustomizationFlutter">here</a>.</p><h4>Table of Contents</h4><ol><li>Introduction</li><li>Popup Menu Button Constructor</li><li>Creating Normal Popup Menu</li><li>Customizing Menu Button according to our need</li></ol><h3><strong>Introduction</strong></h3><p>Popup menus are one of the most used widgets that display a menu when pressed and calls onselected<em> </em>when the menu is dismissed because an item was selected. Think of it as when you right-click your mouse, you see a list of menu items such as view, sort by, refresh, and …</p><figure><img alt="Windows Menu Item" src="https://cdn-images-1.medium.com/max/266/1*xEhy2MIoeNa2uo2jUjTHOw.png" /></figure><p>So now we know what popup menus are. Let’s deep dive into the constructor and see the properties.</p><h3><strong>Popup Menu Constructor</strong></h3><pre><a href="https://api.flutter.dev/flutter/material/PopupMenuButton/PopupMenuButton.html">PopupMenuButton</a>({<a href="https://api.flutter.dev/flutter/foundation/Key-class.html">Key</a>? key, required <a href="https://api.flutter.dev/flutter/material/PopupMenuItemBuilder.html">PopupMenuItemBuilder</a>&lt;T&gt; itemBuilder, T? initialValue, <a href="https://api.flutter.dev/flutter/material/PopupMenuItemSelected.html">PopupMenuItemSelected</a>&lt;T&gt;? onSelected, <a href="https://api.flutter.dev/flutter/material/PopupMenuCanceled.html">PopupMenuCanceled</a>? onCanceled, <a href="https://api.flutter.dev/flutter/dart-core/String-class.html">String</a>? tooltip, <a href="https://api.flutter.dev/flutter/dart-core/double-class.html">double</a>? elevation, <a href="https://api.flutter.dev/flutter/painting/EdgeInsetsGeometry-class.html">EdgeInsetsGeometry</a> padding = const EdgeInsets.all(8.0), <a href="https://api.flutter.dev/flutter/widgets/Widget-class.html">Widget</a>? child, <a href="https://api.flutter.dev/flutter/widgets/Widget-class.html">Widget</a>? icon, <a href="https://api.flutter.dev/flutter/dart-core/double-class.html">double</a>? iconSize, <a href="https://api.flutter.dev/flutter/dart-ui/Offset-class.html">Offset</a> offset = Offset.zero, <a href="https://api.flutter.dev/flutter/dart-core/bool-class.html">bool</a> enabled = true, <a href="https://api.flutter.dev/flutter/painting/ShapeBorder-class.html">ShapeBorder</a>? shape, <a href="https://api.flutter.dev/flutter/dart-ui/Color-class.html">Color</a>? color, <a href="https://api.flutter.dev/flutter/dart-core/bool-class.html">bool</a>? enableFeedback})</pre><p>Let’s deep dive into each parameter of the constructor.</p><p>key: It uniquely identifies specific widgets within in the collection. Rarely used in Popup menu constructor.</p><p>itemBuilder: creates the item to show in the menu.</p><p>initialValue: Makes sure that the item is highlighted when you open the menu. Make sure to provide it inside Menu Item as well.</p><p>onSelected: Called when user selects value from the popup menu button.</p><p>onCanceled: Called when user dismiss the popup menu without selecting the item.</p><p>tooltip: Text that describes the action that will occur when the menu item is long pressed.</p><p>elevation: Controls the size of the shadow behind the menu.</p><p>padding: Sets the padding of the menu item. Useful to be able to set the padding to zero.</p><p>child: If provided, child is the widget used for this button and the button will utilize an Inkwell for taps.</p><p>offset: Useful property when you want to display menu at a particular position. Will be discussed later.</p><p>color: Provides the background color for the Popup Menu.</p><p>shape: Used to provide specific shape to our popup menu.</p><h3><strong>Creating Normal Popup Menu</strong></h3><p>In most cases, we will be using a popup menu as trailing widget in our appbar. We will also do so but can be used anywhere, the method will remain the same.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4093bca663f26c1cb64f917e2cd4cc99/href">https://medium.com/media/4093bca663f26c1cb64f917e2cd4cc99/href</a></iframe><p>For code reusability, I have created a method named _buildAppBar() that constructs a basic appbar with action as a PopupMenuButton which consist of itembuilder property that defines how to build a single menu item which is defined below in the _buildPopupMenuItem() method. The current implementation results are as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/328/1*VQcJBUOEPGQVjrWJEHV00g.png" /></figure><p>The child property inside a PopupMenuItem can be any widget. Suppose we want to have an icon and text widget as a menu item, then we do the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5edc1110fa2f2bd63fcce4e77f1007ae/href">https://medium.com/media/5edc1110fa2f2bd63fcce4e77f1007ae/href</a></iframe><p>The current implementation results in this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/323/1*Z7khZye8D9KGTBEhaagg0w.png" /></figure><p>We can change the background color of PopupMenuButton by adding a property called color as well as we can do a hell lot of other customizations as discussed above.</p><p>If we want to perform a particular action on click of a particular MenuItem, we have to supply an additional argument named value inside PopupMenuItem and adjust according to our needs.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cb47e858454b73a2294919ec153d20db/href">https://medium.com/media/cb47e858454b73a2294919ec153d20db/href</a></iframe><p>Here what we have done is that we have added a property name onSelected inside the PopumenuButton that executes a method _onMenuItemSelected() inside of which we have changed the value of the variable named _changeColorAccordingToMenuItem. Also, don&#39;t forget to pass the value argument into the _buildPopupMenuItem() method.</p><p>The current implementation results in this on click of ‘Upload’ option:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/324/1*6NueQoC88FYN8NINBQBFlw.png" /></figure><p>You can perform various other operations like navigating to other pages whenever a menu item is pressed according to your need.</p><h3><strong>Customizing Menu Button according to our need</strong></h3><p>Now our need is to put PopupMenu below the appbar and it should have some rounded corner shape. To achieve that, we will supply the property named offset inside the PopupMenuButton that expects x and y coordinates.</p><p>For our y coordinate, we will calculate the height of appbar and pass into the Offset() constructor as the second argument as we want our menu to lie below the appbar.</p><p>Similiary, for making rounded corner shape, we will provide shape property to our PopupMenuButton.</p><p>The final code looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ada14a3d2a8fe57b519ea8a39a264b43/href">https://medium.com/media/ada14a3d2a8fe57b519ea8a39a264b43/href</a></iframe><p>The given code results in this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/324/1*XxI7V3_VyBZKWSbUKrTJoA.png" /></figure><p>I hope this article was helpful for you to understand about the popup menu. You can customize it all the way to your need. Thanks for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa8827f6ce39" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/popup-menu-customization-in-flutter-aa8827f6ce39">Popup Menu Customization in Flutter</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>