<?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 Praveen K P on Medium]]></title>
        <description><![CDATA[Stories by Praveen K P on Medium]]></description>
        <link>https://medium.com/@praveenkprathap?source=rss-cf25f9f9bb7c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*VFL8udgNHmVCg5NbLcxF5g.jpeg</url>
            <title>Stories by Praveen K P on Medium</title>
            <link>https://medium.com/@praveenkprathap?source=rss-cf25f9f9bb7c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 22:58:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@praveenkprathap/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[Explore the Power of Async and Async* in Flutter.]]></title>
            <link>https://medium.com/@praveenkprathap/explore-the-power-of-async-and-async-in-flutter-9dd3cfb9a80d?source=rss-cf25f9f9bb7c------2</link>
            <guid isPermaLink="false">https://medium.com/p/9dd3cfb9a80d</guid>
            <dc:creator><![CDATA[Praveen K P]]></dc:creator>
            <pubDate>Tue, 21 Feb 2023 12:59:44 GMT</pubDate>
            <atom:updated>2023-02-21T12:59:44.919Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, we’ll discuss two important concepts in Dart’s asynchronous programming model: Futures and Streams, and their counterparts, async and async* functions.</p><h3>Understanding Asynchronous Programming in Dart</h3><p>Asynchronous programming in Dart enables you to perform operations that take a long time to complete, such as network requests or database queries, without blocking the execution of your program. When you execute a long-running operation synchronously, it can cause your application to freeze or become unresponsive until the operation is complete. Asynchronous programming solves this problem by allowing you to execute long-running operations asynchronously, so that other parts of your application can continue to execute in the meantime.</p><h3>Futures in Dart</h3><p>A Future represents a value that may not be available yet. It is a placeholder for a value that will be available sometime in the future. Futures are commonly used to represent asynchronous operations that may take some time to complete, such as network requests or database queries. When a Future completes, it can either have a value or an error.</p><p>You can create a Future in Dart by using the Future class constructor and passing in a callback function that performs the asynchronous operation. Here&#39;s an example of a Future that retrieves a user&#39;s data from a remote server:</p><pre>Future&lt;User&gt; getUser(String userId) {<br>  return Future.delayed(Duration(seconds: 1), () {<br>    return User(<br>      id: userId,<br>      name: &#39;John Doe&#39;,<br>      email: &#39;john.doe@example.com&#39;,<br>    );<br>  });<br>}</pre><p>In this example, the getUser function returns a Future&lt;User&gt; object that represents the user&#39;s data. The function simulates a network request that takes one second to complete by using the Future.delayed method. When the network request completes, the user&#39;s data is returned as a User object.</p><p>To retrieve the user’s data from the Future, you can use the then method to register a callback function that will be called when the Future completes:</p><pre>void main() {<br>  getUser(&#39;123&#39;).then((user) {<br>    print(&#39;User ID: ${user.id}&#39;);<br>    print(&#39;User Name: ${user.name}&#39;);<br>    print(&#39;User Email: ${user.email}&#39;);<br>  });<br>}</pre><p>In this example, the main function calls the getUser function with a user ID of 123 and registers a callback function that prints the user&#39;s data to the console.</p><h3>Streams in Dart</h3><p>A Stream is a sequence of asynchronous events that can be processed one at a time. It is similar to a Future, but it can emit multiple values over time, rather than a single value. Streams are commonly used to represent data that is continuously changing, such as user input or real-time data from a sensor.</p><p>You can create a Stream in Dart by using the Stream class constructor and passing in a callback function that produces the events. Here&#39;s an example of a Stream that emits a sequence of numbers:</p><pre>Stream&lt;int&gt; countNumbers(int max) async* {<br>  for (int i = 1; i &lt;= max; i++) {<br>    yield i;<br>  }<br>}</pre><p>In this example, the countNumbers function returns a Stream&lt;int&gt; object that emits a sequence of numbers from 1 to max. The async* keyword indicates that this is an async generator function, which allows the function to produce a sequence of values over time.</p><p>To process the events from the Stream, you can use the listen method to register a callback function that will be called for each event:</p><pre>void main() {<br>  countNumbers(5).listen((number) {<br>    print(number);<br>  });<br>}</pre><p>In this example, the main function calls the countNumbers function with a maximum value of 5 and registers a callback function that prints each number to the console.</p><h3>Async and Async* Functions in Dart</h3><p>An async function in Dart is a function that performs an asynchronous operation and returns a Future. The async keyword is used to mark the function as asynchronous, which enables you to use await expressions to pause the function&#39;s execution until a Future completes. Here&#39;s an example of an async function that retrieves a user&#39;s data from a remote server:</p><pre>Future&lt;User&gt; getUser(String userId) async {<br>  final response = await http.get(Uri.parse(&#39;https://example.com/users/$userId&#39;));<br><br>  if (response.statusCode == 200) {<br>    final userData = json.decode(response.body);<br>    return User(<br>      id: userData[&#39;id&#39;],<br>      name: userData[&#39;name&#39;],<br>      email: userData[&#39;email&#39;],<br>    );<br>  } else {<br>    throw Exception(&#39;Failed to retrieve user data&#39;);<br>  }<br>}</pre><p>In this example, the getUser function retrieves the user&#39;s data from a remote server using the http package. The await keyword is used to pause the function&#39;s execution until the server response is received. If the response status code is 200, the user&#39;s data is decoded from the JSON response and returned as a User object. If the response status code is not 200, an exception is thrown.</p><p>An async* function in Dart is a function that returns a Stream. The async* keyword is used to mark the function as an async generator function, which allows the function to produce a sequence of values over time. Here&#39;s an example of an async* function that searches for a song in a large collection of songs:</p><pre>Stream&lt;Song&gt; searchSong(String query) async* {<br>  for (var song in allSongs) {<br>    if (song.title.toLowerCase().contains(query.toLowerCase())) {<br>      yield song;<br>    }<br>  }<br>}</pre><p>In this example, the searchSong function searches for a song in a large collection of songs by checking if the song title contains the search query. The function uses the async* keyword to indicate that it is an async generator function that produces a Stream&lt;Song&gt; of matching songs.</p><h3>Using FutureBuilder and StreamBuilder in Flutter</h3><p>Flutter provides two widgets, FutureBuilder and StreamBuilder, which make it easy to handle Future and Stream objects in your UI. Both widgets rebuild themselves whenever the Future or Stream emits a new value, which enables you to update your UI in real-time.</p><p>Here&#39;s an example of a FutureBuilder that displays a user&#39;s data:</p><pre>class UserWidget extends StatelessWidget {<br>  final Future&lt;User&gt; user;<br><br>  UserWidget({required this.user});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return FutureBuilder&lt;User&gt;(<br>      future: user,<br>      builder: (context, snapshot) {<br>        if (snapshot.hasData) {<br>          final user = snapshot.data!;<br>          return Column(<br>            crossAxisAlignment: CrossAxisAlignment.start,<br>            children: [<br>              Text(&#39;User ID: ${user.id}&#39;),<br>              Text(&#39;User Name: ${user.name}&#39;),<br>              Text(&#39;User Email: ${user.email}&#39;),<br>            ],<br>          );<br>        } else if (snapshot.hasError) {<br>          return Text(&#39;Failed to retrieve user data&#39;);<br>        } else {<br>          return CircularProgressIndicator();<br>        }<br>      },<br>    );<br>  }<br>}</pre><p>this example, the UserWidget displays a user&#39;s data using a FutureBuilder. The UserWidget takes a Future&lt;User&gt; as a parameter and passes it to the future property of the FutureBuilder. The builder function of the FutureBuilder takes a BuildContext and a AsyncSnapshot&lt;User&gt; as parameters. The builder function checks the snapshot for the current state of the Future. If the snapshot has data, the user&#39;s data is displayed in a Column. If the snapshot has an error, an error message is displayed. If the snapshot is still loading, a CircularProgressIndicator is displayed.</p><p>Here’s an example of a StreamBuilder that displays a list of numbers:</p><pre>class NumbersWidget extends StatelessWidget {<br>  final Stream&lt;int&gt; numbers;<br><br>  NumbersWidget({required this.numbers});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return StreamBuilder&lt;int&gt;(<br>      stream: numbers,<br>      builder: (context, snapshot) {<br>        if (snapshot.hasData) {<br>          final numbers = snapshot.data!;<br>          return ListView.builder(<br>            itemCount: numbers.length,<br>            itemBuilder: (context, index) {<br>              return ListTile(<br>                title: Text(&#39;${numbers[index]}&#39;),<br>              );<br>            },<br>          );<br>        } else if (snapshot.hasError) {<br>          return Text(&#39;Failed to retrieve numbers data&#39;);<br>        } else {<br>          return CircularProgressIndicator();<br>        }<br>      },<br>    );<br>  }<br>}</pre><p>In this example, the NumbersWidget displays a list of numbers using a StreamBuilder. The NumbersWidget takes a Stream&lt;int&gt; as a parameter and passes it to the stream property of the StreamBuilder. The builder function of the StreamBuilder takes a BuildContext and a AsyncSnapshot&lt;int&gt; as parameters. The builder function checks the snapshot for the current state of the Stream. If the snapshot has data, the list of numbers is displayed in a ListView.builder. If the snapshot has an error, an error message displayed. If the snapshot is still loading, a CircularProgressIndicator is displayed.</p><h3>Conclusion</h3><p>In conclusion, async and async* are important features in Dart that enable developers to work with asynchronous operations in a more efficient and readable way. The async keyword is used to mark a function as asynchronous and to enable the use of await expressions to pause the function&#39;s execution until a Future completes. The async* keyword is used to mark a function as an async generator function that produces a sequence of values over time using a Stream.</p><p>In Flutter, the FutureBuilder and StreamBuilder widgets make it easy to handle Future and Stream objects in your UI by automatically rebuilding themselves whenever the Future or Stream emits a new value. These widgets enable you to create responsive and real-time UIs that can handle asynchronous operations with ease.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9dd3cfb9a80d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter Isolates: Improving App Performance with Parallel Processing]]></title>
            <link>https://medium.com/@praveenkprathap/flutter-isolates-improving-app-performance-with-parallel-processing-c2dfeacdea7d?source=rss-cf25f9f9bb7c------2</link>
            <guid isPermaLink="false">https://medium.com/p/c2dfeacdea7d</guid>
            <dc:creator><![CDATA[Praveen K P]]></dc:creator>
            <pubDate>Mon, 20 Feb 2023 13:17:41 GMT</pubDate>
            <atom:updated>2023-02-20T13:17:41.561Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dg1p27NoWYMf1epLeitBpw.png" /></figure><p>In this article, we’ll take a closer look at what isolates are, how they work, and how you can use them in your Flutter applications.</p><p>What are Isolates?</p><p>An isolate is a lightweight process that runs in its own memory space, separate from the main application thread. Isolates are designed to execute code concurrently without interfering with each other. They can communicate with each other using messages, which are passed between isolates using message passing.</p><p>The use of isolates is important in mobile app development because it allows developers to perform computationally expensive tasks without blocking the user interface. For example, if you need to perform a complex calculation, you can do it in an isolate and update the UI once the calculation is complete.</p><p>How do Isolates work?</p><p>Isolates are similar to threads, but with a few key differences. Threads run in the same memory space as the main application thread, and can access and modify shared data. This can lead to issues such as race conditions and deadlocks. Isolates, on the other hand, have their own memory space and cannot directly access or modify data in other isolates. Instead, they communicate with each other using messages.</p><p>Isolates are created using the Isolate.spawn method. This method takes a function as an argument, which is the entry point for the isolate. Here&#39;s an example:</p><pre>Isolate.spawn(myFunction, myData);</pre><p>In this example, myFunction is the function that will run in the isolate, and myData is any data that you want to pass to the isolate.</p><p>Once an isolate is created, it runs independently of the main application thread. You can communicate with the isolate using message passing, which is done using the SendPort and ReceivePort classes. Here&#39;s an example:</p><pre>// Create a ReceivePort to receive messages from the isolate<br>ReceivePort receivePort = ReceivePort();<br><br>// Spawn the isolate and get its SendPort<br>Isolate.spawn(myFunction, receivePort.sendPort);<br><br>// Listen for messages from the isolate<br>receivePort.listen((message) {<br>  print(&#39;Received message from isolate: $message&#39;);<br>});</pre><p>In this example, we create a ReceivePort to receive messages from the isolate, and then spawn the isolate and get its SendPort. We then listen for messages on the ReceivePort, and print out any messages that we receive.</p><p>Examples of using Isolates in Flutter</p><ol><li>Performing a complex calculation</li></ol><p>Let’s say we want to perform a complex calculation, such as calculating the factorial of a large number. We can do this in an isolate to avoid blocking the UI thread. Here’s an example:</p><pre>Future&lt;int&gt; calculateFactorial(int n) async {<br>  // Create a ReceivePort to receive the result from the isolate<br>  ReceivePort receivePort = ReceivePort();<br><br>  // Spawn the isolate and get its SendPort<br>  Isolate.spawn(_factorialIsolate, n, onExit: receivePort.sendPort);<br><br>  // Wait for the result from the isolate<br>  int result = await receivePort.first;<br><br>  // Return the result<br>  return result;<br>}<br><br>void _factorialIsolate(int n) {<br>  int result = 1;<br>  for (int i = 1; i &lt;= n; i++) {<br>    result *= i;<br>  }<br>  // Send the result back to the main thread<br>  SendPort sendPort = IsolateNameServer.lookupPortByName(&#39;factorial&#39;);<br>  sendPort.send(result);<br>}</pre><p>In this example, we define a function calculateFactorial that creates an isolate to calculate the factorial of a number n. The _factorialIsolate function is the entry point for the isolate and performs the actual calculation. It then sends the result back to the main thread using the SendPort.</p><p>To use this function, we can call it from our UI code as follows:</p><pre>int result = await calculateFactorial(10);<br>print(&#39;Factorial of 10 is $result&#39;);</pre><p>In this example, we calculate the factorial of 10 and print the result. Since the calculation is done in an isolate, it does not block the UI thread.</p><ol><li>Parallelizing network requests</li></ol><p>Another use case for isolates is parallelizing network requests. Let’s say we have a list of URLs that we want to fetch, and we want to fetch them in parallel to improve performance. We can use isolates to achieve this. Here’s an example:</p><pre>Future&lt;List&lt;String&gt;&gt; fetchUrls(List&lt;String&gt; urls) async {<br>  // Create a list of ReceivePorts to receive the results from the isolates<br>  List&lt;ReceivePort&gt; receivePorts = List.generate(urls.length, (_) =&gt; ReceivePort());<br><br>  // Spawn an isolate for each URL and get its SendPort<br>  List&lt;SendPort&gt; sendPorts = [];<br>  for (int i = 0; i &lt; urls.length; i++) {<br>    Isolate.spawn(_fetchUrlIsolate, [urls[i], receivePorts[i].sendPort]);<br>    sendPorts.add(await IsolateNameServer.lookupPortByName(&#39;url-$i&#39;));<br>  }<br><br>  // Wait for the results from the isolates<br>  List&lt;String&gt; results = await Future.wait(<br>      receivePorts.map((receivePort) =&gt; receivePort.first).toList());<br><br>  // Return the results<br>  return results;<br>}<br><br>void _fetchUrlIsolate(List data) async {<br>  String url = data[0];<br>  SendPort sendPort = data[1];<br><br>  // Fetch the URL<br>  http.Response response = await http.get(Uri.parse(url));<br>  String body = response.body;<br><br>  // Send the result back to the main thread<br>  sendPort.send(body);<br><br>  // Register the SendPort so it can be looked up by name<br>  int isolateId = Isolate.current.hashCode;<br>  IsolateNameServer.registerPortWithName(sendPort, &#39;url-$isolateId&#39;);<br>}</pre><p>In this example, we define a function fetchUrls that takes a list of URLs as input and uses isolates to fetch the URLs in parallel. The _fetchUrlIsolate function is the entry point for each isolate and performs the actual network request. It then sends the result back to the main thread using the SendPort.</p><p>To use this function, we can call it from our UI code as follows:</p><pre>List&lt;String&gt; urls = [&#39;https://example.com&#39;, &#39;https://google.com&#39;, &#39;https://facebook.com&#39;];<br>List&lt;String&gt; results = await fetchUrls(urls);<br>print(&#39;Results: $results&#39;);</pre><p>In this example, we fetch three URLs in parallel and print the results. Since the requests are made in isolates, they do not block the UI thread.</p><p>Conclusion</p><p>In this article, we’ve seen how isolates can be used to perform concurrent operations in Flutter applications. Isolates are a powerful tool for improving performance and avoiding blocking the UI thread. By using isolates, you can perform computationally expensive tasks and network requests without affecting the user experience. With a little bit of practice, you’ll be able to use isolates to create fast and responsive Flutter applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c2dfeacdea7d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>