<?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"><channel><title><![CDATA[Harish Learns Code]]></title><description><![CDATA[Flutter SDK Engineer at Esri. I mostly write about Flutter and Rust.]]></description><link>https://harishkunchala.com</link><generator>RSS for Node</generator><lastBuildDate>Tue, 10 Nov 2026 06:24:57 GMT</lastBuildDate><atom:link href="https://harishkunchala.com/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Microsoft Edge: Favorites in “Workspaces” are now displayed in folders instead of directly in the bar [Fix]]]></title><description><![CDATA[While I generally write about Flutter. This problem has been bugging me for a while and there seem to be limited resources to find a solution. So for…]]></description><link>https://harishkunchala.com/microsoft-edge-favorites-in-workspaces-are-now-displayed-in-folders-instead-of-directly-in-the-bar-fix</link><guid isPermaLink="true">https://harishkunchala.com/microsoft-edge-favorites-in-workspaces-are-now-displayed-in-folders-instead-of-directly-in-the-bar-fix</guid><dc:creator><![CDATA[Harish Kunchala]]></dc:creator><pubDate>Mon, 20 Jan 2025 21:06:38 GMT</pubDate><content:encoded><![CDATA[<p>While I generally write about Flutter. This problem has been bugging me for a while and there seem to be limited resources to find a solution. So for anyone who is looking for a solution. Here you go:</p>
<ul>
<li><p>Type <code>edge:flags</code> into the address bar and open it</p>
</li>
<li><p>Search for "favorites"</p>
</li>
<li><p>Set "Show Workspace Favorites in Favorites Bar" to enabled</p>
</li>
<li><p>Restart the browser</p>
</li>
</ul>
<p>Hope this helps.</p>
]]></content:encoded></item><item><title><![CDATA[Flutter Dio Part 3: Interceptors]]></title><description><![CDATA[In this tutorial, we’ll go through covering interceptor, which is a very crucial feature of Dio. You can find the entire source code for the project here…]]></description><link>https://harishkunchala.com/flutter-dio-part-3-interceptors</link><guid isPermaLink="true">https://harishkunchala.com/flutter-dio-part-3-interceptors</guid><category><![CDATA[Flutter]]></category><category><![CDATA[dio]]></category><category><![CDATA[networking]]></category><dc:creator><![CDATA[Harish Kunchala]]></dc:creator><pubDate>Wed, 04 Dec 2024 19:27:23 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1733340404796/15e2b6b7-f20f-472a-931b-4a77d284670d.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In this tutorial, we’ll go through covering interceptor, which is a very crucial feature of Dio. You can find the entire source code for the project here: <a target="_blank" href="https://github.com/harish-kunchala/dio_tasker">dio_tasker</a></p>
<h3 id="heading-understanding-interceptors">Understanding Interceptors:</h3>
<p><strong>What is an interceptor?</strong></p>
<ul>
<li><p>An interceptor in Dio is a powerful feature <mark>that allows us to intercept and modify HTTP requests and responses before they are handled by the application</mark>.</p>
</li>
<li><p>Interceptors can be used for various purposes such as logging, adding headers, handling errors, and more.</p>
</li>
</ul>
<p><strong>Benefits of using Interceptors:</strong></p>
<ol>
<li><p><strong>Centralized Logic</strong>: Interceptors allows us to centralize logic that should be applied to multiple requests or responses, such as adding authentication tokens or logging.</p>
</li>
<li><p><strong>Code Reusability</strong>: By using interceptors, we can avoid duplicating code across different parts of our application.</p>
</li>
<li><p><strong>Error Handling</strong>: Interceptors can be used to handle errors globally, providing a consistent way to manage errors across our application.</p>
</li>
<li><p><strong>Request/ Response Modification</strong>: We can modify requests and responses, such as adding headers, transforming response data, before they reach application logic.</p>
</li>
<li><p><strong>Logging</strong>: Interceptors are useful for logging requests and responses, which can help with debugging and monitoring.</p>
</li>
</ol>
<p>Since interceptors are such a crucial concept, we’ll go through 5 sub tutorials that’ll cover all the aspects of interceptors.</p>
<h3 id="heading-tutorial-1-basic-logging-interceptor">Tutorial 1: Basic Logging Interceptor</h3>
<p>Our objective is to create a simple logging interceptor to log all the requests and responses.</p>
<p><strong>Create a Logging Interceptor:</strong></p>
<ul>
<li>Within our <a target="_blank" href="https://github.com/harish-kunchala/dio_tasker">dio_tasker</a> let’s create a new file <code>lib/interceptors/logging_interceptor.dart</code></li>
</ul>
<pre><code class="lang-dart"><span class="hljs-keyword">import</span> <span class="hljs-string">'package:dio/dio.dart'</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">LoggingInterceptor</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Interceptor</span> </span>{

  <span class="hljs-comment">/// <span class="markdown">onRequest: This method is called before a request is sent.</span></span>
  <span class="hljs-comment">/// <span class="markdown">We log the HTTP method (GET, POST, etc.) and the request path.</span></span>
  <span class="hljs-meta">@override</span>
  <span class="hljs-keyword">void</span> onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    <span class="hljs-comment">// Log the request method and path.</span>
    <span class="hljs-built_in">print</span>(<span class="hljs-string">'REQUEST[<span class="hljs-subst">${options.method}</span>] =&gt; PATH: <span class="hljs-subst">${options.path}</span>'</span>);
    <span class="hljs-comment">// Continue with the request.</span>
    <span class="hljs-keyword">super</span>.onRequest(options, handler);
  }

  <span class="hljs-comment">/// <span class="markdown">onResponse: This method is called when a response is received.</span></span>
  <span class="hljs-comment">/// <span class="markdown">We log the status code and the request path.</span></span>
  <span class="hljs-meta">@override</span>
  <span class="hljs-keyword">void</span> onResponse(Response response, ResponseInterceptorHandler handler) {
    <span class="hljs-comment">// Log the response status code and path.</span>
    <span class="hljs-built_in">print</span>(
        <span class="hljs-string">'RESPONSE[<span class="hljs-subst">${response.statusCode}</span>] =&gt; PATH: <span class="hljs-subst">${response.requestOptions.path}</span>'</span>);
    <span class="hljs-comment">// Continue with the response.</span>
    <span class="hljs-keyword">super</span>.onResponse(response, handler);
  }

  <span class="hljs-comment">/// <span class="markdown">onError: This method is called when an error occurs. </span></span>
  <span class="hljs-comment">/// <span class="markdown">We log the error status code (if available) and the request path.</span></span>
  <span class="hljs-meta">@override</span>
  <span class="hljs-keyword">void</span> onError(DioException err, ErrorInterceptorHandler handler) {
    <span class="hljs-comment">// Log the error status code and path.</span>
    <span class="hljs-built_in">print</span>(
        <span class="hljs-string">'ERROR[<span class="hljs-subst">${err.response?.statusCode}</span>] =&gt; PATH: <span class="hljs-subst">${err.requestOptions.path}</span>'</span>);
    <span class="hljs-comment">// Continue with the error.</span>
    <span class="hljs-keyword">super</span>.onError(err, handler);
  }
}
</code></pre>
<p><strong>Add the interceptor to Dio:</strong></p>
<ul>
<li>Let’s modify our <code>lib/services/api_service.dart</code> to include the logging interceptor:</li>
</ul>
<pre><code class="lang-dart"><span class="hljs-keyword">import</span> <span class="hljs-string">'package:dio/dio.dart'</span>;
<span class="hljs-keyword">import</span> <span class="hljs-string">'package:dio_tasker/interceptors/logging_interceptor.dart'</span>;

<span class="hljs-keyword">import</span> <span class="hljs-string">'../models/tasks.dart'</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ApiService</span> </span>{
  <span class="hljs-keyword">final</span> Dio _dio;

  ApiService() : _dio = Dio() {
    <span class="hljs-comment">// Add the logging interceptor</span>
    _dio.interceptors.add(LoggingInterceptor());
  }

  <span class="hljs-comment">// Method to fetch tasks from the API</span>
  Future&lt;<span class="hljs-built_in">List</span>&lt;Task&gt;&gt; fetchTasks() <span class="hljs-keyword">async</span> {
    <span class="hljs-keyword">try</span> {
      <span class="hljs-comment">// Make a GET request to fetch tasks</span>
      <span class="hljs-keyword">final</span> response =
          <span class="hljs-keyword">await</span> _dio.<span class="hljs-keyword">get</span>(<span class="hljs-string">'https://jsonplaceholder.typicode.com/todos'</span>);
      <span class="hljs-comment">// Parse the response data into a list of Task objects</span>
      <span class="hljs-keyword">return</span> (response.data <span class="hljs-keyword">as</span> <span class="hljs-built_in">List</span>)
          .map((task) =&gt; Task.fromJSON(task))
          .toList();
    } <span class="hljs-keyword">on</span> DioException <span class="hljs-keyword">catch</span> (dioException) {
      <span class="hljs-comment">// Handle Dio Exceptions</span>
      <span class="hljs-keyword">if</span> (dioException.type == DioExceptionType.connectionTimeout) {
        <span class="hljs-keyword">throw</span> Exception(<span class="hljs-string">'Connection Timeout'</span>);
      } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (dioException.type == DioExceptionType.receiveTimeout) {
        <span class="hljs-keyword">throw</span> Exception(<span class="hljs-string">'Receive Timeout'</span>);
      } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (dioException.type == DioExceptionType.badResponse) {
        <span class="hljs-keyword">throw</span> Exception(
            <span class="hljs-string">'Received invalid status code: <span class="hljs-subst">${dioException.response?.statusCode}</span>'</span>);
      } <span class="hljs-keyword">else</span> {
        <span class="hljs-keyword">throw</span> Exception(<span class="hljs-string">'Something went wrong'</span>);
      }
    } <span class="hljs-keyword">catch</span> (e) {
      <span class="hljs-comment">// Handle other errors</span>
      <span class="hljs-keyword">throw</span> Exception(<span class="hljs-string">'Failed to load tasks'</span>);
    }
  }
}
</code></pre>
<p><strong>Test the Interceptor:</strong></p>
<ul>
<li>Let’s run the app and check the console for logs of requests and responses.</li>
</ul>
<p><img src="https://i.postimg.cc/HnYTG13m/Screenshot-2024-12-03-at-1-01-54-PM.png" alt="interceptor-terminal-output" /></p>
<p>Perfect, so as we can see we are able to log both the request and response.</p>
<p>You can find the source code here: <a target="_blank" href="https://github.com/harish-kunchala/dio_tasker/tree/03-01-logging-interceptor">dio_tasker/03-01-logging-interceptors</a>.</p>
<h3 id="heading-understanding-headers">Understanding Headers</h3>
<p><strong>What are Headers?</strong></p>
<ul>
<li><p>Headers are key-value pairs sent along with HTTP requests and responses.</p>
</li>
<li><p>They provide essential information about the request or response, such as the type of content being sent, the length of the content, authentication details and more.</p>
</li>
<li><p>Headers play a crucial role in how the client and server communicate and process the data being exchanged.</p>
</li>
</ul>
<p><strong>Common Types of Headers:</strong></p>
<ul>
<li><p><strong>Content Type</strong>: Specifies the media type of the resource. For example, <code>application/json</code> indicates that the content is in JSON format.</p>
</li>
<li><p><strong>Authorization</strong>: Contains credentials for authenticating the client with the server. For example, <code>Bearer YOUR_TOKEN</code> is used for token-based authentication.</p>
</li>
<li><p><strong>Accept</strong>: Informs the server about the type of data the client can process. For example, <code>Accept: application/json</code> indicates that the client expects JSON data.</p>
</li>
<li><p><strong>User-Agent</strong>: Provides information about the client software making the request. For example, <code>User-Agent: Mozilla/5.0</code>.</p>
</li>
<li><p><strong>Cache-Control</strong>: Directs caching mechanisms on how to handle the request. For example, <code>Cache-Control: no-cache</code> instructs not to cache the response.</p>
</li>
</ul>
<p><strong>Importance of headers:</strong></p>
<ul>
<li><p><strong>Content Negotiation</strong>: Headers like <code>Content-Type</code> and <code>Accept</code> help in content negotiation between the client and server, ensuring that the data is in a format that both can understand.</p>
</li>
<li><p><strong>Authentication and Security</strong>: Headers such as <code>Authorization</code> are crucial for securing API requests and ensuring that only authenticated clients can access certain resources.</p>
</li>
<li><p><strong>Performance Optimization</strong>: Headers like <code>Cache-Control</code> can significantly impact the performance of web applications by controlling how responses are cached.</p>
</li>
<li><p><strong>Metadata</strong>: Headers provide additional metadata about the request or response, which can be used for debugging, logging and monitoring purposes.</p>
</li>
</ul>
<p>Now let’s look at tutorial where we add headers interceptor.</p>
<h3 id="heading-tutorial-2-adding-headers-interceptor">Tutorial 2: Adding Headers Interceptor</h3>
<p>Our objective is to create an interceptor to add common headers to all requests.</p>
<p><strong>Create a new Headers Interceptor</strong>:</p>
<ul>
<li>Let’s create a new file <code>lib/interceptors/headers_interceptor.dart</code></li>
</ul>
<pre><code class="lang-dart"><span class="hljs-keyword">import</span> <span class="hljs-string">'package:dio/dio.dart'</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">HeadersInterceptor</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Interceptor</span> </span>{

  <span class="hljs-comment">/// <span class="markdown">onRequest: This method is called before a request is sent.</span></span>
  <span class="hljs-comment">/// <span class="markdown">We add common headers such as <span class="hljs-code">`Content-Type`</span> and <span class="hljs-code">`Authorization`</span> to the request options.</span></span>
  <span class="hljs-meta">@override</span>
  <span class="hljs-keyword">void</span> onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    <span class="hljs-comment">// Add common headers to the request.</span>
    options.headers.addAll({
      <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'application/json'</span>,
      <span class="hljs-string">'Authorization'</span>: <span class="hljs-string">'Bearer YOUR_TOKEN'</span>,
    });
    <span class="hljs-comment">// Continue with the request.</span>
    <span class="hljs-keyword">super</span>.onRequest(options, handler);
  }
}
</code></pre>
<p><strong>Add the Interceptor to Dio:</strong></p>
<ul>
<li>Now, we have to modify <code>lib/services/api_service.dart</code> to include the headers interceptor:</li>
</ul>
<pre><code class="lang-dart"><span class="hljs-keyword">import</span> <span class="hljs-string">'package:dio/dio.dart'</span>;
<span class="hljs-keyword">import</span> <span class="hljs-string">'package:dio_tasker/interceptors/headers_interceptor.dart'</span>;
<span class="hljs-keyword">import</span> <span class="hljs-string">'package:dio_tasker/interceptors/logging_interceptor.dart'</span>;

<span class="hljs-keyword">import</span> <span class="hljs-string">'../models/tasks.dart'</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ApiService</span> </span>{
  <span class="hljs-keyword">final</span> Dio _dio;

  ApiService() : _dio = Dio() {
    <span class="hljs-comment">// Add the logging interceptor</span>
    _dio.interceptors.add(LoggingInterceptor());

    <span class="hljs-comment">// Add the headers interceptor.</span>
    _dio.interceptors.add(HeadersInterceptor());
  }

  <span class="hljs-comment">// Method to fetch tasks from the API</span>
  Future&lt;<span class="hljs-built_in">List</span>&lt;Task&gt;&gt; fetchTasks() <span class="hljs-keyword">async</span> {
    <span class="hljs-keyword">try</span> {
      <span class="hljs-comment">// Make a GET request to fetch tasks</span>
      <span class="hljs-keyword">final</span> response =
          <span class="hljs-keyword">await</span> _dio.<span class="hljs-keyword">get</span>(<span class="hljs-string">'https://jsonplaceholder.typicode.com/todos'</span>);
      <span class="hljs-comment">// Parse the response data into a list of Task objects</span>
      <span class="hljs-keyword">return</span> (response.data <span class="hljs-keyword">as</span> <span class="hljs-built_in">List</span>)
          .map((task) =&gt; Task.fromJSON(task))
          .toList();
    } <span class="hljs-keyword">on</span> DioException <span class="hljs-keyword">catch</span> (dioException) {
      <span class="hljs-comment">// Handle Dio Exceptions</span>
      <span class="hljs-keyword">if</span> (dioException.type == DioExceptionType.connectionTimeout) {
        <span class="hljs-keyword">throw</span> Exception(<span class="hljs-string">'Connection Timeout'</span>);
      } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (dioException.type == DioExceptionType.receiveTimeout) {
        <span class="hljs-keyword">throw</span> Exception(<span class="hljs-string">'Receive Timeout'</span>);
      } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (dioException.type == DioExceptionType.badResponse) {
        <span class="hljs-keyword">throw</span> Exception(
            <span class="hljs-string">'Received invalid status code: <span class="hljs-subst">${dioException.response?.statusCode}</span>'</span>);
      } <span class="hljs-keyword">else</span> {
        <span class="hljs-keyword">throw</span> Exception(<span class="hljs-string">'Something went wrong'</span>);
      }
    } <span class="hljs-keyword">catch</span> (e) {
      <span class="hljs-comment">// Handle other errors</span>
      <span class="hljs-keyword">throw</span> Exception(<span class="hljs-string">'Failed to load tasks'</span>);
    }
  }
}
</code></pre>
<p><strong>Log the Header:</strong></p>
<p>We can check the request headers to ensure the common headers are included. So, we can modify our <code>onRequest()</code> in our <code>LoggingInterceptor</code>:</p>
<pre><code class="lang-dart">  <span class="hljs-comment">/// <span class="markdown">onRequest: This method is called before a request is sent.</span></span>
  <span class="hljs-comment">/// <span class="markdown">We log the HTTP method (GET, POST, etc.) and the request path.</span></span>
  <span class="hljs-comment">/// <span class="markdown">We log the HTTP request headers</span></span>
  <span class="hljs-meta">@override</span>
  <span class="hljs-keyword">void</span> onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    <span class="hljs-comment">// Log the request method and path.</span>
    <span class="hljs-built_in">print</span>(<span class="hljs-string">'REQUEST[<span class="hljs-subst">${options.method}</span>] =&gt; PATH: <span class="hljs-subst">${options.path}</span>'</span>);
    <span class="hljs-comment">// Log the request header</span>
    <span class="hljs-built_in">print</span>(<span class="hljs-string">'REQUEST HEADER[<span class="hljs-subst">${options.headers.toString()}</span>'</span>);
    <span class="hljs-comment">// Continue with the request.</span>
    <span class="hljs-keyword">super</span>.onRequest(options, handler);
  }
</code></pre>
<p><strong>Test the Interceptor:</strong></p>
<p>Let’s run the app to make a request. Here’s output:</p>
<p><img src="https://i.postimg.cc/L53wpq5Q/Screenshot-2024-12-03-at-1-53-41-PM.png" alt="Headers Log" /></p>
<p>You can check out the source code above example here: <a target="_blank" href="https://github.com/harish-kunchala/dio_tasker/tree/03-02-headers-interceptor">dio_tasker/03-02-headers-interceptor</a></p>
<h3 id="heading-tutorial-3-retry-interceptor">Tutorial 3: Retry Interceptor:</h3>
<ul>
<li>Let’s create a new file <code>lib/interceptors/retry_interceptor.dart</code>:</li>
</ul>
<pre><code class="lang-dart"><span class="hljs-keyword">import</span> <span class="hljs-string">'package:dio/dio.dart'</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">RetryInterceptor</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Interceptor</span> </span>{
  <span class="hljs-keyword">final</span> Dio dio;

  RetryInterceptor(<span class="hljs-keyword">this</span>.dio);

  <span class="hljs-comment">/// <span class="markdown">onError: This method is called when an error occurs.</span></span>
  <span class="hljs-comment">/// <span class="markdown">We check if the request should be retried using the <span class="hljs-emphasis">_shouldRetry method. If it should, we retry the request.</span></span></span>
  <span class="hljs-comment">/// <span class="markdown"><span class="hljs-emphasis">If the retry fails, we call super.onError to pass the error to the next handler. If no retry is needed, we also call super.onError.</span></span></span>
  <span class="hljs-meta">@override</span>
  <span class="hljs-keyword">void</span> onError(DioException err, ErrorInterceptorHandler handler) <span class="hljs-keyword">async</span> {
    <span class="hljs-comment">// Check if the request should be retried</span>
    <span class="hljs-keyword">if</span> (_shouldRetry(err)) {
      <span class="hljs-keyword">try</span> {
        <span class="hljs-comment">// Retry the request</span>
        <span class="hljs-keyword">final</span> response = <span class="hljs-keyword">await</span> dio.request(
          err.requestOptions.path,
          options: Options(
            method: err.requestOptions.method,
            headers: err.requestOptions.headers,
          ),
        );

        <span class="hljs-comment">// Resolve the response</span>
        <span class="hljs-keyword">return</span> handler.resolve(response);
      } <span class="hljs-keyword">catch</span> (e) {
        <span class="hljs-comment">// If the retry fails, pass the error to the next handler.</span>
        <span class="hljs-keyword">return</span> handler.next(err);
      }
    }
    <span class="hljs-comment">// If no retry, pass the error to the next handler.</span>
    <span class="hljs-keyword">super</span>.onError(err, handler);
  }

  <span class="hljs-comment">// Determine if the request should be retried.</span>
  <span class="hljs-built_in">bool</span> _shouldRetry(DioException exception) {
    <span class="hljs-keyword">return</span> exception.type == DioExceptionType.connectionError ||
        exception.type == DioExceptionType.badResponse;
  }
}
</code></pre>
<p><strong>Add the Interceptor to Dio</strong>:</p>
<p>Now, let’s modify the <code>lib/services/api_service.dart</code> to add the <code>RetryInterceptor</code>:</p>
<pre><code class="lang-dart"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ApiService</span> </span>{
  <span class="hljs-keyword">final</span> Dio _dio;

  ApiService() : _dio = Dio() {
    <span class="hljs-comment">// Add the logging interceptor</span>
    _dio.interceptors.add(LoggingInterceptor());

    <span class="hljs-comment">// Add the headers interceptor.</span>
    _dio.interceptors.add(HeadersInterceptor());

    <span class="hljs-comment">// Add the retry interceptor.</span>
    _dio.interceptors.add(RetryInterceptor(_dio));
  }

  <span class="hljs-comment">// Method to fetch tasks from the API</span>
  Future&lt;<span class="hljs-built_in">List</span>&lt;Task&gt;&gt; fetchTasks() <span class="hljs-keyword">async</span> {
    <span class="hljs-keyword">try</span> {
      <span class="hljs-comment">// Make a GET request to fetch tasks</span>
      <span class="hljs-keyword">final</span> response =
          <span class="hljs-keyword">await</span> _dio.<span class="hljs-keyword">get</span>(<span class="hljs-string">'https://jsonplaceholder.typicode.com/todos'</span>);
      <span class="hljs-comment">// Parse the response data into a list of Task objects</span>
      <span class="hljs-keyword">return</span> (response.data <span class="hljs-keyword">as</span> <span class="hljs-built_in">List</span>)
          .map((task) =&gt; Task.fromJSON(task))
          .toList();
    } <span class="hljs-keyword">on</span> DioException <span class="hljs-keyword">catch</span> (dioException) {
      <span class="hljs-comment">// Handle Dio Exceptions</span>
      <span class="hljs-keyword">if</span> (dioException.type == DioExceptionType.connectionTimeout) {
        <span class="hljs-keyword">throw</span> Exception(<span class="hljs-string">'Connection Timeout'</span>);
      } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (dioException.type == DioExceptionType.receiveTimeout) {
        <span class="hljs-keyword">throw</span> Exception(<span class="hljs-string">'Receive Timeout'</span>);
      } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (dioException.type == DioExceptionType.badResponse) {
        <span class="hljs-keyword">throw</span> Exception(
            <span class="hljs-string">'Received invalid status code: <span class="hljs-subst">${dioException.response?.statusCode}</span>'</span>);
      } <span class="hljs-keyword">else</span> {
        <span class="hljs-keyword">throw</span> Exception(<span class="hljs-string">'Something went wrong'</span>);
      }
    } <span class="hljs-keyword">catch</span> (e) {
      <span class="hljs-comment">// Handle other errors</span>
      <span class="hljs-keyword">throw</span> Exception(<span class="hljs-string">'Failed to load tasks'</span>);
    }
  }
}
</code></pre>
<p><strong>Test the Interceptor</strong>:</p>
<p>Finally, we can test if the retry method works. So, I turned off Network on my device and ran the app and this is the output:</p>
<p><img src="https://i.postimg.cc/LhddgfBp/Screenshot-2024-12-03-at-3-38-11-PM.png" alt="No Network" /></p>
<p>Now, I just turned on the network again and here’s the output:</p>
<p><img src="https://i.postimg.cc/cC3xzdFd/Screenshot-2024-12-03-at-3-38-28-PM.png" alt="Network Retry" /></p>
<p>So, as you can see Dio keeps retrying until we get a successful response. You can find the source code above tutorial here: <a target="_blank" href="https://github.com/harish-kunchala/dio_tasker/tree/03-03-retry-interceptor">dio_tasker/03-03-retry-interceptor</a></p>
<h3 id="heading-tutorial-4-authentication-interceptor">Tutorial 4: Authentication Interceptor</h3>
<p>Since we have covered Content type access header in Tutorial 2, let’s go over authentication headers.</p>
<p><strong>Authentication Headers</strong>:</p>
<p>Authentication headers are HTTPS headers used to pass authentication information between the client and server. The most common authentication header is the <code>Authorization</code> header, which typically contains the token.</p>
<p>Example of an Authorization header:</p>
<pre><code class="lang-json">Authorization: Bearer YOUR_ACCESS_TOKEN
</code></pre>
<p>On that note let’s understand Token-Based Authentication</p>
<p><strong>What is Token-Based Authentication?</strong></p>
<p>Token-Based Authentication is a mechanism where client (such as a mobile app or web browser) authenticates with a server using a token. This token is usually string of characters representing the user’s credentials and permissions. Tokens are typically issued by the server upon successful login and must be included in the subsequent requests to access protected resources.</p>
<p><strong>How Token-Based Authentication Works</strong></p>
<ol>
<li><p><strong>Login</strong>: The client sends a login request with the user’s credentials (username and password) to the server.</p>
</li>
<li><p><strong>Token Issuance</strong>: If the credentials are valid, the server generates a token and sends it back to the client.</p>
</li>
<li><p><strong>Token Storage</strong>: The client stores the token (usually in local storage or secure storage).</p>
</li>
<li><p><strong>Authenticated Requests</strong>: For subsequent requests, the client includes the token in the request headers to authenticate the server.</p>
</li>
<li><p><strong>Token Validation</strong>: The server validates the token and grants access to the requested resource if the token is valid.</p>
</li>
<li><p><strong>Token Refresh</strong>: If the token expires, the client can request a new token using a refresh token.</p>
</li>
</ol>
<p>So, on this note let’s look at Authentication Interceptor.</p>
<h3 id="heading-tutorial-4-creating-an-authentication-interceptor">Tutorial 4: Creating an Authentication Interceptor:</h3>
<p><strong>Create an Authentication Interceptor:</strong></p>
<ul>
<li>Let’s create a new file <code>lib/interceptors/auth_interceptor.dart</code></li>
</ul>
<pre><code class="lang-dart"><span class="hljs-keyword">import</span> <span class="hljs-string">'package:dio/dio.dart'</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">AuthInterceptor</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Interceptor</span> </span>{
  <span class="hljs-keyword">final</span> Dio dio;

  AuthInterceptor(<span class="hljs-keyword">this</span>.dio);

  <span class="hljs-comment">/// <span class="markdown">onRequest: This method is called before a request is sent.</span></span>
  <span class="hljs-comment">/// <span class="markdown">We add the access token to the request headers.</span></span>
  <span class="hljs-meta">@override</span>
  <span class="hljs-keyword">void</span> onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    <span class="hljs-comment">// Add the access token to the headers.</span>
    options.headers[<span class="hljs-string">'Authorization'</span>] = <span class="hljs-string">'Bearer YOUR_ACCESS_TOKEN'</span>;
    <span class="hljs-keyword">super</span>.onRequest(options, handler);
  }

  <span class="hljs-comment">/// <span class="markdown">onError: This method is called when an error occurs.</span></span>
  <span class="hljs-comment">/// <span class="markdown">If the error status code is 401 (Unauthorized), we attempt to refresh the token and retry the request with the new token.</span></span>
  <span class="hljs-meta">@override</span>
  <span class="hljs-keyword">void</span> onError(DioException err, ErrorInterceptorHandler handler) <span class="hljs-keyword">async</span> {
    <span class="hljs-keyword">if</span> (err.response?.statusCode == <span class="hljs-number">401</span>) {
      <span class="hljs-comment">// Handle token refresh logic.</span>
      <span class="hljs-keyword">final</span> newToken = <span class="hljs-keyword">await</span> _refreshToken();
      <span class="hljs-keyword">if</span> (newToken != <span class="hljs-keyword">null</span>) {
        <span class="hljs-comment">// Retry the request with the new token</span>
        <span class="hljs-keyword">final</span> options = err.requestOptions;
        options.headers[<span class="hljs-string">'Authorization'</span>] = <span class="hljs-string">'Bearer <span class="hljs-subst">$newToken</span>'</span>;
        <span class="hljs-keyword">final</span> response = <span class="hljs-keyword">await</span> dio.request(
          options.path,
          options: Options(
            method: options.method,
            headers: options.headers,
          ),
        );
        <span class="hljs-keyword">return</span> handler.resolve(response);
      }
    }
    <span class="hljs-keyword">super</span>.onError(err, handler);
  }

  <span class="hljs-comment">/// <span class="markdown"><span class="hljs-emphasis">_refreshToken: This method should contain the logic to refresh the token.</span></span></span>
  <span class="hljs-comment">/// <span class="markdown"><span class="hljs-emphasis">In a real application, you would make a request to your authentication server to get a new token.</span></span></span>
  Future&lt;<span class="hljs-built_in">String?</span>&gt; _refreshToken() <span class="hljs-keyword">async</span> {
    <span class="hljs-keyword">return</span> <span class="hljs-string">'NEW_ACCESS_TOKEN'</span>;
  }
}
</code></pre>
<p><strong>Add the interceptor to Dio:</strong></p>
<pre><code class="lang-dart"><span class="hljs-keyword">import</span> <span class="hljs-string">'package:dio/dio.dart'</span>;
<span class="hljs-keyword">import</span> <span class="hljs-string">'package:dio_tasker/interceptors/auth_interceptor.dart'</span>;
<span class="hljs-keyword">import</span> <span class="hljs-string">'package:dio_tasker/interceptors/headers_interceptor.dart'</span>;
<span class="hljs-keyword">import</span> <span class="hljs-string">'package:dio_tasker/interceptors/logging_interceptor.dart'</span>;
<span class="hljs-keyword">import</span> <span class="hljs-string">'package:dio_tasker/interceptors/retry_interceptor.dart'</span>;

<span class="hljs-keyword">import</span> <span class="hljs-string">'../models/tasks.dart'</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ApiService</span> </span>{
  <span class="hljs-keyword">final</span> Dio _dio;

  ApiService() : _dio = Dio() {
    <span class="hljs-comment">// Add the logging interceptor</span>
    _dio.interceptors.add(LoggingInterceptor());

    <span class="hljs-comment">// Add the headers interceptor.</span>
    _dio.interceptors.add(HeadersInterceptor());

    <span class="hljs-comment">// Add the retry interceptor.</span>
    _dio.interceptors.add(RetryInterceptor(_dio));

    <span class="hljs-comment">// Add the authentication interceptor.</span>
    _dio.interceptors.add(AuthInterceptor(_dio));
  }

  <span class="hljs-comment">// Method to fetch tasks from the API</span>
  Future&lt;<span class="hljs-built_in">List</span>&lt;Task&gt;&gt; fetchTasks() <span class="hljs-keyword">async</span> {
    <span class="hljs-keyword">try</span> {
      <span class="hljs-comment">// Make a GET request to fetch tasks</span>
      <span class="hljs-keyword">final</span> response =
          <span class="hljs-keyword">await</span> _dio.<span class="hljs-keyword">get</span>(<span class="hljs-string">'https://jsonplaceholder.typicode.com/todos'</span>);
      <span class="hljs-comment">// Parse the response data into a list of Task objects</span>
      <span class="hljs-keyword">return</span> (response.data <span class="hljs-keyword">as</span> <span class="hljs-built_in">List</span>)
          .map((task) =&gt; Task.fromJSON(task))
          .toList();
    } <span class="hljs-keyword">on</span> DioException <span class="hljs-keyword">catch</span> (dioException) {
      <span class="hljs-comment">// Handle Dio Exceptions</span>
      <span class="hljs-keyword">if</span> (dioException.type == DioExceptionType.connectionTimeout) {
        <span class="hljs-keyword">throw</span> Exception(<span class="hljs-string">'Connection Timeout'</span>);
      } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (dioException.type == DioExceptionType.receiveTimeout) {
        <span class="hljs-keyword">throw</span> Exception(<span class="hljs-string">'Receive Timeout'</span>);
      } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (dioException.type == DioExceptionType.badResponse) {
        <span class="hljs-keyword">throw</span> Exception(
            <span class="hljs-string">'Received invalid status code: <span class="hljs-subst">${dioException.response?.statusCode}</span>'</span>);
      } <span class="hljs-keyword">else</span> {
        <span class="hljs-keyword">throw</span> Exception(<span class="hljs-string">'Something went wrong'</span>);
      }
    } <span class="hljs-keyword">catch</span> (e) {
      <span class="hljs-comment">// Handle other errors</span>
      <span class="hljs-keyword">throw</span> Exception(<span class="hljs-string">'Failed to load tasks'</span>);
    }
  }
}
</code></pre>
<p><strong>Test the Interceptor:</strong></p>
<p>Let’s check if the token is added to the request headers thanks to our <code>LogInterceptor</code>.</p>
<p><img src="https://i.postimg.cc/JhfRsy84/Screenshot-2024-12-04-at-10-33-53-AM.png" alt="auth token" /></p>
<p>Perfect, as we can see, the header includes <code>YOUR_ACCESS_TOKEN</code>.</p>
<p>You can find the source code for above tutorial here: <a target="_blank" href="https://github.com/harish-kunchala/dio_tasker/tree/03-04-auth-interceptor">dio_tasker/03-04-auth-interceptor</a></p>
<h3 id="heading-tutorial-5-custom-error-handling-interceptor">Tutorial 5: Custom Error Handling Interceptor</h3>
<p>Now, we’ll create an interceptor to handle custom error messages and show user-friendly messages.</p>
<p><strong>Create a Custom Error Handling Interceptor:</strong></p>
<ul>
<li>Create a new file <code>lib/interceptors/error_interceptor.dart</code></li>
</ul>
<pre><code class="lang-dart"><span class="hljs-keyword">import</span> <span class="hljs-string">'package:dio/dio.dart'</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ErrorInterceptor</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Interceptor</span> </span>{

  <span class="hljs-comment">/// <span class="markdown">onError: This method is called when an error occurs. </span></span>
  <span class="hljs-comment">/// <span class="markdown">We determine the type of error and set a user-friendly error message.</span></span>
  <span class="hljs-comment">/// <span class="markdown">The error message is then printed, and the error is passed to the next handler using super.onError.</span></span>
  <span class="hljs-meta">@override</span>
  <span class="hljs-keyword">void</span> onError(DioException err, ErrorInterceptorHandler handler) {
    <span class="hljs-built_in">String</span> errorMessage;
    <span class="hljs-keyword">if</span> (err.type == DioExceptionType.connectionTimeout) {
      errorMessage = <span class="hljs-string">'Connection Timeout'</span>;
    } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (err.type == DioExceptionType.receiveTimeout) {
      errorMessage = <span class="hljs-string">'Receive Timeout'</span>;
    } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (err.type == DioExceptionType.badResponse) {
      errorMessage =
          <span class="hljs-string">'Received invalid status code: <span class="hljs-subst">${err.response?.statusCode}</span>'</span>;
    } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (err.type == DioExceptionType.connectionError) {
      errorMessage = <span class="hljs-string">'Connection Error'</span>;
    } <span class="hljs-keyword">else</span> {
      errorMessage = <span class="hljs-string">'Something went wrong'</span>;
    }
    <span class="hljs-comment">// Show a user-friendly error message.</span>
    <span class="hljs-built_in">print</span>(<span class="hljs-string">'Error: <span class="hljs-subst">$errorMessage</span>'</span>);
    <span class="hljs-comment">// Pass the error to the next handler.</span>
    <span class="hljs-keyword">super</span>.onError(err, handler);
  }
}
</code></pre>
<p><strong>Add the Interceptor to Dio:</strong></p>
<pre><code class="lang-dart"><span class="hljs-keyword">import</span> <span class="hljs-string">'package:dio/dio.dart'</span>;
<span class="hljs-keyword">import</span> <span class="hljs-string">'package:dio_tasker/interceptors/auth_interceptor.dart'</span>;
<span class="hljs-keyword">import</span> <span class="hljs-string">'package:dio_tasker/interceptors/error_interceptor.dart'</span>;
<span class="hljs-keyword">import</span> <span class="hljs-string">'package:dio_tasker/interceptors/headers_interceptor.dart'</span>;
<span class="hljs-keyword">import</span> <span class="hljs-string">'package:dio_tasker/interceptors/logging_interceptor.dart'</span>;
<span class="hljs-keyword">import</span> <span class="hljs-string">'package:dio_tasker/interceptors/retry_interceptor.dart'</span>;

<span class="hljs-keyword">import</span> <span class="hljs-string">'../models/tasks.dart'</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ApiService</span> </span>{
  <span class="hljs-keyword">final</span> Dio _dio;

  ApiService() : _dio = Dio() {
    <span class="hljs-comment">// Add the headers interceptor</span>
    _dio.interceptors.add(HeadersInterceptor());

    <span class="hljs-comment">// Add the authentication interceptor</span>
    _dio.interceptors.add(AuthInterceptor(_dio));

    <span class="hljs-comment">// Add the error interceptor.</span>
    _dio.interceptors.add(ErrorInterceptor());

    <span class="hljs-comment">// Add the logging interceptor last</span>
    _dio.interceptors.add(LoggingInterceptor());
  }

  <span class="hljs-comment">// Method to fetch tasks from the API</span>
  Future&lt;<span class="hljs-built_in">List</span>&lt;Task&gt;&gt; fetchTasks() <span class="hljs-keyword">async</span> {
    <span class="hljs-keyword">try</span> {
      <span class="hljs-comment">// Make a GET request to fetch tasks</span>
      <span class="hljs-keyword">final</span> response =
          <span class="hljs-keyword">await</span> _dio.<span class="hljs-keyword">get</span>(<span class="hljs-string">'https://jsonplaceholder.typicode.com/todos'</span>);
      <span class="hljs-comment">// Parse the response data into a list of Task objects</span>
      <span class="hljs-keyword">return</span> (response.data <span class="hljs-keyword">as</span> <span class="hljs-built_in">List</span>)
          .map((task) =&gt; Task.fromJSON(task))
          .toList();
    } <span class="hljs-keyword">on</span> DioException <span class="hljs-keyword">catch</span> (dioException) {
      <span class="hljs-comment">// Handle Dio Exceptions</span>
      <span class="hljs-keyword">if</span> (dioException.type == DioExceptionType.connectionTimeout) {
        <span class="hljs-keyword">throw</span> Exception(<span class="hljs-string">'Connection Timeout'</span>);
      } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (dioException.type == DioExceptionType.receiveTimeout) {
        <span class="hljs-keyword">throw</span> Exception(<span class="hljs-string">'Receive Timeout'</span>);
      } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (dioException.type == DioExceptionType.badResponse) {
        <span class="hljs-keyword">throw</span> Exception(
            <span class="hljs-string">'Received invalid status code: <span class="hljs-subst">${dioException.response?.statusCode}</span>'</span>);
      } <span class="hljs-keyword">else</span> {
        <span class="hljs-keyword">throw</span> Exception(<span class="hljs-string">'Something went wrong'</span>);
      }
    } <span class="hljs-keyword">catch</span> (e) {
      <span class="hljs-comment">// Handle other errors</span>
      <span class="hljs-keyword">throw</span> Exception(<span class="hljs-string">'Failed to load tasks'</span>);
    }
  }
}
</code></pre>
<p><strong>Test the interceptor:</strong></p>
<p>Finally let’s test the interceptor to see if our app can handle the error messages:</p>
<p><img src="https://i.postimg.cc/fbmXY3WD/Screenshot-2024-12-04-at-10-57-31-AM.png" alt="custom-error-interceptor" /></p>
<p>When I turned off the network, we can see the <em>Error: Connection Error,</em> in our console.</p>
<p>You can find the source code for the above tutorial here: <a target="_blank" href="https://github.com/harish-kunchala/dio_tasker/tree/03-05-error-interceptor">dio_tasker/03-05-error-interceptor</a></p>
<h3 id="heading-conclusion">Conclusion:</h3>
<p>In this series of tutorials, we’ve gone through interceptors in Dio comprehensively. We are going to take a look at other parts of Dio in future articles. But until then have fun and happy coding 🐦</p>
]]></content:encoded></item><item><title><![CDATA[Flutter Dio Part 2: Handling Responses and Errors]]></title><description><![CDATA[In this part, we’ll enhance our Task Manager app by parsing JSON responses and handling different types of errors. We’ll use Dio’s built-in error handling…]]></description><link>https://harishkunchala.com/flutter-dio-part-2-handling-responses-and-errors</link><guid isPermaLink="true">https://harishkunchala.com/flutter-dio-part-2-handling-responses-and-errors</guid><category><![CDATA[Flutter]]></category><category><![CDATA[dio]]></category><dc:creator><![CDATA[Harish Kunchala]]></dc:creator><pubDate>Tue, 03 Dec 2024 18:00:38 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1733175926248/9737bc99-3d38-4799-97fe-93a7e646de1e.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In this part, we’ll enhance our Task Manager app by parsing JSON responses and handling different types of errors. We’ll use Dio’s built-in error handling mechanisms.</p>
<p>You can find the source code of the entire app here: <a target="_blank" href="https://github.com/harish-kunchala/dio_tasker">dio_tasker</a></p>
<h3 id="heading-parsing-json-responses">Parsing JSON Responses:</h3>
<p>We’ll update our <code>ApiService</code> to parse JSON response into a list of task objects.</p>
<ol>
<li><strong>Create a Task Model:</strong></li>
</ol>
<p>First, we’ll create a new file <code>lib/models/task.dart</code></p>
<pre><code class="lang-dart"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Task</span> </span>{
  <span class="hljs-keyword">final</span> <span class="hljs-built_in">int</span> id;
  <span class="hljs-keyword">final</span> <span class="hljs-built_in">String</span> title;
  <span class="hljs-keyword">final</span> <span class="hljs-built_in">bool</span> completed;

  Task({<span class="hljs-keyword">required</span> <span class="hljs-keyword">this</span>.id, <span class="hljs-keyword">required</span> <span class="hljs-keyword">this</span>.title, <span class="hljs-keyword">required</span> <span class="hljs-keyword">this</span>.completed});

  <span class="hljs-comment">// Factory method to create a Task from JSON</span>
  <span class="hljs-keyword">factory</span> Task.fromJSON(<span class="hljs-built_in">Map</span>&lt;<span class="hljs-built_in">String</span>, <span class="hljs-built_in">dynamic</span>&gt; json) =&gt; Task(
        id: json[<span class="hljs-string">'id'</span>],
        title: json[<span class="hljs-string">'title'</span>],
        completed: json[<span class="hljs-string">'completed'</span>],
      );
}
</code></pre>
<ol start="2">
<li><strong>Update</strong> <code>ApiService</code>:</li>
</ol>
<p>Now, let’s modify the <code>lib/services/api_service.dart</code> to use the Task model:</p>
<pre><code class="lang-dart"><span class="hljs-keyword">import</span> <span class="hljs-string">'package:dio/dio.dart'</span>;

<span class="hljs-keyword">import</span> <span class="hljs-string">'../models/tasks.dart'</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ApiService</span> </span>{
  <span class="hljs-comment">// Create an instance of Dio</span>
  <span class="hljs-keyword">final</span> _dio = Dio();

  <span class="hljs-comment">// Method to fetch tasks from the API</span>
  Future&lt;<span class="hljs-built_in">List</span>&lt;Task&gt;&gt; fetchTasks() <span class="hljs-keyword">async</span> {
    <span class="hljs-keyword">try</span> {
      <span class="hljs-comment">// Make a GET request to the API endpoint</span>
      <span class="hljs-keyword">final</span> response =
          <span class="hljs-keyword">await</span> _dio.<span class="hljs-keyword">get</span>(<span class="hljs-string">'https://jsonplaceholder.typicode.com/todos'</span>);
      <span class="hljs-comment">// Parse the response data into a list of Task objects</span>
      <span class="hljs-keyword">return</span> (response.data <span class="hljs-keyword">as</span> <span class="hljs-built_in">List</span>)
          .map((task) =&gt; Task.fromJSON(task))
          .toList();
    } <span class="hljs-keyword">catch</span> (e) {
      <span class="hljs-comment">// Handle errors</span>
      <span class="hljs-keyword">throw</span> Exception(<span class="hljs-string">'Failed to load tasks'</span>);
    }
  }
}
</code></pre>
<h3 id="heading-handling-different-types-of-errors">Handling Different Types of Errors:</h3>
<p>Now we’ll handle network errors, server errors and other types of errors.</p>
<ol>
<li><strong>Update</strong> <code>ApiService</code> <strong>to Handle Errors</strong>:</li>
</ol>
<p>Let’s modify <code>lib/services/api_service.dart</code> to handle different types of errors:</p>
<pre><code class="lang-dart"><span class="hljs-keyword">import</span> <span class="hljs-string">'package:dio/dio.dart'</span>;

<span class="hljs-keyword">import</span> <span class="hljs-string">'../models/tasks.dart'</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ApiService</span> </span>{
  <span class="hljs-comment">// Create an instance of Dio</span>
  <span class="hljs-keyword">final</span> _dio = Dio();

  <span class="hljs-comment">// Method to fetch tasks from the API</span>
  Future&lt;<span class="hljs-built_in">List</span>&lt;Task&gt;&gt; fetchTasks() <span class="hljs-keyword">async</span> {
    <span class="hljs-keyword">try</span> {
      <span class="hljs-comment">// Make a GET request to the API endpoint</span>
      <span class="hljs-keyword">final</span> response =
          <span class="hljs-keyword">await</span> _dio.<span class="hljs-keyword">get</span>(<span class="hljs-string">'https://jsonplaceholder.typicode.com/todos'</span>);
      <span class="hljs-comment">// Parse the response data into a list of Task objects</span>
      <span class="hljs-keyword">return</span> (response.data <span class="hljs-keyword">as</span> <span class="hljs-built_in">List</span>)
          .map((task) =&gt; Task.fromJSON(task))
          .toList();
    } <span class="hljs-keyword">on</span> DioException <span class="hljs-keyword">catch</span> (dioException) {
      <span class="hljs-comment">// Handle Dio Exceptions</span>
      <span class="hljs-keyword">if</span> (dioException.type == DioExceptionType.connectionTimeout) {
        <span class="hljs-keyword">throw</span> Exception(<span class="hljs-string">'Connection Timeout'</span>);
      } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (dioException.type == DioExceptionType.receiveTimeout) {
        <span class="hljs-keyword">throw</span> Exception(<span class="hljs-string">'Receive Timeout'</span>);
      } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (dioException.type == DioExceptionType.badResponse) {
        <span class="hljs-keyword">throw</span> Exception(
            <span class="hljs-string">'Received invalid status code: <span class="hljs-subst">${dioException.response?.statusCode}</span>'</span>);
      } <span class="hljs-keyword">else</span> {
        <span class="hljs-keyword">throw</span> Exception(<span class="hljs-string">'Something went wrong'</span>);
      }
    } <span class="hljs-keyword">catch</span> (e) {
      <span class="hljs-comment">// Handle other errors</span>
      <span class="hljs-keyword">throw</span> Exception(<span class="hljs-string">'Failed to load tasks'</span>);
    }
  }
}
</code></pre>
<h3 id="heading-update-ui-to-display-errors">Update UI to Display Errors:</h3>
<p>We’ll update the UI to display error messages when fetching tasks fails.</p>
<ol>
<li><strong>Modify TaskListScreen:</strong></li>
</ol>
<p>Let’s update <code>lib/main.dart</code> to display error messages:</p>
<pre><code class="lang-dart"><span class="hljs-keyword">import</span> <span class="hljs-string">'package:dio_tasker/services/api_service.dart'</span>;
<span class="hljs-keyword">import</span> <span class="hljs-string">'package:flutter/material.dart'</span>;

<span class="hljs-keyword">void</span> main() {
  runApp(<span class="hljs-keyword">const</span> MyApp());
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyApp</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">StatelessWidget</span> </span>{
  <span class="hljs-keyword">const</span> MyApp({<span class="hljs-keyword">super</span>.key});

  <span class="hljs-meta">@override</span>
  Widget build(BuildContext context) {
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">const</span> MaterialApp(
      home: TaskListScreen(),
    );
  }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">TaskListScreen</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">StatefulWidget</span> </span>{
  <span class="hljs-keyword">const</span> TaskListScreen({<span class="hljs-keyword">super</span>.key});

  <span class="hljs-meta">@override</span>
  State&lt;TaskListScreen&gt; createState() =&gt; _TaskListScreenState();
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">_TaskListScreenState</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">State</span>&lt;<span class="hljs-title">TaskListScreen</span>&gt; </span>{
  <span class="hljs-comment">// Create an instance of ApiService</span>
  <span class="hljs-keyword">final</span> ApiService _apiService = ApiService();

  <span class="hljs-comment">// List to hold the fetched tasks</span>
  <span class="hljs-built_in">List</span>&lt;<span class="hljs-built_in">dynamic</span>&gt; _tasks = [];

  <span class="hljs-comment">// Variable to hold error messages</span>
  <span class="hljs-built_in">String?</span> _errorMessage;

  <span class="hljs-meta">@override</span>
  <span class="hljs-keyword">void</span> initState() {
    <span class="hljs-keyword">super</span>.initState();
    <span class="hljs-comment">// Fetch tasks when the widget is initialized</span>
    _fetchTasks();
  }

  <span class="hljs-comment">// Method to fetch tasks and update the state</span>
  <span class="hljs-keyword">void</span> _fetchTasks() <span class="hljs-keyword">async</span> {
    <span class="hljs-keyword">try</span> {
      <span class="hljs-comment">// Fetch tasks from the API</span>
      <span class="hljs-keyword">final</span> tasks = <span class="hljs-keyword">await</span> _apiService.fetchTasks();
      <span class="hljs-comment">// Update the state with the fetched tasks</span>
      setState(() {
        _tasks = tasks;
      });
    } <span class="hljs-keyword">catch</span> (e) {
      <span class="hljs-comment">// Update the state with the error message</span>
      setState(() {
        _errorMessage = e.toString();
      });
    }
  }

  <span class="hljs-meta">@override</span>
  Widget build(BuildContext context) {
    <span class="hljs-keyword">return</span> Scaffold(
      appBar: AppBar(
        title: <span class="hljs-keyword">const</span> Text(<span class="hljs-string">'Task Manager'</span>),
      ),
      body: _errorMessage != <span class="hljs-keyword">null</span>
          ? Center(
              child: Text(_errorMessage!),
            )
          : ListView.builder(
              <span class="hljs-comment">// Set the number of items in the list</span>
              itemCount: _tasks.length,
              <span class="hljs-comment">// Build each item in the list</span>
              itemBuilder: (context, index) {
                <span class="hljs-keyword">return</span> ListTile(
                  <span class="hljs-comment">// Display the task title</span>
                  title: Text(_tasks[index].title),
                );
              },
            ),
    );
  }
}
</code></pre>
<h3 id="heading-output">Output:</h3>
<ol>
<li><strong>Without Any Errors</strong></li>
</ol>
<p>Allright so let’s run the app and see if we get any errors.</p>
<p><img src="https://i.postimg.cc/qRWLMcW1/Simulator-Screen-Recording-i-Phone-15-Pro-Max-2024-12-02-at-12-13-58.gif" alt="app without errors" /></p>
<ol start="2">
<li><strong>With an Error:</strong></li>
</ol>
<p>Now we’ll change the URL to an invalid URL and see if the app can handle that. So instead of using <a target="_blank" href="https://jsonplaceholder.typicode.com/todos">https://jsonplaceholder.typicode.com/todos</a> we’ll use <a target="_blank" href="https://jsonplaceholder.typicode.com/todos">https://jsonplaceholder.typicode.com/to</a>. Which is an invalid URL. And here’s the output:</p>
<p><img src="https://i.postimg.cc/hGYDvhsC/Simulator-Screenshot-i-Phone-15-Pro-Max-2024-12-02-at-13-40-36.png" alt="Error" /></p>
<p>Perfect. As we can see, our app is able to handle errors.</p>
<p>You can find the source code for the above example here: <a target="_blank" href="https://github.com/harish-kunchala/dio_tasker/tree/02-handling-response-errors">dio_tasker/02-handling-response-errors</a>.</p>
]]></content:encoded></item><item><title><![CDATA[Flutter Dio Part 1: Introduction to Dio]]></title><description><![CDATA[While building apps in Flutter is extremely fluid and wonderfully intuitive. We obviously know that we can’t build the next TikTok or Twitter by only…]]></description><link>https://harishkunchala.com/flutter-dio-part-1-introduction-to-dio</link><guid isPermaLink="true">https://harishkunchala.com/flutter-dio-part-1-introduction-to-dio</guid><category><![CDATA[Flutter]]></category><category><![CDATA[dio]]></category><dc:creator><![CDATA[Harish Kunchala]]></dc:creator><pubDate>Mon, 02 Dec 2024 20:39:55 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1733171956725/02fc8a45-0ca9-488c-908b-c10700673ffd.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>While building apps in Flutter is extremely fluid and wonderfully intuitive. We obviously know that we can’t build the next TikTok or Twitter by only building offline apps. Which is why we absolutely need internet capabilities in our Flutter apps.</p>
<p>There are several libraries that help us with our networking needs, but I think these two are the most popular in Flutter:</p>
<ul>
<li><p><a target="_blank" href="https://pub.dev/packages/http">http</a>: We can’t do any internet calls without adding the <code>http</code> package. This is good for basic networking needs.</p>
</li>
<li><p><a target="_blank" href="https://pub.dev/packages/dio">dio</a>: A powerful HTTP networking package for Dart/Flutter, supports Global configuration, Interceptors, FormData, Request cancellation, File uploading/downloading, Timeout, Custom adapters, Transformers, etc.</p>
</li>
</ul>
<p>So, in this <a target="_blank" href="https://harishkunchala.com/series/flutter-dio">series</a>, we’ll build a sample task management app that’ll go through every feature of dio in detail.</p>
<p>You can find all the code in the following repo: <a target="_blank" href="https://github.com/harish-kunchala/dio_tasker">dio_tasker</a></p>
<h3 id="heading-introduction-to-dio">Introduction to Dio:</h3>
<ol>
<li><strong>Create a New Flutter Project</strong>:</li>
</ol>
<p>First, we’ll create a new flutter project named <code>dio_tasker</code>. Let’s open our terminal and run the following commands:</p>
<pre><code class="lang-bash">flutter create dio_tasker --platform android,ios --org com.yourorg
</code></pre>
<ol start="2">
<li><strong>Add Dio to our Project:</strong></li>
</ol>
<p>Next, let’s add Dio to our project dependencies. Within terminal, navigate to our project directory and let’s run the following command:</p>
<pre><code class="lang-bash">flutter pub add dio
</code></pre>
<ol start="3">
<li><strong>Set Up Dio:</strong></li>
</ol>
<p>Now let’s set up Dio in our project. First create a new directory under our <code>lib/</code> named <code>services</code>. Create a file named <code>api_service.dart</code> under <code>lib/services</code> directory. This file will contain the code for making HTTP requests using Dio.</p>
<pre><code class="lang-dart"><span class="hljs-keyword">import</span> <span class="hljs-string">'package:dio/dio.dart'</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ApiService</span> </span>{
  <span class="hljs-comment">// Create an instance of Dio</span>
  <span class="hljs-keyword">final</span> _dio = Dio();

  <span class="hljs-comment">// Method to fetch tasks from the API</span>
  Future&lt;<span class="hljs-built_in">List</span>&lt;<span class="hljs-built_in">dynamic</span>&gt;&gt; fetchTasks() <span class="hljs-keyword">async</span> {
    <span class="hljs-comment">// Make a GET request to the API endpoint</span>
    <span class="hljs-keyword">final</span> response = <span class="hljs-keyword">await</span> _dio.<span class="hljs-keyword">get</span>(<span class="hljs-string">'https://jsonplaceholder.typicode.com/todos'</span>);
    <span class="hljs-comment">// Return the response data</span>
    <span class="hljs-keyword">return</span> response.data;
  }
}
</code></pre>
<ol start="4">
<li><strong>Fetch and Display Tasks:</strong></li>
</ol>
<p>Next, we’ll update the <code>main.dart</code> to fetch and display tasks using <code>ApiService</code> class. So, let’s replace the code in <code>lib/main.dart</code> with the following:</p>
<pre><code class="lang-dart"><span class="hljs-keyword">import</span> <span class="hljs-string">'package:dio_tasker/services/api_service.dart'</span>;
<span class="hljs-keyword">import</span> <span class="hljs-string">'package:flutter/material.dart'</span>;

<span class="hljs-keyword">void</span> main() {
  runApp(<span class="hljs-keyword">const</span> MyApp());
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyApp</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">StatelessWidget</span> </span>{
  <span class="hljs-keyword">const</span> MyApp({<span class="hljs-keyword">super</span>.key});

  <span class="hljs-meta">@override</span>
  Widget build(BuildContext context) {
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">const</span> MaterialApp(
      home: TaskListScreen(),
    );
  }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">TaskListScreen</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">StatefulWidget</span> </span>{
  <span class="hljs-keyword">const</span> TaskListScreen({<span class="hljs-keyword">super</span>.key});

  <span class="hljs-meta">@override</span>
  State&lt;TaskListScreen&gt; createState() =&gt; _TaskListScreenState();
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">_TaskListScreenState</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">State</span>&lt;<span class="hljs-title">TaskListScreen</span>&gt; </span>{
  <span class="hljs-comment">// Create an instance of ApiService</span>
  <span class="hljs-keyword">final</span> ApiService _apiService = ApiService();
  <span class="hljs-comment">// List to hold the fetched tasks</span>
  <span class="hljs-built_in">List</span>&lt;<span class="hljs-built_in">dynamic</span>&gt; _tasks = [];

  <span class="hljs-meta">@override</span>
  <span class="hljs-keyword">void</span> initState() {
    <span class="hljs-keyword">super</span>.initState();
    <span class="hljs-comment">// Fetch tasks when the widget is initialized</span>
    _fetchTasks();
  }

  <span class="hljs-comment">// Method to fetch tasks and update the state</span>
  <span class="hljs-keyword">void</span> _fetchTasks() <span class="hljs-keyword">async</span> {
    <span class="hljs-comment">// Fetch tasks from the API</span>
    <span class="hljs-keyword">final</span> tasks = <span class="hljs-keyword">await</span> _apiService.fetchTasks();
    <span class="hljs-comment">// Update the state with the fetched tasks</span>
    setState(() {
      _tasks = tasks;
    });
  }

  <span class="hljs-meta">@override</span>
  Widget build(BuildContext context) {
    <span class="hljs-keyword">return</span> Scaffold(
      appBar: AppBar(
        title: <span class="hljs-keyword">const</span> Text(<span class="hljs-string">'Task Manager'</span>),
      ),
      body: ListView.builder(
        <span class="hljs-comment">// Set the number of items in the list</span>
        itemCount: _tasks.length,
        <span class="hljs-comment">// Build each item in the list</span>
        itemBuilder: (context, index) {
          <span class="hljs-keyword">return</span> ListTile(
            <span class="hljs-comment">// Display the task title</span>
            title: Text(_tasks[index][<span class="hljs-string">'title'</span>]),
          );
        },
      ),
    );
  }
}
</code></pre>
<h3 id="heading-output">Output:</h3>
<p>Now that we’ve added <code>ApiService</code> and also setup <code>_fetchTasks()</code> in <code>main.dart</code> to get the list of mock tasks. Let’s look out the output.</p>
<p><img src="https://i.postimg.cc/qRWLMcW1/Simulator-Screen-Recording-i-Phone-15-Pro-Max-2024-12-02-at-12-13-58.gif" alt="dio-01-Introduction-gif" /></p>
<p>You can find the source code for the above code here: <a target="_blank" href="https://github.com/harish-kunchala/dio_tasker/tree/01-introduction">dio_tasker/01-introduction</a>.</p>
<p>In the upcoming articles. We’ll go through additional features of dio. Happy Coding 🐦.</p>
]]></content:encoded></item><item><title><![CDATA[Mastering setState in Flutter: When to Use It and When to Avoid It]]></title><description><![CDATA[Understanding when to use setState in Flutter is crucial for managing our app’s state effectively. Here’s a detailed guide: Performance Considerations: Be…]]></description><link>https://harishkunchala.com/mastering-setstate-in-flutter-when-to-use-it-and-when-to-avoid-it</link><guid isPermaLink="true">https://harishkunchala.com/mastering-setstate-in-flutter-when-to-use-it-and-when-to-avoid-it</guid><category><![CDATA[Flutter]]></category><category><![CDATA[setState]]></category><category><![CDATA[State Management ]]></category><category><![CDATA[widget lifecycle]]></category><dc:creator><![CDATA[Harish Kunchala]]></dc:creator><pubDate>Tue, 19 Nov 2024 22:02:55 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1732053724040/6668c5ef-a9d6-4710-b311-71ed5b35e381.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Understanding when to use <code>setState</code> in Flutter is crucial for managing our app’s state effectively. Here’s a detailed guide:</p>
<h3 id="heading-when-to-use-setstate">When to use <code>setState</code> ?</h3>
<ol>
<li><strong>Updating the UI</strong>: Use <code>setState</code> <em><mark>when we need to update the UI in response to changes in the internal state of a</mark></em> <code>StatefulWidget</code>. For example, if we have a counter that increments when a button is pressed, we will use <code>setState</code> to update the counter and refresh the UI.</li>
</ol>
<pre><code class="lang-dart"><span class="hljs-keyword">void</span> _incrementCounter() {
    setState(() {
            _counter++;
        });
}
</code></pre>
<ol start="2">
<li><strong>User Interactions</strong>: It’s common to use <code>setState</code> in response to user interactions, such as button presses, form submissions, or other input events.</li>
</ol>
<pre><code class="lang-dart">onPressed: () {
    setState(() {
            _isButtonPressed=<span class="hljs-keyword">true</span>;
        });
}
</code></pre>
<ol start="3">
<li><strong>State Changes:</strong> When the state of our widget changes and we need the UI to reflect these changes, <code>setState</code> is necessary. This includes changes in variables that are used in the build method.</li>
</ol>
<pre><code class="lang-dart"><span class="hljs-keyword">void</span> _toggleVisibility() {
  setState(() {
    _isVisible = !_isVisible;
  });
}
</code></pre>
<h3 id="heading-when-not-to-use-setstate">When not to use <code>setState</code> ?</h3>
<ol>
<li><strong>Initialization</strong>: Do not use <code>setState</code> in the <code>initState</code> method. The <code>initState</code> method is called only once when the widget is inserted into widget tree, and the state is already considered dirty at this point.</li>
</ol>
<pre><code class="lang-dart"><span class="hljs-meta">@override</span>
<span class="hljs-keyword">void</span> initState() {
  <span class="hljs-keyword">super</span>.initState();
  <span class="hljs-comment">// No need for setState here</span>
  _initializeData();
}
</code></pre>
<ol start="2">
<li><strong>Asynchronous Operations:</strong> Avoid using <code>setState</code> directly in asynchronous operations. Instead, complete the async operation first and then call <code>setState</code> to update the state.</li>
</ol>
<pre><code class="lang-dart"><span class="hljs-keyword">void</span> _fetchData() <span class="hljs-keyword">async</span> {
  <span class="hljs-keyword">final</span> data = <span class="hljs-keyword">await</span> fetchDataFromApi();
  setState(() {
    _data = data;
  });
}
</code></pre>
<ol start="3">
<li><p><strong>Performance Considerations:</strong> Be mindful of performance. Avoid calling <code>setState</code> in tight loops or frequently within a short period, as it can lead to performance issues. Only call <code>setState</code> when necessary to update the UI.</p>
</li>
<li><p><strong>Disposed Widgets</strong>: Never call <code>setState</code> after the widget has been disposed. This can lead to errors and unexpected behavior. Always check if the widget is still mounted before calling <code>setState</code>.</p>
</li>
</ol>
<pre><code class="lang-dart"><span class="hljs-keyword">if</span> (mounted) {
  setState(() {
    _data = newData;
  });
}
</code></pre>
<h3 id="heading-best-practices">Best Practices:</h3>
<ul>
<li><strong>Minimal Updates</strong>: Only wrap the state changes that require a UI update within <code>setState</code>. Avoid wrapping computational logic or asynchronous calls inside <code>setState</code>.</li>
</ul>
<pre><code class="lang-dart"><span class="hljs-keyword">void</span> _updateCounter() {
  _counter++;
  setState(() {}); <span class="hljs-comment">// Only the state change is wrapped</span>
}
</code></pre>
<ul>
<li><strong>State Management</strong>: For complex state management, consider using state management solutions like Provider, Riverpod or Bloc instead of relying solely on <code>setState</code>.</li>
</ul>
<p>By following the above guidelines, we can ensure that our Flutter app remains efficient and responsive. Happy Coding 🐦.</p>
]]></content:encoded></item><item><title><![CDATA[Understanding final in Java]]></title><description><![CDATA[Compile-time initialization: This is resolved at compile-time and the value is embedded directly in the bytecode. These are also resolved at compile-time…]]></description><link>https://harishkunchala.com/understanding-final-in-java</link><guid isPermaLink="true">https://harishkunchala.com/understanding-final-in-java</guid><category><![CDATA[Java]]></category><dc:creator><![CDATA[Harish Kunchala]]></dc:creator><pubDate>Sat, 27 Jul 2024 18:47:38 GMT</pubDate><content:encoded><![CDATA[<p>Compile-time initialization:</p>
<ol>
<li>Final variables initialized at declaration:</li>
</ol>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Example</span> </span>{
    <span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> COMPILE_TIME_CONSTANT = <span class="hljs-number">10</span>;
}
</code></pre>
<p>This is resolved at compile-time and the value is embedded directly in the bytecode.</p>
<ol start="2">
<li>Static final variables with constant expressions:</li>
</ol>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Example</span> </span>{
    <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> DAYS_IN_WEEK = <span class="hljs-number">7</span>;
    <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> String PREFIX = <span class="hljs-string">"user_"</span>;
}
</code></pre>
<p>These are also resolved at compile-time and treated as compile-time constants.</p>
<p>Runtime initialization:</p>
<ol>
<li>Final instance variables in constructors:</li>
</ol>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Example</span> </span>{
    <span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> runtimeValue;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Example</span><span class="hljs-params">(<span class="hljs-keyword">int</span> value)</span> </span>{
        <span class="hljs-keyword">this</span>.runtimeValue = value;
    }
}
</code></pre>
<p>The value is set when an object is created, allowing different instances to have different values.</p>
<ol start="2">
<li>Final variables in instance initializer blocks:</li>
</ol>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Example</span> </span>{
    <span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> runtimeValue;

    {
        runtimeValue = someMethod();
    }

    <span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">int</span> <span class="hljs-title">someMethod</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-number">42</span>;
    }
}
</code></pre>
<p>This allows for more complex initialization logic at runtime.</p>
<ol start="3">
<li>Static final variables with non-constant expressions:</li>
</ol>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Example</span> </span>{
    <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> RANDOM_NUMBER = <span class="hljs-keyword">new</span> Random().nextInt(<span class="hljs-number">100</span>);
}
</code></pre>
<p>This is initialized when the class is loaded, but the value is determined at runtime.</p>
<p>Remember, once a final variable is initialized, whether at compile-time or runtime, its value cannot be changed. The key difference is that runtime initialization allows for more flexibility in determining the initial value, while compile-time constants are fixed and known at compile-time.</p>
<p>Good luck and happy coding 🐦</p>
]]></content:encoded></item><item><title><![CDATA[Understanding the Plugin template in Flutter]]></title><description><![CDATA[A package is a set of programs files that provides us with a specific functionality. Say like a International Time Converter, Useful Extensions Provider or…]]></description><link>https://harishkunchala.com/understanding-the-plugin-template-in-flutter</link><guid isPermaLink="true">https://harishkunchala.com/understanding-the-plugin-template-in-flutter</guid><category><![CDATA[Flutter]]></category><category><![CDATA[plugins]]></category><dc:creator><![CDATA[Harish Kunchala]]></dc:creator><pubDate>Fri, 26 Jul 2024 21:01:11 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1722027644180/4627c821-7acd-48a9-be6b-ffded9710a6f.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-what-is-a-package">What is a Package?</h2>
<p>A package is a set of programs files that provides us with a specific functionality. Say like a International Time Converter, Useful Extensions Provider or may be a custom UI with some complex animations.</p>
<p>There are two types of packages in Flutter:</p>
<p><strong>Dart packages:</strong></p>
<ul>
<li><p>These are written in pure dart and have no platform dependency so they basically can be used anywhere Flutter runs.</p>
</li>
<li><p>In fact there are even Dart packages with no dependency on Flutter Framework, these can run in any environment: web, desktop , server and so on.</p>
</li>
<li><p>Eg: intl, custom_search_bar, http</p>
</li>
</ul>
<p><strong>Plugin Packages:</strong></p>
<ul>
<li><p>These are a combination of Dart and Platform specific code.</p>
</li>
<li><p>These packages commonly known as plugins, contain platform-native implementation code.</p>
</li>
<li><p>They are generally used to access platform features such as native camera, native file system or a platform specific feature like Health Data from iOS or Google pedometer data from Google Fit.</p>
</li>
<li><p>Eg: image_picker, camera_x</p>
</li>
</ul>
<p>From here on out we'll call them by their common names:</p>
<ul>
<li><p>Dart/Flutter Package is Package</p>
</li>
<li><p>Plugin Package is Plugin</p>
</li>
</ul>
<h3 id="heading-create-a-package">Create a Package:</h3>
<p>When we want to create a package in Flutter, we will use the Flutter <code>create</code> command and set the <code>template</code> as package.</p>
<p>So here's an example code</p>
<pre><code class="lang-bash">flutter create --template=package sample_package
</code></pre>
<h4 id="heading-file-structure">File Structure:</h4>
<p>Let's take a look at the file structure of the package:</p>
<pre><code class="lang-bash">.
├── CHANGELOG.md
├── LICENSE
├── README.md
├── analysis_options.yaml
├── lib
│   └── sample_package.dart
├── pubspec.lock
├── pubspec.yaml
├── sample_package.iml
└── <span class="hljs-built_in">test</span>
    └── sample_package_test.dart

3 directories, 9 files
</code></pre>
<p><mark>As we see there are no android or iOS folders</mark>. Because as I said a package is a pure dart implementation with no native code necessary.</p>
<p>Note: If you want to create a dart package with no flutter dependency use: dart create --template=package package_name</p>
<h2 id="heading-creating-a-plugin">Creating a Plugin</h2>
<p>Now if we want to create a Plugin with platforms as android and iOS. We'll use the following command:</p>
<pre><code class="lang-bash">flutter create --template=plugin --platforms=android,ios sample_plugin
</code></pre>
<h4 id="heading-file-structure-of-a-plugin">File Structure of a Plugin:</h4>
<p>Not only does it come with the usual <code>lib</code>, <code>android</code>, and <code>ios</code> folders:</p>
<p><img src="https://i.postimg.cc/pdScVZr4/Screenshot-2024-07-25-at-3-57-42-PM.png" alt /></p>
<p>But it also comes with an example folder, where we'll write the example code on how to integrate the plugin.</p>
<p>Also we generally interact with native code using Method Channels. How to use Method Channels: <a target="_blank" href="https://harishkunchala.com/how-to-use-platform-channels-in-flutter">Using Platform Channels Article</a></p>
<h4 id="heading-pubspecyaml-of-a-plugin"><code>Pubspec.yaml</code> of a Plugin.</h4>
<p>Now let's take a look at the <code>pubspec.yaml</code> of the plugin.</p>
<pre><code class="lang-yaml"><span class="hljs-attr">name:</span> <span class="hljs-string">sample_plugin</span>
<span class="hljs-attr">description:</span> <span class="hljs-string">"A new Flutter plugin project."</span>
<span class="hljs-attr">version:</span> <span class="hljs-number">0.0</span><span class="hljs-number">.1</span>
<span class="hljs-attr">homepage:</span>

<span class="hljs-attr">environment:</span>
  <span class="hljs-attr">sdk:</span> <span class="hljs-string">'&gt;=3.4.4 &lt;4.0.0'</span>
  <span class="hljs-attr">flutter:</span> <span class="hljs-string">'&gt;=3.3.0'</span>

<span class="hljs-attr">dependencies:</span>
  <span class="hljs-attr">flutter:</span>
    <span class="hljs-attr">sdk:</span> <span class="hljs-string">flutter</span>
  <span class="hljs-attr">plugin_platform_interface:</span> <span class="hljs-string">^2.0.2</span>

<span class="hljs-attr">dev_dependencies:</span>
  <span class="hljs-attr">flutter_test:</span>
    <span class="hljs-attr">sdk:</span> <span class="hljs-string">flutter</span>
  <span class="hljs-attr">flutter_lints:</span> <span class="hljs-string">^3.0.0</span>

<span class="hljs-attr">flutter:</span>
  <span class="hljs-attr">plugin:</span>
    <span class="hljs-attr">platforms:</span>
      <span class="hljs-attr">android:</span>
        <span class="hljs-attr">package:</span> <span class="hljs-string">com.example.sample_plugin</span>
        <span class="hljs-attr">pluginClass:</span> <span class="hljs-string">SamplePlugin</span>
      <span class="hljs-attr">ios:</span>
        <span class="hljs-attr">pluginClass:</span> <span class="hljs-string">SamplePlugin</span>
</code></pre>
<p>So as we can see the plugin classes are defined on both Android and iOS and we are going to use them for contacting via method channels.</p>
<h1 id="heading-what-is-a-method-channel">What is a Method Channel?</h1>
<p>For a detailed explanation see: <a target="_blank" href="https://harishkunchala.com/how-to-use-platform-channels-in-flutter">How to use Platform Channels in Flutter</a></p>
<p>Method channels allows us to communicate between Flutter and Native Platforms through method invocation on the platform side. We use:</p>
<ul>
<li><p><code>MethodChannel</code> on Android</p>
</li>
<li><p><code>FlutterMethodChannel</code> on iOS for receiving method calls and sending a result back.</p>
</li>
</ul>
<p>So basically the platform (Host) listens on the platform channel, and receives a message. It can use it's platform APIs to make the implementation of the logic and send back a response to the Flutter App (Client).</p>
<h2 id="heading-implementing-the-android-plugin">Implementing the Android Plugin:</h2>
<p>We get a default code from Android with an example on MethodChannel to get the build version. Let's see the code:</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">package</span> com.example.sample_plugin

<span class="hljs-keyword">import</span> androidx.<span class="hljs-keyword">annotation</span>.NonNull

<span class="hljs-keyword">import</span> io.flutter.embedding.engine.plugins.FlutterPlugin
<span class="hljs-keyword">import</span> io.flutter.plugin.common.MethodCall
<span class="hljs-keyword">import</span> io.flutter.plugin.common.MethodChannel
<span class="hljs-keyword">import</span> io.flutter.plugin.common.MethodChannel.MethodCallHandler
<span class="hljs-keyword">import</span> io.flutter.plugin.common.MethodChannel.Result

<span class="hljs-comment">/** SamplePlugin */</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">SamplePlugin</span>: <span class="hljs-type">FlutterPlugin</span>, <span class="hljs-type">MethodCallHandler {</span></span>
  <span class="hljs-comment">/// The MethodChannel that will the communication between Flutter and native Android</span>
  <span class="hljs-comment">///</span>
  <span class="hljs-comment">/// This local reference serves to register the plugin with the Flutter Engine and unregister it</span>
  <span class="hljs-comment">/// when the Flutter Engine is detached from the Activity</span>
  <span class="hljs-keyword">private</span> <span class="hljs-keyword">lateinit</span> <span class="hljs-keyword">var</span> channel : MethodChannel

  <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">onAttachedToEngine</span><span class="hljs-params">(flutterPluginBinding: <span class="hljs-type">FlutterPlugin</span>.<span class="hljs-type">FlutterPluginBinding</span>)</span></span> {
    channel = MethodChannel(flutterPluginBinding.binaryMessenger, <span class="hljs-string">"sample_plugin"</span>)
    channel.setMethodCallHandler(<span class="hljs-keyword">this</span>)
  }

  <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">onMethodCall</span><span class="hljs-params">(call: <span class="hljs-type">MethodCall</span>, result: <span class="hljs-type">Result</span>)</span></span> {
    <span class="hljs-keyword">if</span> (call.method == <span class="hljs-string">"getPlatformVersion"</span>) {
      result.success(<span class="hljs-string">"Android <span class="hljs-subst">${android.os.Build.VERSION.RELEASE}</span>"</span>)
    } <span class="hljs-keyword">else</span> {
      result.notImplemented()
    }
  }

  <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">onDetachedFromEngine</span><span class="hljs-params">(binding: <span class="hljs-type">FlutterPlugin</span>.<span class="hljs-type">FlutterPluginBinding</span>)</span></span> {
    channel.setMethodCallHandler(<span class="hljs-literal">null</span>)
  }
}
</code></pre>
<h2 id="heading-code-explanation">Code Explanation:</h2>
<h3 id="heading-package-declaration-and-imports">Package Declaration and Imports</h3>
<pre><code class="lang-kotlin"><span class="hljs-keyword">package</span> com.example.sample_plugin

<span class="hljs-keyword">import</span> androidx.<span class="hljs-keyword">annotation</span>.NonNull

<span class="hljs-keyword">import</span> io.flutter.embedding.engine.plugins.FlutterPlugin
<span class="hljs-keyword">import</span> io.flutter.plugin.common.MethodCall
<span class="hljs-keyword">import</span> io.flutter.plugin.common.MethodChannel
<span class="hljs-keyword">import</span> io.flutter.plugin.common.MethodChannel.MethodCallHandler
<span class="hljs-keyword">import</span> io.flutter.plugin.common.MethodChannel.Result
</code></pre>
<ul>
<li><p><strong>Package Declaration</strong>: The code is part of the <code>com.example.sample_plugin</code> package.</p>
</li>
<li><p><strong>Imports</strong>: The code imports necessary classes from the Android and Flutter libraries to create a Flutter plugin.</p>
</li>
</ul>
<h3 id="heading-class-declaration">Class Declaration</h3>
<pre><code class="lang-kotlin"><span class="hljs-comment">/** SamplePlugin */</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">SamplePlugin</span>: <span class="hljs-type">FlutterPlugin</span>, <span class="hljs-type">MethodCallHandler {</span></span>
</code></pre>
<ul>
<li><strong>Class Declaration</strong>: The <code>SamplePlugin</code> class implements two interfaces: <code>FlutterPlugin</code> and <code>MethodCallHandler</code>.</li>
</ul>
<h3 id="heading-properties">Properties</h3>
<pre><code class="lang-kotlin"><span class="hljs-keyword">private</span> <span class="hljs-keyword">lateinit</span> <span class="hljs-keyword">var</span> channel : MethodChannel
</code></pre>
<ul>
<li><code>channel</code>: This is a <code>MethodChannel</code> object that will handle communication between Flutter and the native Android code. It is declared as a <code>lateinit var</code>, meaning it will be initialized later.</li>
</ul>
<h3 id="heading-onattachedtoengine-method">onAttachedToEngine Method</h3>
<pre><code class="lang-kotlin"><span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">onAttachedToEngine</span><span class="hljs-params">(flutterPluginBinding: <span class="hljs-type">FlutterPlugin</span>.<span class="hljs-type">FlutterPluginBinding</span>)</span></span> {
  channel = MethodChannel(flutterPluginBinding.binaryMessenger, <span class="hljs-string">"sample_plugin"</span>)
  channel.setMethodCallHandler(<span class="hljs-keyword">this</span>)
}
</code></pre>
<ul>
<li><p><code>onAttachedToEngine</code>: This method is called when the plugin is attached to the Flutter engine.</p>
<ul>
<li><p><code>flutterPluginBinding.binaryMessenger</code>: This is used to create a <code>MethodChannel</code> with the name <code>"sample_plugin"</code>.</p>
</li>
<li><p><code>channel.setMethodCallHandler(this)</code>: Sets the current instance (<code>this</code>) as the handler for method calls coming through the channel.</p>
</li>
</ul>
</li>
</ul>
<h3 id="heading-onmethodcall-method">onMethodCall Method</h3>
<pre><code class="lang-kotlin"><span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">onMethodCall</span><span class="hljs-params">(call: <span class="hljs-type">MethodCall</span>, result: <span class="hljs-type">Result</span>)</span></span> {
  <span class="hljs-keyword">if</span> (call.method == <span class="hljs-string">"getPlatformVersion"</span>) {
    result.success(<span class="hljs-string">"Android <span class="hljs-subst">${android.os.Build.VERSION.RELEASE}</span>"</span>)
  } <span class="hljs-keyword">else</span> {
    result.notImplemented()
  }
}
</code></pre>
<ul>
<li><p><code>onMethodCall</code>: This method handles incoming method calls from Flutter.</p>
<ul>
<li><p><code>call.method</code>: Checks the method name of the incoming call.</p>
</li>
<li><p><code>getPlatformVersion</code>: If the method name is <code>"getPlatformVersion"</code>, it returns the Android version of the device.</p>
</li>
<li><p><code>result.success</code>: Sends the result back to Flutter.</p>
</li>
<li><p><code>result.notImplemented</code>: If the method is not recognized, it returns a "not implemented" response.</p>
</li>
</ul>
</li>
</ul>
<h3 id="heading-ondetachedfromengine-method">onDetachedFromEngine Method</h3>
<pre><code class="lang-kotlin"><span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">onDetachedFromEngine</span><span class="hljs-params">(binding: <span class="hljs-type">FlutterPlugin</span>.<span class="hljs-type">FlutterPluginBinding</span>)</span></span> {
  channel.setMethodCallHandler(<span class="hljs-literal">null</span>)
}
</code></pre>
<ul>
<li><p><code>onDetachedFromEngine</code>: This method is called when the plugin is detached from the Flutter engine.</p>
<ul>
<li><code>channel.setMethodCallHandler(null)</code>: Unregisters the method call handler by setting it to <code>null</code>.</li>
</ul>
</li>
</ul>
<h3 id="heading-summary">Summary</h3>
<ul>
<li><p>The <code>SamplePlugin</code> class is a Flutter plugin for Android.</p>
</li>
<li><p>It sets up a <code>MethodChannel</code> for communication between Flutter and native Android code.</p>
</li>
<li><p>It handles a specific method call (<code>getPlatformVersion</code>) to return the Android version.</p>
</li>
<li><p>It properly manages the lifecycle of the plugin by attaching and detaching from the Flutter engine.</p>
</li>
</ul>
<p>This code essentially enables Flutter to call native Android functions and get responses back, which is useful for our platform-specific functionality.</p>
<h2 id="heading-implementing-the-ios-plugin">Implementing the iOS Plugin:</h2>
<p>Now let's take a look at the default code provided by iOS. So here's the default code provided in <code>SamplePlugin.swift</code></p>
<pre><code class="lang-swift"><span class="hljs-keyword">import</span> Flutter
<span class="hljs-keyword">import</span> UIKit

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">SamplePlugin</span>: <span class="hljs-title">NSObject</span>, <span class="hljs-title">FlutterPlugin</span> </span>{
  <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">register</span><span class="hljs-params">(with registrar: FlutterPluginRegistrar)</span></span> {
    <span class="hljs-keyword">let</span> channel = <span class="hljs-type">FlutterMethodChannel</span>(name: <span class="hljs-string">"sample_plugin"</span>, binaryMessenger: registrar.messenger())
    <span class="hljs-keyword">let</span> instance = <span class="hljs-type">SamplePlugin</span>()
    registrar.addMethodCallDelegate(instance, channel: channel)
  }

  <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">handle</span><span class="hljs-params">(<span class="hljs-number">_</span> call: FlutterMethodCall, result: @escaping FlutterResult)</span></span> {
    <span class="hljs-keyword">switch</span> call.method {
    <span class="hljs-keyword">case</span> <span class="hljs-string">"getPlatformVersion"</span>:
      result(<span class="hljs-string">"iOS "</span> + <span class="hljs-type">UIDevice</span>.current.systemVersion)
    <span class="hljs-keyword">default</span>:
      result(<span class="hljs-type">FlutterMethodNotImplemented</span>)
    }
  }
}
</code></pre>
<h2 id="heading-code-explanation-1">Code Explanation:</h2>
<h3 id="heading-imports">Imports</h3>
<pre><code class="lang-swift"><span class="hljs-keyword">import</span> Flutter
<span class="hljs-keyword">import</span> UIKit
</code></pre>
<ul>
<li><p><code>import Flutter</code>: Imports the Flutter framework for iOS.</p>
</li>
<li><p><code>import UIKit</code>: Imports the UIKit framework, which provides the necessary infrastructure for constructing and managing iOS apps.</p>
</li>
</ul>
<h3 id="heading-class-declaration-1">Class Declaration</h3>
<pre><code class="lang-swift"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">SamplePlugin</span>: <span class="hljs-title">NSObject</span>, <span class="hljs-title">FlutterPlugin</span> </span>{
</code></pre>
<ul>
<li><strong>Class Declaration</strong>: The <code>SamplePlugin</code> class inherits from <code>NSObject</code> and conforms to the <code>FlutterPlugin</code> protocol. This means it can act as a Flutter plugin.</li>
</ul>
<h3 id="heading-register-method">register Method</h3>
<pre><code class="lang-swift"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">register</span><span class="hljs-params">(with registrar: FlutterPluginRegistrar)</span></span> {
  <span class="hljs-keyword">let</span> channel = <span class="hljs-type">FlutterMethodChannel</span>(name: <span class="hljs-string">"sample_plugin"</span>, binaryMessenger: registrar.messenger())
  <span class="hljs-keyword">let</span> instance = <span class="hljs-type">SamplePlugin</span>()
  registrar.addMethodCallDelegate(instance, channel: channel)
}
</code></pre>
<ul>
<li><p><code>register</code> Method: This static method is called when the plugin is registered with the Flutter engine.</p>
<ul>
<li><p><code>FlutterMethodChannel</code>: Creates a method channel named <code>"sample_plugin"</code> for communication between Flutter and native iOS code.</p>
</li>
<li><p><code>registrar.messenger()</code>: Provides the binary messenger for the channel.</p>
</li>
<li><p><code>SamplePlugin()</code>: Creates an instance of the <code>SamplePlugin</code> class.</p>
</li>
<li><p><code>registrar.addMethodCallDelegate</code>: Registers the instance as a method call delegate for the channel. This means that the instance will handle method calls coming through the channel.</p>
</li>
</ul>
</li>
</ul>
<h3 id="heading-handle-method">handle Method</h3>
<pre><code class="lang-swift"><span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">handle</span><span class="hljs-params">(<span class="hljs-number">_</span> call: FlutterMethodCall, result: @escaping FlutterResult)</span></span> {
  <span class="hljs-keyword">switch</span> call.method {
  <span class="hljs-keyword">case</span> <span class="hljs-string">"getPlatformVersion"</span>:
    result(<span class="hljs-string">"iOS "</span> + <span class="hljs-type">UIDevice</span>.current.systemVersion)
  <span class="hljs-keyword">default</span>:
    result(<span class="hljs-type">FlutterMethodNotImplemented</span>)
  }
}
</code></pre>
<ul>
<li><p><code>handle</code> Method: This method handles incoming method calls from Flutter.</p>
<ul>
<li><p><code>call.method</code>: Checks the method name of the incoming call.</p>
</li>
<li><p><code>getPlatformVersion</code>: If the method name is <code>"getPlatformVersion"</code>, it returns the iOS version of the device.</p>
</li>
<li><p><code>result("iOS " + UIDevice.current.systemVersion)</code>: Sends the result back to Flutter with the iOS version.</p>
</li>
<li><p><code>result(FlutterMethodNotImplemented)</code>: If the method is not recognized, it returns a "not implemented" response.</p>
</li>
</ul>
</li>
</ul>
<h3 id="heading-summary-1">Summary</h3>
<ul>
<li><p>The <code>SamplePlugin</code> class is a Flutter plugin for iOS.</p>
</li>
<li><p>It sets up a <code>FlutterMethodChannel</code> for communication between Flutter and native iOS code.</p>
</li>
<li><p>It handles a specific method call (<code>getPlatformVersion</code>) to return the iOS version.</p>
</li>
<li><p>It properly registers itself with the Flutter engine and handles method calls through the <code>handle</code> method.</p>
</li>
</ul>
<p>This code enables Flutter to call native iOS functions and get responses back, which is useful for our platform-specific functionality.</p>
<h2 id="heading-the-dart-api">The Dart API:</h2>
<p>Now let's look at the associated dart code provided to us in <code>lib/sample_plugin_method_channel.dart</code></p>
<pre><code class="lang-dart"><span class="hljs-keyword">import</span> <span class="hljs-string">'package:flutter/foundation.dart'</span>;
<span class="hljs-keyword">import</span> <span class="hljs-string">'package:flutter/services.dart'</span>;

<span class="hljs-keyword">import</span> <span class="hljs-string">'sample_plugin_platform_interface.dart'</span>;

<span class="hljs-comment">/// <span class="markdown">An implementation of [SamplePluginPlatform] that uses method channels.</span></span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MethodChannelSamplePlugin</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">SamplePluginPlatform</span> </span>{
  <span class="hljs-comment">/// <span class="markdown">The method channel used to interact with the native platform.</span></span>
  <span class="hljs-meta">@visibleForTesting</span>
  <span class="hljs-keyword">final</span> methodChannel = <span class="hljs-keyword">const</span> MethodChannel(<span class="hljs-string">'sample_plugin'</span>);

  <span class="hljs-meta">@override</span>
  Future&lt;<span class="hljs-built_in">String?</span>&gt; getPlatformVersion() <span class="hljs-keyword">async</span> {
    <span class="hljs-keyword">final</span> version = <span class="hljs-keyword">await</span> methodChannel.invokeMethod&lt;<span class="hljs-built_in">String</span>&gt;(<span class="hljs-string">'getPlatformVersion'</span>);
    <span class="hljs-keyword">return</span> version;
  }
}
</code></pre>
<h3 id="heading-code-explanation-2">Code Explanation:</h3>
<pre><code class="lang-dart"><span class="hljs-keyword">import</span> <span class="hljs-string">'package:flutter/foundation.dart'</span>;
<span class="hljs-keyword">import</span> <span class="hljs-string">'package:flutter/services.dart'</span>;

<span class="hljs-keyword">import</span> <span class="hljs-string">'sample_plugin_platform_interface.dart'</span>;
</code></pre>
<p>These are the import statements. The code is importing necessary Flutter packages and a local file (<code>sample_plugin_platform_interface.dart</code>).</p>
<pre><code class="lang-dart"><span class="hljs-comment">/// <span class="markdown">An implementation of [SamplePluginPlatform] that uses method channels.</span></span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MethodChannelSamplePlugin</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">SamplePluginPlatform</span> </span>{
</code></pre>
<p>This defines a class named <code>MethodChannelSamplePlugin</code> that extends <code>SamplePluginPlatform</code>. It's an implementation of the platform interface using method channels.</p>
<pre><code class="lang-dart">  <span class="hljs-comment">/// <span class="markdown">The method channel used to interact with the native platform.</span></span>
  <span class="hljs-meta">@visibleForTesting</span>
  <span class="hljs-keyword">final</span> methodChannel = <span class="hljs-keyword">const</span> MethodChannel(<span class="hljs-string">'sample_plugin'</span>);
</code></pre>
<p>This creates a <code>MethodChannel</code> object named <code>methodChannel</code>. Method channels are used for communication between Flutter (Dart) and the native platform (iOS/Android). The channel is identified by the string 'sample_plugin'.</p>
<p>The <code>@visibleForTesting</code> annotation indicates that this field is intended to be visible for testing purposes.</p>
<pre><code class="lang-dart">  <span class="hljs-meta">@override</span>
  Future&lt;<span class="hljs-built_in">String?</span>&gt; getPlatformVersion() <span class="hljs-keyword">async</span> {
    <span class="hljs-keyword">final</span> version = <span class="hljs-keyword">await</span> methodChannel.invokeMethod&lt;<span class="hljs-built_in">String</span>&gt;(<span class="hljs-string">'getPlatformVersion'</span>);
    <span class="hljs-keyword">return</span> version;
  }
</code></pre>
<p>This is an overridden method from the <code>SamplePluginPlatform</code> class. It's an asynchronous method that returns a <code>Future&lt;String?&gt;</code>.</p>
<p>Inside the method:</p>
<ol>
<li><p>It calls <code>invokeMethod</code> on the <code>methodChannel</code>, passing 'getPlatformVersion' as the method name.</p>
</li>
<li><p>This invokes a method on the native side (iOS/Android) through the method channel.</p>
</li>
<li><p>The result (platform version) is then returned.</p>
</li>
</ol>
<p>In summary, this code sets up a method channel to communicate with native code, specifically to retrieve the platform version.</p>
<h2 id="heading-example-directory">Example Directory:</h2>
<p>The <code>example/</code> directory contains a simple Flutter application that depends on the created <code>sample_plugin</code>. Let's check out the <code>pubspec.yaml</code> file:</p>
<pre><code class="lang-yaml"><span class="hljs-attr">name:</span> <span class="hljs-string">sample_plugin_example</span>
<span class="hljs-attr">description:</span> <span class="hljs-string">"Demonstrates how to use the sample_plugin plugin."</span>
<span class="hljs-comment"># The following line prevents the package from being accidentally published to</span>
<span class="hljs-comment"># pub.dev using `flutter pub publish`. This is preferred for private packages.</span>
<span class="hljs-attr">publish_to:</span> <span class="hljs-string">'none'</span> <span class="hljs-comment"># Remove this line if you wish to publish to pub.dev</span>

<span class="hljs-attr">environment:</span>
  <span class="hljs-attr">sdk:</span> <span class="hljs-string">'&gt;=3.4.4 &lt;4.0.0'</span>

<span class="hljs-attr">dependencies:</span>
  <span class="hljs-attr">flutter:</span>
    <span class="hljs-attr">sdk:</span> <span class="hljs-string">flutter</span>

  <span class="hljs-attr">sample_plugin:</span>
    <span class="hljs-attr">path:</span> <span class="hljs-string">../</span>
  <span class="hljs-attr">cupertino_icons:</span> <span class="hljs-string">^1.0.6</span>

<span class="hljs-attr">dev_dependencies:</span>
  <span class="hljs-attr">integration_test:</span>
    <span class="hljs-attr">sdk:</span> <span class="hljs-string">flutter</span>
  <span class="hljs-attr">flutter_test:</span>
    <span class="hljs-attr">sdk:</span> <span class="hljs-string">flutter</span>

  <span class="hljs-attr">flutter_lints:</span> <span class="hljs-string">^3.0.0</span>

<span class="hljs-attr">flutter:</span>

  <span class="hljs-attr">uses-material-design:</span> <span class="hljs-literal">true</span>
</code></pre>
<p>As we can see it set the path of the sample plugin.</p>
<h3 id="heading-using-the-plugin">Using the Plugin:</h3>
<p>To use the plugin package, we start by importing it into our Dart libraries like, like any other plugin:</p>
<pre><code class="lang-dart"><span class="hljs-keyword">import</span> <span class="hljs-string">'package:sample_plugin/sample_plugin.dart'</span>
</code></pre>
<p>Now we can see the <code>main.dart</code> under <code>example/lib/</code> in the following folder:</p>
<pre><code class="lang-dart"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">_MyAppState</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">State</span>&lt;<span class="hljs-title">MyApp</span>&gt; </span>{
  <span class="hljs-built_in">String</span> _platformVersion = <span class="hljs-string">'Unknown'</span>;
  <span class="hljs-keyword">final</span> _samplePlugin = SamplePlugin();

  <span class="hljs-meta">@override</span>
  <span class="hljs-keyword">void</span> initState() {
    <span class="hljs-keyword">super</span>.initState();
    initPlatformState();
  }

  <span class="hljs-comment">// Platform messages are asynchronous, so we initialize in an async method.</span>
  Future&lt;<span class="hljs-keyword">void</span>&gt; initPlatformState() <span class="hljs-keyword">async</span> {
    <span class="hljs-built_in">String</span> platformVersion;
    <span class="hljs-comment">// Platform messages may fail, so we use a try/catch PlatformException.</span>
    <span class="hljs-comment">// We also handle the message potentially returning null.</span>
    <span class="hljs-keyword">try</span> {
      platformVersion =
          <span class="hljs-keyword">await</span> _samplePlugin.getPlatformVersion() ?? <span class="hljs-string">'Unknown platform version'</span>;
    } <span class="hljs-keyword">on</span> PlatformException {
      platformVersion = <span class="hljs-string">'Failed to get platform version.'</span>;
    }

    <span class="hljs-comment">// If the widget was removed from the tree while the asynchronous platform</span>
    <span class="hljs-comment">// message was in flight, we want to discard the reply rather than calling</span>
    <span class="hljs-comment">// setState to update our non-existent appearance.</span>
    <span class="hljs-keyword">if</span> (!mounted) <span class="hljs-keyword">return</span>;

    setState(() {
      _platformVersion = platformVersion;
    });
  }

  <span class="hljs-meta">@override</span>
  Widget build(BuildContext context) {
    <span class="hljs-keyword">return</span> MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: <span class="hljs-keyword">const</span> Text(<span class="hljs-string">'Plugin example app'</span>),
        ),
        body: Center(
          child: Text(<span class="hljs-string">'Running on: <span class="hljs-subst">$_platformVersion</span>\n'</span>),
        ),
      ),
    );
  }
}
</code></pre>
<p>So we want to make note of some points here:</p>
<ul>
<li><p>The method calling is <code>async</code> as platform messages are asynchronous.</p>
</li>
<li><p>Since platform messages may fail, we are using a try/catch <code>PlatformException</code> that helps to inspect errors.</p>
</li>
<li><p><code>!(mounted)</code> helps us in discarding the result from the platform if the widget is removed from the tree by then.</p>
</li>
<li><p>We call <code>setState()</code> to notify our stateful widget to show the updated platform version from the plugin.</p>
</li>
</ul>
<h3 id="heading-documentation-for-your-plugin">Documentation for your Plugin:</h3>
<p>Creating good documentation for your project is out of scope of this article. You can read up more on this from dart website: <a target="_blank" href="https://dart.dev/effective-dart/documentation">Effective Dart Documentation</a>.</p>
<p>Good luck and happy coding 🐦</p>
]]></content:encoded></item><item><title><![CDATA[Flutter embed Native Platforms:]]></title><description><![CDATA[Platform views allow you to embed native views in a Flutter app, so you can apply transforms, clips, and opacity to the native view from Dart. This allows…]]></description><link>https://harishkunchala.com/flutter-embed-native-platforms</link><guid isPermaLink="true">https://harishkunchala.com/flutter-embed-native-platforms</guid><category><![CDATA[Platform-views]]></category><category><![CDATA[Flutter]]></category><category><![CDATA[Android]]></category><category><![CDATA[iOS]]></category><dc:creator><![CDATA[Harish Kunchala]]></dc:creator><pubDate>Mon, 22 Jul 2024 05:04:26 GMT</pubDate><content:encoded><![CDATA[<p>Platform views allow you to embed native views in a Flutter app, so you can apply transforms, clips, and opacity to the native view from Dart.</p>
<p>This allows you, for example, to use the native Google Maps from the Android SDK directly inside your Flutter app.</p>
<h3 id="heading-source-code">Source Code:</h3>
<p>You can find the source code here: <a target="_blank" href="https://github.com/khkred/native_views_flutter">native_views_flutter</a></p>
<h3 id="heading-two-implementations">Two implementations:</h3>
<p>Platform Views on Android have two implementations. They come with tradeoffs both in terms of performance and fidelity. <mark>Platforms views require Android API 23+.</mark></p>
<h3 id="heading-hybrid-composition">Hybrid Composition:</h3>
<p>Platform views are rendered as they are normally. Flutter content is rendered into a texture. SurfaceFlinger composes the Flutter content and platform Views.</p>
<p><strong>SurfaceFlinger:</strong></p>
<ul>
<li><p>SurfaceFlinger is a service that plays a critical part in determining what is rendered on the screen on any Android device.</p>
</li>
<li><p>SurfaceFlinger doesn't render anything on the screen.</p>
</li>
<li><p>In fact, all it does is merely composite buffers of data before handing them off to the HAL.</p>
</li>
<li><p>In layman’s terms — The SurfaceFlinger takes in buffers of display data, composites them into a single buffer, and then passes that on to the hardware abstraction layer (HAL).</p>
</li>
</ul>
<h3 id="heading-texture-layer">Texture Layer:</h3>
<p>Platform Views are rendered as textures. Flutter draws the platform views (via the texture). Flutter content is rendered directly into a Surface.</p>
<h3 id="heading-lets-start-the-app">Let's start the app:</h3>
<p>First of all let's create the an app in flutter:</p>
<pre><code class="lang-bash">flutter create native_views --platforms=android,ios
</code></pre>
<p>After we create it, go to <code>android/app/build.gradle</code> and set <code>minSDK = 23</code></p>
<p><img src="https://i.postimg.cc/DZnbFWwx/min-gradle.png" alt /></p>
<h2 id="heading-platform-side-android">Platform side: Android</h2>
<h3 id="heading-nativeviewexampledart">native_view_example.dart</h3>
<p>Now let's create a new file named <code>native_view_example.dart</code> and build it in order to get the Android view:</p>
<pre><code class="lang-dart"><span class="hljs-keyword">import</span> <span class="hljs-string">'package:flutter/material.dart'</span>;
<span class="hljs-keyword">import</span> <span class="hljs-string">'package:flutter/services.dart'</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">NativeViewExample</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">StatelessWidget</span> </span>{
  <span class="hljs-keyword">const</span> NativeViewExample({<span class="hljs-keyword">super</span>.key});

  <span class="hljs-meta">@override</span>
  Widget build(BuildContext context) {
    <span class="hljs-comment">// This is used in the platform side to register the view</span>
    <span class="hljs-keyword">const</span> <span class="hljs-built_in">String</span> viewType = <span class="hljs-string">'&lt;platform-view-type&gt;'</span>;
    <span class="hljs-comment">// Pass parameters to the platform side</span>
    <span class="hljs-keyword">final</span> <span class="hljs-built_in">Map</span>&lt;<span class="hljs-built_in">String</span>, <span class="hljs-built_in">dynamic</span>&gt; creationParams = &lt;<span class="hljs-built_in">String</span>, <span class="hljs-built_in">dynamic</span>&gt;{};

    <span class="hljs-keyword">return</span> AndroidView(
      viewType: viewType,
      layoutDirection: TextDirection.ltr,
      creationParams: creationParams,
      creationParamsCodec: <span class="hljs-keyword">const</span> StandardMessageCodec(),
    );
  }
}
</code></pre>
<p>Now on the android side let's use the standard <code>io.flutter.plugin.platform</code> package in Kotlin:</p>
<p>First let's start by creating an internal class in a file named <code>NativeView.kt</code> which extends PlatformView.</p>
<h3 id="heading-nativeviewkt">NativeView.kt:</h3>
<p>This view is basically what see in our Flutter. So let's open our android folder in our Android studio and get started: File: <code>NativeView.kt</code></p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">package</span> com.harishkunchala.native_views  

<span class="hljs-keyword">import</span> android.content.Context  
<span class="hljs-keyword">import</span> android.graphics.Color  
<span class="hljs-keyword">import</span> android.view.View  
<span class="hljs-keyword">import</span> android.widget.TextView  
<span class="hljs-keyword">import</span> io.flutter.plugin.platform.PlatformView  

<span class="hljs-keyword">internal</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">NativeView</span> </span>(context: Context, id: <span class="hljs-built_in">Int</span>, creationParams: Map&lt;String?, Any?&gt;?): PlatformView{  
    <span class="hljs-keyword">private</span>  <span class="hljs-keyword">val</span> textView: TextView = TextView(context)  

    <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">getView</span><span class="hljs-params">()</span></span>: View {  
        <span class="hljs-keyword">return</span>  textView  
    }  

    <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">dispose</span><span class="hljs-params">()</span></span> {  
    }  
    <span class="hljs-keyword">init</span> {  
        textView.textSize = <span class="hljs-number">72f</span>  
        textView.setBackgroundColor(Color.rgb(<span class="hljs-number">255</span>,<span class="hljs-number">255</span>,<span class="hljs-number">255</span>))  
        textView.text = <span class="hljs-string">"Rendered on a native Android view (id: <span class="hljs-variable">$id</span>)"</span>  
    }  
}
</code></pre>
<h3 id="heading-nativeviewfactorykt">NativeViewFactory.kt:</h3>
<p>Now let's create a factory class that creates an instance of <code>NativeView</code> created eariler.</p>
<p>File: <code>NativeViewFactory.kt</code>:</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">package</span> com.harishkunchala.native_views  

<span class="hljs-keyword">import</span> android.content.Context  
<span class="hljs-keyword">import</span> io.flutter.plugin.common.StandardMessageCodec  
<span class="hljs-keyword">import</span> io.flutter.plugin.platform.PlatformView  
<span class="hljs-keyword">import</span> io.flutter.plugin.platform.PlatformViewFactory  

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">NativeViewFactory</span> : <span class="hljs-type">PlatformViewFactory</span></span>(StandardMessageCodec.INSTANCE){  
    <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">create</span><span class="hljs-params">(context: <span class="hljs-type">Context</span>, viewId: <span class="hljs-type">Int</span>, args: <span class="hljs-type">Any</span>?)</span></span>: PlatformView {  
        <span class="hljs-keyword">val</span> creationParams = args <span class="hljs-keyword">as</span> Map&lt;String?, Any?&gt;?  
        <span class="hljs-keyword">return</span> NativeView(context,viewId,creationParams)  
    }  
}
</code></pre>
<p>Finally let's register the platform view. You can do this in an app or a plugin. Since we are doing it in an app, for app registration, modify the app's main activity</p>
<h3 id="heading-finally-connect-everything-together-in-mainactivitykt">Finally Connect Everything together in MainActivity.kt</h3>
<p>File: <code>MainActivity.kt</code></p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">package</span> com.harishkunchala.native_views  

<span class="hljs-keyword">import</span> io.flutter.embedding.android.FlutterActivity  
<span class="hljs-keyword">import</span> io.flutter.embedding.engine.FlutterEngine  

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MainActivity</span>: <span class="hljs-type">FlutterActivity</span></span>() {  
    <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">configureFlutterEngine</span><span class="hljs-params">(flutterEngine: <span class="hljs-type">FlutterEngine</span>)</span></span> {  
        <span class="hljs-keyword">super</span>.configureFlutterEngine(flutterEngine)  
        flutterEngine.platformViewsController.registry.registerViewFactory(<span class="hljs-string">"&lt;platform-view-type&gt;"</span>, NativeViewFactory())  

    }  
}
</code></pre>
<p>Finally let's test the app in an android emulator. Before we do that let's set this as the body of our <code>HomePage()</code> from our <code>main.dart</code>.</p>
<h3 id="heading-call-nativeviewexampledart-in-our-maindart">Call <code>native_view_example.dart</code> in our <code>main.dart</code></h3>
<p>File: <code>main.dart</code></p>
<pre><code class="lang-dart"><span class="hljs-keyword">import</span> <span class="hljs-string">'package:flutter/material.dart'</span>;
<span class="hljs-keyword">import</span> <span class="hljs-string">'package:native_views/src/native_view_example.dart'</span>;

<span class="hljs-keyword">void</span> main() {
  runApp(<span class="hljs-keyword">const</span> MyApp());
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyApp</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">StatelessWidget</span> </span>{
  <span class="hljs-keyword">const</span> MyApp({<span class="hljs-keyword">super</span>.key});

  <span class="hljs-comment">// This widget is the root of your application.</span>
  <span class="hljs-meta">@override</span>
  Widget build(BuildContext context) {
    <span class="hljs-keyword">return</span> MaterialApp(
      title: <span class="hljs-string">'Native View Demo'</span>,
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: <span class="hljs-keyword">true</span>,
      ),
      home: <span class="hljs-keyword">const</span> HomePage(),
    );
  }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">HomePage</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">StatelessWidget</span> </span>{
  <span class="hljs-keyword">const</span> HomePage({<span class="hljs-keyword">super</span>.key});

  <span class="hljs-meta">@override</span>
  Widget build(BuildContext context) {
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">const</span> Scaffold(
      body: SizedBox(
        width: <span class="hljs-built_in">double</span>.infinity,
        child: Center(
          child: NativeViewExample(),
        ),
      ),
    );
  }
}
</code></pre>
<h3 id="heading-android-output">Android Output:</h3>
<p>Perfect let's test our app: And here's output:</p>
<p><img src="https://i.postimg.cc/zXtMgKmR/Screenshot-2024-07-21-at-7-41-50-PM.png" alt /></p>
<h2 id="heading-platform-side-ios">Platform Side: iOS</h2>
<h3 id="heading-nativeviewiosdart">native_view_ios.dart</h3>
<p>First of all let's create a dart file that'll show our native ios view. For this we are going to use the <code>UiKitView</code></p>
<p>File: <code>native_view_ios.dart</code></p>
<pre><code class="lang-dart"><span class="hljs-keyword">import</span> <span class="hljs-string">'package:flutter/material.dart'</span>;
<span class="hljs-keyword">import</span> <span class="hljs-string">'package:flutter/services.dart'</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">NativeViewIos</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">StatelessWidget</span> </span>{
  <span class="hljs-keyword">const</span> NativeViewIos({<span class="hljs-keyword">super</span>.key});

<span class="hljs-meta">@override</span>
Widget build(BuildContext context) {
  <span class="hljs-comment">// This is used in the platform side to register the view.</span>
  <span class="hljs-keyword">const</span> <span class="hljs-built_in">String</span> viewType = <span class="hljs-string">'&lt;platform-view-type&gt;'</span>;
  <span class="hljs-comment">// Pass parameters to the platform side.</span>
  <span class="hljs-keyword">final</span> <span class="hljs-built_in">Map</span>&lt;<span class="hljs-built_in">String</span>, <span class="hljs-built_in">dynamic</span>&gt; creationParams = &lt;<span class="hljs-built_in">String</span>, <span class="hljs-built_in">dynamic</span>&gt;{};

  <span class="hljs-keyword">return</span> UiKitView(
    viewType: viewType,
    layoutDirection: TextDirection.ltr,
    creationParams: creationParams,
    creationParamsCodec: <span class="hljs-keyword">const</span> StandardMessageCodec(),
  );
}
}
</code></pre>
<h3 id="heading-flnativeviewfactory-and-flnativeview">FLNativeViewFactory and FLNativeView</h3>
<p>Now we need to implement the platform view and the factory. The <code>FLNativeViewFactory</code> creates the platform view, and the platform view provides a reference to the <code>UIView</code>.</p>
<p>File: <code>FLNativeView.swift</code>:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">import</span> Flutter
<span class="hljs-keyword">import</span> UIKit

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">FLNativeViewFactory</span>: <span class="hljs-title">NSObject</span>, <span class="hljs-title">FlutterPlatformViewFactory</span> </span>{

    <span class="hljs-keyword">private</span> <span class="hljs-keyword">var</span> messenger: <span class="hljs-type">FlutterBinaryMessenger</span>

    <span class="hljs-keyword">init</span>(messenger: <span class="hljs-type">FlutterBinaryMessenger</span>) {
        <span class="hljs-keyword">self</span>.messenger = messenger
        <span class="hljs-keyword">super</span>.<span class="hljs-keyword">init</span>()
    }

    <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">create</span> <span class="hljs-params">(
        withFrame frame: CGRect,
        viewIdentifier viewId: Int64,
        arguments args: <span class="hljs-keyword">Any</span>?
    )</span></span> -&gt; <span class="hljs-type">FlutterPlatformView</span>{
    <span class="hljs-keyword">return</span> <span class="hljs-type">FLNativeView</span>(frame: frame,
                        viewIdentifier: viewId,
                        arguments: args,
                        binaryMessenger: messenger)
    }

    <span class="hljs-comment">/// Implementing this method is only necessary when the `arguments` in `createWithFrame` is not `nil`.</span>
        <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">createArgsCodec</span><span class="hljs-params">()</span></span> -&gt; <span class="hljs-type">FlutterMessageCodec</span> &amp; <span class="hljs-type">NSObjectProtocol</span> {
              <span class="hljs-keyword">return</span> <span class="hljs-type">FlutterStandardMessageCodec</span>.sharedInstance()
        }
}


<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">FLNativeView</span>: <span class="hljs-title">NSObject</span>, <span class="hljs-title">FlutterPlatformView</span> </span>{
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">var</span> _view: <span class="hljs-type">UIView</span>

    <span class="hljs-keyword">init</span>(frame: <span class="hljs-type">CGRect</span>, viewIdentifier viewId: <span class="hljs-type">Int64</span>, arguments args: <span class="hljs-type">Any?</span>, binaryMessenger messenger: <span class="hljs-type">FlutterBinaryMessenger</span>) {
        _view = <span class="hljs-type">UIView</span>()
        <span class="hljs-keyword">super</span>.<span class="hljs-keyword">init</span>()

        <span class="hljs-comment">// iOS views can be created here</span>
        createNativeView(view: _view)
    }

    <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">view</span><span class="hljs-params">()</span></span> -&gt; <span class="hljs-type">UIView</span> {
        <span class="hljs-keyword">return</span> _view
    }

    <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">createNativeView</span><span class="hljs-params">(view _view: UIView)</span></span> {  
    _view.backgroundColor = <span class="hljs-type">UIColor</span>.blue  

    <span class="hljs-keyword">let</span> nativeLabel = <span class="hljs-type">UILabel</span>()  
    nativeLabel.text = <span class="hljs-string">"Native text from iOS"</span>  
    nativeLabel.textColor = <span class="hljs-type">UIColor</span>.white  
    nativeLabel.textAlignment = .center  

    <span class="hljs-comment">// Set the label's size    nativeLabel.sizeToFit()  </span>

    <span class="hljs-comment">// Center the label in the view    nativeLabel.center = _view.center  </span>

    _view.addSubview(nativeLabel)  

    <span class="hljs-comment">// Add constraints to keep the label centered    nativeLabel.translatesAutoresizingMaskIntoConstraints = false  </span>
    <span class="hljs-type">NSLayoutConstraint</span>.activate([  
        nativeLabel.centerXAnchor.constraint(equalTo: _view.centerXAnchor),  
        nativeLabel.centerYAnchor.constraint(equalTo: _view.centerYAnchor)  
    ])  
}

}
</code></pre>
<h3 id="heading-register-the-platform-view-in-appdelegateswift">Register the platform view in AppDelegate.swift:</h3>
<p>Finally let's register the platform view with AppDelegate:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">import</span> Flutter
<span class="hljs-keyword">import</span> UIKit

<span class="hljs-meta">@UIApplicationMain</span>
<span class="hljs-meta">@objc</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">AppDelegate</span>: <span class="hljs-title">FlutterAppDelegate</span> </span>{
  <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">application</span><span class="hljs-params">(
    <span class="hljs-number">_</span> application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: <span class="hljs-keyword">Any</span>]?
  )</span></span> -&gt; <span class="hljs-type">Bool</span> {
    <span class="hljs-type">GeneratedPluginRegistrant</span>.register(with: <span class="hljs-keyword">self</span>)

      <span class="hljs-keyword">guard</span> <span class="hljs-keyword">let</span> pluginRegisterar = <span class="hljs-keyword">self</span>.registrar(forPlugin: <span class="hljs-string">"plugin-name"</span>) <span class="hljs-keyword">else</span> { <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>}

      <span class="hljs-keyword">let</span> factory = <span class="hljs-type">FLNativeViewFactory</span>(messenger: pluginRegisterar.messenger())
      pluginRegisterar.register(factory, withId: <span class="hljs-string">"&lt;platform-view-type&gt;"</span>)
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">super</span>.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
}
</code></pre>
<h3 id="heading-connecting-it-in-dart">Connecting it in dart:</h3>
<p>Now in our <code>HomePage.dart</code>, we can use <code>defaultTargetPlatform</code> to detect the platform, and decide which widget to use:</p>
<pre><code class="lang-dart"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">HomePage</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">StatelessWidget</span> </span>{
  <span class="hljs-keyword">const</span> HomePage({<span class="hljs-keyword">super</span>.key});

  Widget getTargetPlatformView() {
    <span class="hljs-keyword">switch</span> (defaultTargetPlatform) {
      <span class="hljs-keyword">case</span> TargetPlatform.android:
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">const</span> NativeViewExample();

      <span class="hljs-keyword">case</span> TargetPlatform.iOS:
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">const</span> NativeViewIos();

      <span class="hljs-keyword">default</span>:
        <span class="hljs-keyword">throw</span> UnsupportedError(<span class="hljs-string">"Unsupported platform View"</span>);
    }
  }

  <span class="hljs-meta">@override</span>
  Widget build(BuildContext context) {
    <span class="hljs-keyword">return</span> Scaffold(
      body: SizedBox(
        width: <span class="hljs-built_in">double</span>.infinity,
        child: Center(
          child: getTargetPlatformView(),
        ),
      ),
    );
  }
}
</code></pre>
<h3 id="heading-ios-output">iOS Output:</h3>
<p>Now if we run the code on iOS simulator: Here's the output:</p>
<p><img src="https://i.postimg.cc/FKSGKnXD/Simulator-Screenshot-Iphone-15-pro-max-17-4-2024-07-21-at-21-56-01.png" alt /></p>
<p>And thus we can see our iOS update.</p>
]]></content:encoded></item><item><title><![CDATA[Flutter Unit Testing with Mockito:]]></title><description><![CDATA[In the previous article. We saw how to run the tests using Mocktail. In here we are going to look at how to do it using Mockito. Mocks allow emulating a…]]></description><link>https://harishkunchala.com/flutter-unit-testing-with-mockito</link><guid isPermaLink="true">https://harishkunchala.com/flutter-unit-testing-with-mockito</guid><category><![CDATA[Flutter]]></category><category><![CDATA[unit testing]]></category><category><![CDATA[mockito]]></category><dc:creator><![CDATA[Harish Kunchala]]></dc:creator><pubDate>Sat, 20 Jul 2024 21:37:43 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1721511384064/9e3e9ac9-0cc3-4ed8-9665-9780171fffc9.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In the previous <a target="_blank" href="https://harishkunchala.com/unit-testing-in-flutter-with-examples#heading-example-2-http-user-app">article</a>. We saw how to run the tests using <code>Mocktail</code>. In here we are going to look at how to do it using Mockito.</p>
<p>Mocks allow emulating a live web service or database and return specific results depending on the situation.</p>
<p>In here we are going to couple of things:</p>
<ol>
<li><p>Add the package dependencies.</p>
</li>
<li><p>Create a function to test.</p>
</li>
<li><p>Create a test file with a mock <code>http.Client</code>.</p>
</li>
<li><p>Write a test for each condition.</p>
</li>
<li><p>Run the tests.</p>
</li>
</ol>
<p>For more information, see the <a target="_blank" href="https://pub.dev/packages/mockito">Mockito package</a> documentation.</p>
<h3 id="heading-source-code">Source Code:</h3>
<p>Also you can find the source code here: <a target="_blank" href="https://github.com/khkred/flutter_testing_examples/tree/mockito_testing/unit_testing/users_http_test">users_http_test/mockito branch</a></p>
<h3 id="heading-1-add-the-package-dependencies">1. Add the package dependencies:</h3>
<p>To the use the <code>mockito</code> package, let's add it to <code>pubspec.yaml</code></p>
<p><code>mockito: 5.0.0</code> supports Dart's null safety thanks to code generation. To run the required code generation, add the <code>build_runner</code> dependency in the <code>dev_dependencies</code> section.</p>
<p>To add the dependencies, run <code>flutter pub add</code>:</p>
<pre><code class="lang-bash">flutter pub add dev:mockito dev:build_runner
</code></pre>
<h3 id="heading-2-create-a-function-to-test">2. Create a function to test</h3>
<p>In the previous article, we got a User from jsonplacholder.com</p>
<p>In here we are going to create a function to get a single album from <a target="_blank" href="http://jsonplaceholder.com">jsonplaceholder.com</a>. To test this, we are going to pass the <code>http.Client</code> as an argument to the function.</p>
<pre><code class="lang-dart"><span class="hljs-keyword">import</span> <span class="hljs-string">'dart:convert'</span>;  

<span class="hljs-keyword">import</span> <span class="hljs-string">'package:http/http.dart'</span> <span class="hljs-keyword">as</span> http;  

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">UserAlbum</span> </span>{  
  <span class="hljs-keyword">final</span> http.Client client;  

  UserAlbum({<span class="hljs-keyword">required</span> <span class="hljs-keyword">this</span>.client});  

  Future&lt;<span class="hljs-built_in">Map</span>&lt;<span class="hljs-built_in">String</span>, <span class="hljs-built_in">dynamic</span>&gt;&gt; fetchAlbum() <span class="hljs-keyword">async</span> {  
    <span class="hljs-keyword">final</span> response = <span class="hljs-keyword">await</span> client  
        .<span class="hljs-keyword">get</span>(<span class="hljs-built_in">Uri</span>.parse(<span class="hljs-string">'https://jsonplaceholder.typicode.com/albums/1'</span>));  

    <span class="hljs-keyword">if</span> (response.statusCode == <span class="hljs-number">200</span>) {  
      <span class="hljs-keyword">final</span> responseBody = jsonDecode(response.body);  

      <span class="hljs-keyword">return</span> responseBody <span class="hljs-keyword">as</span> <span class="hljs-built_in">Map</span>&lt;<span class="hljs-built_in">String</span>, <span class="hljs-built_in">dynamic</span>&gt;;  
    } <span class="hljs-keyword">else</span> {  
      <span class="hljs-keyword">throw</span> Exception(<span class="hljs-string">'Failed to load album'</span>);  
    }  
  }  
}
</code></pre>
<h3 id="heading-3-create-a-test-file-with-a-mock-httpclient">3. Create a test file with a mock <code>http.Client</code></h3>
<ul>
<li><p>Following the advice from previous article let's create a <code>user_album_test.dart</code> in the root <code>test</code> folder.</p>
</li>
<li><p>Add the annotation <code>@GenerateMocks([http.Client])</code> to the main function to generate a <code>MockClient</code>class with <code>mockito</code>.</p>
</li>
<li><p>The generated <code>MockClient</code> class implements the <code>http.Client</code> class. This allows you to pass the <code>MockClient</code> to the <code>userAlbum</code> class, and return different http responses in each test.</p>
</li>
</ul>
<pre><code class="lang-dart"><span class="hljs-keyword">import</span> <span class="hljs-string">'package:http/http.dart'</span> <span class="hljs-keyword">as</span> http;  
<span class="hljs-keyword">import</span> <span class="hljs-string">'package:users_http_test/user_album.dart'</span>;  
<span class="hljs-keyword">import</span> <span class="hljs-string">'package:mockito/annotations.dart'</span>;  

<span class="hljs-comment">// Generate a MockClient using the Mockito package.  </span>
<span class="hljs-comment">// Create new instances of this class in each test.  </span>
<span class="hljs-meta">@GenerateMocks</span>([http.Client])  
<span class="hljs-keyword">void</span> main() {  
}
</code></pre>
<p>Next, generate the mocks running the following command:</p>
<pre><code class="lang-bash">dart run build_runner build
</code></pre>
<h3 id="heading-4-write-a-test-for-each-condition">4. Write a test for each condition</h3>
<p>The <code>fetchAlbum()</code> function does one of two things:</p>
<ol>
<li><p>Returns an Album JSON if the http call succeeds.</p>
</li>
<li><p>Throws an <code>Exception</code> if the http call fails</p>
</li>
</ol>
<p>Therefore, you want to test these two conditions. Use the <code>MockClient</code> class to return an "Ok" response for the success test, and an error response for the unsuccessful test. Test these conditions using the <code>when()</code> function provided by Mockito:</p>
<pre><code class="lang-dart"><span class="hljs-keyword">import</span> <span class="hljs-string">'package:flutter_test/flutter_test.dart'</span>;  
<span class="hljs-keyword">import</span> <span class="hljs-string">'package:http/http.dart'</span> <span class="hljs-keyword">as</span> http;  
<span class="hljs-keyword">import</span> <span class="hljs-string">'package:mockito/mockito.dart'</span>;  
<span class="hljs-keyword">import</span> <span class="hljs-string">'package:users_http_test/user_album.dart'</span>;  
<span class="hljs-keyword">import</span> <span class="hljs-string">'package:mockito/annotations.dart'</span>;  

<span class="hljs-keyword">import</span> <span class="hljs-string">'user_album_test.mocks.dart'</span>;  

<span class="hljs-comment">// Generate a MockClient using the Mockito package.  </span>
<span class="hljs-comment">// Create new instances of this class in each test.  </span>
<span class="hljs-meta">@GenerateMocks</span>([http.Client])  
<span class="hljs-keyword">void</span> main() {  
  group(<span class="hljs-string">'fetchAlbum'</span>, () {  
    test(<span class="hljs-string">'Given an UserAlbum Class, when fetchAlbum() is called then return an JSON IF THE HTTP call completes successfully'</span>, () <span class="hljs-keyword">async</span> {  
      <span class="hljs-keyword">final</span> client = MockClient();  

      <span class="hljs-comment">// Use Mockito to return a successful response when it calls the  </span>
      <span class="hljs-comment">// provided http.Client.      when(client.get(Uri.parse('https://jsonplaceholder.typicode.com/albums/1'))).thenAnswer((_) async {  </span>
        <span class="hljs-keyword">return</span> http.Response(<span class="hljs-string">'{"userId": 1, "id": 2, "title": "mock"}'</span>, <span class="hljs-number">200</span>);  
      });  

      <span class="hljs-keyword">final</span> userAlbum = UserAlbum(client: client);  

      expect(<span class="hljs-keyword">await</span> userAlbum.fetchAlbum(), isA&lt;<span class="hljs-built_in">Map</span>&lt;<span class="hljs-built_in">String</span>,<span class="hljs-built_in">dynamic</span>&gt;&gt;());  
    });  

    test(<span class="hljs-string">'Given an UserAlbum Class, when fetchAlbum() is called, then throws an exception if http call completes with an error'</span>, () <span class="hljs-keyword">async</span> {  
      <span class="hljs-keyword">final</span> client = MockClient();  

      <span class="hljs-comment">// Use Mockito to return an unsuccessful response when it calls the  </span>
      <span class="hljs-comment">// provided http.Client.      </span>
           when(client.<span class="hljs-keyword">get</span>(<span class="hljs-built_in">Uri</span>.parse(<span class="hljs-string">'https://jsonplaceholder.typicode.com/albums/1'</span>))).thenAnswer((_) <span class="hljs-keyword">async</span> =&gt; http.Response(<span class="hljs-string">'Not Found'</span>, <span class="hljs-number">404</span>));  

      <span class="hljs-keyword">final</span> userAlbum = UserAlbum(client: client);  
      expect(userAlbum.fetchAlbum(), throwsException);  
    });  
  });  
}
</code></pre>
<h3 id="heading-5-run-the-tests">5. Run the tests</h3>
<p>Now that we have a <code>fetchAlbum()</code> functions with tests in place, run the tests:</p>
<pre><code class="lang-bash">flutter <span class="hljs-built_in">test</span> <span class="hljs-built_in">test</span>/user_album_test.dart
</code></pre>
<p>And looks like all the tests passed. So we've learned how to use the Mockito package, I would recommend that you read up more by reading the documentation provided by the <a target="_blank" href="https://pub.dev/packages/mockito">Mockito package</a>.</p>
<p>So good luck with your programming journey and happy coding 🐦</p>
]]></content:encoded></item><item><title><![CDATA[How to use Platform Channels in Flutter]]></title><description><![CDATA[Platform channels in Flutter uses a flexible system that allows us to call platform-specific APIs in a language that works directly with those APIs: Kotlin…]]></description><link>https://harishkunchala.com/how-to-use-platform-channels-in-flutter</link><guid isPermaLink="true">https://harishkunchala.com/how-to-use-platform-channels-in-flutter</guid><category><![CDATA[Flutter]]></category><category><![CDATA[interoperability]]></category><dc:creator><![CDATA[Harish Kunchala]]></dc:creator><pubDate>Sat, 20 Jul 2024 02:09:23 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1721441331569/1076f6ab-e527-4b9e-849e-0d2c9039b246.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Platform channels in Flutter uses a flexible system that allows us to call platform-specific APIs in a language that works directly with those APIs:</p>
<ul>
<li><p>Kotlin or Java on Android</p>
</li>
<li><p>Swift or Objective-C on iOS</p>
</li>
<li><p>C++ on Windows</p>
</li>
<li><p>Objective-C on macOS</p>
</li>
<li><p>C on Linux</p>
</li>
</ul>
<p><mark>Flutter's builtin platform-specific API support doesn't rely on code generation, but rather on a flexible message passing style</mark></p>
<p>This is the way it works:</p>
<ul>
<li><p>The Flutter portion of the app sends messages to its <em>host</em>, the non-Dart portion of the app, over a platform channel.</p>
</li>
<li><p>The <em>host</em> listens on the platform channel, and receives the message. It then calls into any number of platform-specific APIs—using the native programming language—and sends a response back to the <em>client</em>, the Flutter portion of the app.</p>
</li>
</ul>
<h3 id="heading-platform-channels-architecture">Platform Channels Architecture:</h3>
<p><img src="https://docs.flutter.dev/assets/images/docs/PlatformChannels.png" alt /></p>
<p><strong>Observations from the architecture:</strong> - On Flutter side <code>MethodChannel</code> enables sending messages that correspond to method calls. - On the platform side, <code>MethodChannel</code> on Android <a target="_blank" href="https://api.flutter.dev/javadoc/io/flutter/plugin/common/MethodChannel.html">MethodChannelAndroid</a> and <code>FlutterMethodChannel</code> on iOS <a target="_blank" href="https://api.flutter.dev/ios-embedder/interface_flutter_method_channel.html">MethodChanneliOS</a> enable receiving method calls and sending back a result. These classes allow you to develop a platform plugin with very little 'boilerplate' code.</p>
<h3 id="heading-getting-battery-life-of-the-device-using-platform-channels">Getting Battery Life of the device using Platform Channels</h3>
<p>Let's create an app that gets Battery life of the device. We are going to implement it in all the platforms. Here are the platforms along with their associated APIs.</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Platform</td><td>API</td></tr>
</thead>
<tbody>
<tr>
<td>Android</td><td><code>BatteryManager</code></td></tr>
<tr>
<td>iOS</td><td><code>device.batteryLevel</code></td></tr>
<tr>
<td>Windows</td><td><code>GetSystemPowerStatus</code></td></tr>
<tr>
<td>Linux</td><td><code>UPower</code></td></tr>
<tr>
<td>We are going to call all of this with a Single Platform Message: <code>getBatteryLevel()</code></td></tr>
</tbody>
</table>
</div><p>For now we'll stick with Android and iOS</p>
<h3 id="heading-source-code">Source Code:</h3>
<p>You can find the source code here: <a target="_blank" href="https://github.com/khkred/battery_level_tutorial">battery_level_tutorial</a></p>
<h3 id="heading-step-1-create-a-new-app">Step 1: Create a new App</h3>
<p>In terminal run the following: <code>flutter create battery_level_tutorial</code></p>
<h3 id="heading-step-2-create-the-flutter-platform-client">Step 2: Create the Flutter Platform Client</h3>
<p>As we know the app's <code>State</code> class holds the current app state. So let's extend that to hold the current battery state.</p>
<p><strong>First, construct the channel:</strong> In order to do that we need to define a single method called <code>MethodChannel()</code> that returns the battery level.</p>
<p><strong>The client and host sides of a channel are connected through a channel name passed in the constructor.</strong> All channel names used in a single app must be unique; So we just have to prefix the channel name with a unique domain prefix.</p>
<p><strong>Our Channel Name:</strong> For example, let's say our channel name is <mark>battery</mark> so our domain prefix would be. <code>com.harishkunchala</code> so our <mark>total channel name</mark> is <code>com.harishkunchala/battery</code></p>
<p><strong>Current Imports:</strong></p>
<ul>
<li><p>Remember platform values are going to be always either async or streams.</p>
</li>
<li><p>Since we are going to call our battery percentage through a trigger like clicking a button. It is async value. Hence here are our imports:</p>
</li>
</ul>
<pre><code class="lang-dart"><span class="hljs-keyword">import</span> <span class="hljs-string">'dart:async'</span>; <span class="hljs-comment">// As battery value is async</span>
<span class="hljs-keyword">import</span> <span class="hljs-string">'package:flutter/material.dart'</span>;
<span class="hljs-keyword">import</span> <span class="hljs-string">'package:flutter/services.dart'</span>; <span class="hljs-comment">// For calling method channel</span>
</code></pre>
<p><strong>Initialize our Method Channel:</strong></p>
<ul>
<li>We can initialize our method channel in the <code>HomePage</code> class like this:</li>
</ul>
<pre><code class="lang-dart"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">_MyHomePageState</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">State</span>&lt;<span class="hljs-title">MyHomePage</span>&gt; </span>{

<span class="hljs-keyword">static</span> <span class="hljs-keyword">const</span> platform = MethodChannel(<span class="hljs-string">'com.harishkunchala/battery'</span>);
....
</code></pre>
<ul>
<li><p>Next, invoke a method on the method channel, specifying the concrete method to call using the <code>String</code> identifier <code>getBatteryLevel</code>.</p>
</li>
<li><p>The call might fail—for example, if the platform doesn't support the platform API (such as when running in a simulator), so wrap the <code>invokeMethod</code> call in a try-catch statement.</p>
</li>
</ul>
<pre><code class="lang-dart"><span class="hljs-comment">// Get Battery Level</span>
  <span class="hljs-built_in">String</span> _batteryLevel = <span class="hljs-string">'Unknown battery level.'</span>;

  Future&lt;<span class="hljs-keyword">void</span>&gt; _getBatteryLevel() <span class="hljs-keyword">async</span> {
    <span class="hljs-built_in">String</span> batteryLevel;

    <span class="hljs-keyword">try</span> {
      <span class="hljs-keyword">final</span> result = <span class="hljs-keyword">await</span> platform.invokeMethod&lt;<span class="hljs-built_in">int</span>&gt;(<span class="hljs-string">'getBatteryLevel'</span>);
      batteryLevel = <span class="hljs-string">'Battery level at <span class="hljs-subst">$result</span> %'</span>;
    } <span class="hljs-keyword">on</span> PlatformException <span class="hljs-keyword">catch</span> (e) {
      batteryLevel = <span class="hljs-string">"Failed to get battery level: '<span class="hljs-subst">${e.message}</span>'."</span>;
    }

    setState(() {
      _batteryLevel = batteryLevel;
    });
  }
</code></pre>
<p><strong>Update the build method:</strong> We'll create a simple UI with a basic column with a button and text to show the battery percentage.</p>
<pre><code class="lang-dart">Widget build(BuildContext context) {
    <span class="hljs-keyword">return</span> Scaffold(
      body: Center(
        child: Column(
          children: [
            ElevatedButton(
                onPressed: _getBatteryLevel,
                child: <span class="hljs-keyword">const</span> Text(<span class="hljs-string">'Get Battery Level'</span>)),
            <span class="hljs-keyword">const</span> SizedBox(height: <span class="hljs-number">20</span>),
            Text(_batteryLevel),
          ],
        ),
      ),
    );
  }
</code></pre>
<h3 id="heading-step-3-add-an-android-specific-implementation">Step 3: Add an Android Specific Implementation:</h3>
<ul>
<li><p>First open <code>android/</code> folder in Android Studio.</p>
</li>
<li><p>Navigate to Kotlin folder and open <code>MainActivity.kt</code></p>
</li>
<li><p>Inside our MainActivity define a String variable <code>CHANNEL</code> and set it to exactly what we used in our flutter:</p>
</li>
</ul>
<pre><code class="lang-kotlin"><span class="hljs-keyword">private</span> <span class="hljs-keyword">val</span> CHANNEL = <span class="hljs-string">"com.harishkunchala/battery"</span>;
</code></pre>
<ul>
<li>Also override <code>configureFlutterEngine</code> method and create a <code>MethodChannel</code> and call <code>setMethodCallHandler()</code>. Here's the entire code:</li>
</ul>
<pre><code class="lang-kotlin"><span class="hljs-keyword">package</span> com.example.battery_level_tutorial  

<span class="hljs-keyword">import</span> io.flutter.embedding.android.FlutterActivity  
<span class="hljs-keyword">import</span> io.flutter.embedding.engine.FlutterEngine  
<span class="hljs-keyword">import</span> io.flutter.plugin.common.MethodChannel  

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MainActivity</span>: <span class="hljs-type">FlutterActivity</span></span>() {  
    <span class="hljs-keyword">private</span>  <span class="hljs-keyword">val</span> CHANNEL = <span class="hljs-string">"com.harishkunchala/battery"</span>  

    <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">configureFlutterEngine</span><span class="hljs-params">(flutterEngine: <span class="hljs-type">FlutterEngine</span>)</span></span> {  
        <span class="hljs-keyword">super</span>.configureFlutterEngine(flutterEngine)  
        MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler{  
            call, result -&gt;  
            <span class="hljs-comment">// This method is invoked on the main thread  </span>
            <span class="hljs-comment">// TODO  </span>
        }  
    }  
}
</code></pre>
<ul>
<li><p>Add the Android Kotlin code that uses the Android battery APIs to retrieve the battery level. This code is exactly the same as you would write in a native Android app.</p>
</li>
<li><p>First let's add the needed imports at the top of the file:</p>
</li>
</ul>
<pre><code class="lang-kotlin"><span class="hljs-keyword">import</span> android.content.Context  
<span class="hljs-keyword">import</span> android.os.BatteryManager
</code></pre>
<ul>
<li>Now add the following method below in the <code>MainActivity</code> class below <code>configureFlutterEngine()</code> method:</li>
</ul>
<pre><code class="lang-kotlin"><span class="hljs-keyword">private</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">getBatteryLevel</span><span class="hljs-params">()</span></span>: <span class="hljs-built_in">Int</span> {  
    <span class="hljs-keyword">val</span> batteryLevel: <span class="hljs-built_in">Int</span>  
    <span class="hljs-keyword">val</span> batteryManager = getSystemService(Context.BATTERY_SERVICE) <span class="hljs-keyword">as</span> BatteryManager  
    batteryLevel = batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY)  

    <span class="hljs-keyword">return</span> batteryLevel  
}
</code></pre>
<p><strong>Call</strong> <code>setMethodCallHandler()</code>:</p>
<ul>
<li><p>We need to handle a single platform method, <code>getBatteryLevel()</code></p>
</li>
<li><p>so let's test for that in the call argument.</p>
</li>
<li><p>The implementation of this platform method calls the Android code written in the previous step.</p>
</li>
<li><p>It returns a response for both the success and error cases using the <code>result</code> argument.</p>
</li>
<li><p>If an unknown method is called, report that instead</p>
</li>
</ul>
<p>So here's our final <code>MethodChannle()</code>:</p>
<pre><code class="lang-kotlin">MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler {  
    <span class="hljs-comment">// This method is invoked in the main thread  </span>
        call, result -&gt;  
    <span class="hljs-keyword">if</span> (call.method == <span class="hljs-string">"getBatteryLevel"</span>) {  
        <span class="hljs-keyword">val</span> batteryLevel = getBatteryLevel()  

        <span class="hljs-keyword">if</span> (batteryLevel != -<span class="hljs-number">1</span>) {  
            result.success(batteryLevel)  
        } <span class="hljs-keyword">else</span> {  
            result.error(<span class="hljs-string">"UNAVAILABLE"</span>, <span class="hljs-string">"Battery level not available"</span>, <span class="hljs-literal">null</span>)  
        }  
    } <span class="hljs-keyword">else</span> {  
        result.notImplemented()  
    }  
}
</code></pre>
<h3 id="heading-step-4-add-an-ios-platform-specific-implementation">Step 4: Add an iOS platform-specific implementation</h3>
<p>Start by opening the iOS host portion of your Flutter app in Xcode:</p>
<ol>
<li><p>Start Xcode.</p>
</li>
<li><p>Select the menu item <strong>File &gt; Open...</strong>.</p>
</li>
<li><p>Navigate to the directory holding your Flutter app, and select the <strong>ios</strong> folder inside it. Click <strong>OK</strong>.</p>
</li>
</ol>
<p>Add support for Swift in the standard template setup that uses Objective-C:</p>
<ol>
<li><p><strong>Expand Runner &gt; Runner</strong> in the Project navigator.</p>
</li>
<li><p>Open the file <code>AppDelegate.swift</code> located under <strong>Runner &gt; Runner</strong> in the Project navigator.</p>
</li>
</ol>
<h4 id="heading-steps">Steps:</h4>
<ul>
<li>Override the <code>application:didFinishLaunchingWithOptions:</code> function and create a <code>FlutterMethodChannel</code> tied to the channel name <code>com.harishkunchala/battery</code>:</li>
</ul>
<pre><code class="lang-swift"><span class="hljs-keyword">import</span> Flutter
<span class="hljs-keyword">import</span> UIKit

<span class="hljs-meta">@UIApplicationMain</span>
<span class="hljs-meta">@objc</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">AppDelegate</span>: <span class="hljs-title">FlutterAppDelegate</span> </span>{
  <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">application</span><span class="hljs-params">(
    <span class="hljs-number">_</span> application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: <span class="hljs-keyword">Any</span>]?)</span></span> -&gt; <span class="hljs-type">Bool</span> {

    <span class="hljs-keyword">let</span> controller : <span class="hljs-type">FlutterViewController</span> = window?.rootViewController <span class="hljs-keyword">as</span>! <span class="hljs-type">FlutterViewController</span>
    <span class="hljs-keyword">let</span> batteryChannel = <span class="hljs-type">FlutterMethodChannel</span>(name: <span class="hljs-string">"com.harishkunchala/battery"</span>,
                                              binaryMessenger: controller.binaryMessenger)
    batteryChannel.setMethodCallHandler({
      (call: <span class="hljs-type">FlutterMethodCall</span>, result: @escaping <span class="hljs-type">FlutterResult</span>) -&gt; <span class="hljs-type">Void</span> <span class="hljs-keyword">in</span>
      <span class="hljs-comment">// This method is invoked on the UI thread.</span>
      <span class="hljs-comment">// Handle battery messages.</span>
    })

    <span class="hljs-type">GeneratedPluginRegistrant</span>.register(with: <span class="hljs-keyword">self</span>)
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">super</span>.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
}
</code></pre>
<ul>
<li>Next let's create a method <code>receiveBatteryLevel()</code> that's retrieve iOS battery level. So add the following code at the bottom of <code>AppDelegate.swift</code></li>
</ul>
<pre><code class="lang-swift"><span class="hljs-keyword">private</span> <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">receiveBatteryLevel</span><span class="hljs-params">(result: FlutterResult)</span></span> {
    <span class="hljs-keyword">let</span> device = <span class="hljs-type">UIDevice</span>.current
    device.isBatteryMonitoringEnabled = <span class="hljs-literal">true</span>
    <span class="hljs-keyword">if</span> device.batteryState == <span class="hljs-type">UIDevice</span>.<span class="hljs-type">BatteryState</span>.unknown {
        result(<span class="hljs-type">FlutterError</span>(code: <span class="hljs-string">"UNAVAILABLE"</span>, message: <span class="hljs-string">"Battery level not available."</span>, details: <span class="hljs-literal">nil</span>))
    } <span class="hljs-keyword">else</span> {
        result(<span class="hljs-type">Int</span>(device.batteryLevel * <span class="hljs-number">100</span>))
    }
}
</code></pre>
<ul>
<li><p>Finally complete the <code>setMethodCallHandler()</code> method added earlier.</p>
</li>
<li><p>We need to handle a single platform method <code>getBatteryLevel()</code>, so test for that in the <code>call</code> argument.</p>
</li>
<li><p>The implementation of this platform method calls the iOS code written in the previous step. If an unknown method is called, report that instead:</p>
</li>
</ul>
<pre><code class="lang-swift">batteryChannel.setMethodCallHandler({
      (call: <span class="hljs-type">FlutterMethodCall</span>, result: @escaping <span class="hljs-type">FlutterResult</span>) -&gt; <span class="hljs-type">Void</span> <span class="hljs-keyword">in</span>
      <span class="hljs-comment">// This method is invoked on the UI thread.</span>
        <span class="hljs-keyword">guard</span> call.method == <span class="hljs-string">"getBatterLevel"</span> <span class="hljs-keyword">else</span> {
            result(<span class="hljs-type">FlutterMethodNotImplemented</span>)
            <span class="hljs-keyword">return</span>
        }
        <span class="hljs-keyword">self</span>?.receiveBatteryLevel(result: result)
    })
</code></pre>
<p>You should now be able to run the app on iOS. <strong>Note:</strong> If you are using iOS simulator, it doesn't support battery APIs, and the app displays 'Battery level not available'.</p>
<h3 id="heading-testing-the-code">Testing the code:</h3>
<p>Perfect, for now let's test it on an actual Android device. Here's the output:</p>
<p><img src="https://media1.giphy.com/media/v1.Y2lkPTc5MGI3NjExYm8xMzlzMGF6OWh5ODI2YnRwbWtmcWRhbWU2bThwZjJlNHBic296cCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/6s3lzKZoCFymz3kB1B/giphy.gif" alt /></p>
<p>Finally our app is working perfectly. You can find the entire source code for the app here: <a target="_blank" href="https://github.com/khkred/battery_level_tutorial">battery_level_tutorial</a></p>
<p>Happy Coding 🐦</p>
]]></content:encoded></item><item><title><![CDATA[How to use Dart FFI for writing C code]]></title><description><![CDATA[Foreign Function Interface (FFI) allows a program written in one language to call functions or services written in another language. In Dart FFI is used to…]]></description><link>https://harishkunchala.com/how-to-use-dart-ffi-for-writing-c-code</link><guid isPermaLink="true">https://harishkunchala.com/how-to-use-dart-ffi-for-writing-c-code</guid><category><![CDATA[Dart]]></category><category><![CDATA[FFI]]></category><category><![CDATA[interoperability]]></category><dc:creator><![CDATA[Harish Kunchala]]></dc:creator><pubDate>Tue, 16 Jul 2024 20:58:42 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1721163401847/46eadf66-ffd1-43f3-9a0a-3a0251c5ef51.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3 id="heading-what-is-ffi">What is FFI?</h3>
<ul>
<li><p>Foreign Function Interface (FFI) allows a program written in one language to call functions or services written in another language.</p>
</li>
<li><p>In Dart FFI is used to call native C functions and libraries, thus enhancing the app's capabilities by utilizing existing code or libraries.</p>
</li>
<li><p>Dart FFI can be used with <mark>any language that can expose a C-compatible API</mark> like C, C++, Rust and to some extent even Python3.</p>
</li>
</ul>
<p><strong>Use Cases:</strong></p>
<ul>
<li><p>Reuse existing libraries.</p>
</li>
<li><p>Performing tasks that require high performance.</p>
</li>
<li><p>Accessing platform-specific features not exposed by Flutter.</p>
</li>
</ul>
<p>Let's create a basic FFI.</p>
<h3 id="heading-source-code">Source Code:</h3>
<p>You can find the source code for here: <a target="_blank" href="https://github.com/khkred/ffi_factorial">ffi_factorial</a></p>
<h2 id="heading-dart-ffi-factorial-app">Dart FFI Factorial App:</h2>
<p>We'll create two basic Dart Apps that runs on Windows, Linux and Mac as a CLI app to get factorial.</p>
<ul>
<li><p>The first app will have give us factorial of a static number like 5 or 10.</p>
</li>
<li><p>The second app will provide us a factorial based on the user input.</p>
</li>
</ul>
<p>Also you can find the source code for the app here: <a target="_blank" href="https://github.com/khkred/ffi_factorial">ffi_factorial</a></p>
<h3 id="heading-step-1-create-the-dart-app">Step 1. Create the Dart App:</h3>
<p>Let's create a new dart project:</p>
<pre><code class="lang-bash">dart create ffi_factorial
<span class="hljs-built_in">cd</span> ffi_factorial/bin/
</code></pre>
<p>Now if we look at the files inside the Dart project we get this:</p>
<pre><code class="lang-bash">ls
ffi_factorial.dart
</code></pre>
<h3 id="heading-step-2-create-factorialc-inside-our-bin">Step 2. Create <code>factorial.c</code> inside our bin/</h3>
<p>Let's write our C code (e.g., <code>factorial.c</code> ) containing the functions you want to access from Dart. Remember to write inside our bin/ folder for easy access.</p>
<pre><code class="lang-c"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;stdio.h&gt;</span></span>
<span class="hljs-comment">// factorial.c using memoization to get the time complexity to O(n)</span>
<span class="hljs-comment">// Array to store memoized results (adjust size as needed)</span>
<span class="hljs-keyword">int</span> memo[<span class="hljs-number">100</span>];

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">factorial_memo</span><span class="hljs-params">(<span class="hljs-keyword">int</span> n)</span> </span>{
    <span class="hljs-keyword">if</span> (n == <span class="hljs-number">0</span>) {
        <span class="hljs-keyword">return</span> <span class="hljs-number">1</span>;
    } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (memo[n] != <span class="hljs-number">0</span>) {
        <span class="hljs-keyword">return</span> memo[n]; <span class="hljs-comment">// Return memoized result</span>
    } <span class="hljs-keyword">else</span> {
        memo[n] = n * factorial_memo(n - <span class="hljs-number">1</span>);
        <span class="hljs-keyword">return</span> memo[n];
    }
}
</code></pre>
<h3 id="heading-step-3-create-dynamic-library">Step 3. Create Dynamic library.</h3>
<p>Now if we want to access our C Code inside our Dart function. We need to create a dynamic library.</p>
<p>Now since each operating system is different we'll have to create separate dynamic library files for each OS.</p>
<p><strong>Operating System and Library Name:</strong></p>
<ul>
<li><p><strong>macOS:</strong> The library file will be named <code>libfactorial.dylib</code>.</p>
</li>
<li><p><strong>Linux:</strong> The library file will be named <a target="_blank" href="http://libfactorial.so"><code>libfactorial.so</code></a>.</p>
</li>
<li><p><strong>Windows:</strong> The library file will be named <code>factorial.dll</code>.</p>
</li>
</ul>
<p><strong>Compile your C code into a dynamic library:</strong></p>
<ul>
<li><p><strong>Linux:</strong> <code>gcc -shared -o</code> <a target="_blank" href="http://libfactorial.so"><code>libfactorial.so</code></a> <code>factorial.c -fPIC</code></p>
</li>
<li><p><strong>Windows:</strong> <code>gcc -shared -o factorial.dll factorial.c</code></p>
</li>
<li><p><strong>macOS:</strong> <code>gcc -dynamiclib -o libfactorial.dylib factorial.c</code></p>
</li>
</ul>
<p><mark>Note: When I say different OS, I mean target Operating Systems, not where you are compiling the code from.</mark></p>
<p>For instance although I am writing all of this code in macOS if I want it to run on all 3 platforms, then I'll have to create all 3 files.</p>
<p>So I am running all three commands:</p>
<pre><code class="lang-bash">gcc -dynamiclib -o libfactorial.dylib factorial.c
gcc -shared -o factorial.dll factorial.c
gcc -shared -o libfactorial.so factorial.c -fPIC
</code></pre>
<p>Now here are the current files:</p>
<pre><code class="lang-bash">ls
factorial.c        factorial.dll        ffi_factorial.dart    libfactorial.dylib    libfactorial.so
</code></pre>
<h3 id="heading-step-4-call-native-functions-from-our-ffifactorialdart">Step 4. Call Native Functions from our <code>ffi_factorial.dart</code>:</h3>
<p>Open <code>bin/my_ffi_project.dart</code> and add the following imports:</p>
<pre><code class="lang-dart"><span class="hljs-keyword">import</span> <span class="hljs-string">'dart:ffi'</span>;
<span class="hljs-keyword">import</span> <span class="hljs-string">'dart:io'</span>;
</code></pre>
<ol>
<li>Now within the <code>main()</code> load the dynamic libraries:</li>
</ol>
<p>As you can see we are ensuring that the correct file is opened in correct os</p>
<pre><code class="lang-dart"><span class="hljs-comment">// 1. Load the Dynamic Library (dylib)</span>
<span class="hljs-comment">// Ensure to use the correct extension for your platform (.dll for Windows, .dylib for macOS, .so for Linux)</span>
  <span class="hljs-keyword">final</span> dylib = Platform.isWindows
      ? DynamicLibrary.open(<span class="hljs-string">'libfactorial.dll'</span>)
      : Platform.isMacOS
          ? DynamicLibrary.open(<span class="hljs-string">'libfactorial.dylib'</span>)
          : DynamicLibrary.open(<span class="hljs-string">'libfactorial.so'</span>); <span class="hljs-comment">// Linux</span>
</code></pre>
<ol start="2">
<li>Create typedefs to represent the the C function signatures in Dart:</li>
</ol>
<p>Create them on top of our <code>main()</code>.</p>
<pre><code class="lang-dart"><span class="hljs-comment">// 2. Define FFI Function Signature</span>
<span class="hljs-keyword">typedef</span> NativeFactorialMemoFunc = Int32 <span class="hljs-built_in">Function</span>(Int32 n);
<span class="hljs-keyword">typedef</span> DartFactorialMemoFunc = <span class="hljs-built_in">int</span> <span class="hljs-built_in">Function</span>(<span class="hljs-built_in">int</span> n);
</code></pre>
<ol start="3">
<li>Use the <code>lookup</code> method to get a reference to the C function within the loaded library:</li>
</ol>
<pre><code class="lang-dart">  <span class="hljs-comment">// 3. Look Up the Native Function</span>
  <span class="hljs-keyword">final</span> DartFactorialMemoFunc nativeFactorialMemo =
      dylib.lookupFunction&lt;NativeFactorialMemoFunc, DartFactorialMemoFunc&gt;(<span class="hljs-string">'factorial_memo'</span>);
</code></pre>
<ol start="4">
<li>Finally call the native function</li>
</ol>
<pre><code class="lang-dart"><span class="hljs-comment">// 4. Call the Native Function (from Dart)</span>
  <span class="hljs-keyword">final</span> result = nativeFactorialMemo(<span class="hljs-number">5</span>);
  <span class="hljs-built_in">print</span>(<span class="hljs-string">'Factorial of 5 is: <span class="hljs-subst">$result</span>'</span>); <span class="hljs-comment">// Output: 120</span>
</code></pre>
<p>Here's the entire code:</p>
<pre><code class="lang-dart"><span class="hljs-keyword">import</span> <span class="hljs-string">'dart:ffi'</span>;
<span class="hljs-keyword">import</span> <span class="hljs-string">'dart:io'</span>;

<span class="hljs-comment">// 2. Define FFI Function Signature</span>
<span class="hljs-keyword">typedef</span> NativeFactorialMemoFunc = Int32 <span class="hljs-built_in">Function</span>(Int32 n);
<span class="hljs-keyword">typedef</span> DartFactorialMemoFunc = <span class="hljs-built_in">int</span> <span class="hljs-built_in">Function</span>(<span class="hljs-built_in">int</span> n);

<span class="hljs-keyword">void</span> main(<span class="hljs-built_in">List</span>&lt;<span class="hljs-built_in">String</span>&gt; arguments) {

  <span class="hljs-comment">// 1. Load the Dynamic Library (dylib)</span>
  <span class="hljs-comment">// Ensure to use the correct extension for your platform (.dll for Windows, .dylib for macOS, .so for Linux)</span>
  <span class="hljs-keyword">final</span> dylib = Platform.isWindows
      ? DynamicLibrary.open(<span class="hljs-string">'libfactorial.dll'</span>)
      : Platform.isMacOS
          ? DynamicLibrary.open(<span class="hljs-string">'libfactorial.dylib'</span>)
          : DynamicLibrary.open(<span class="hljs-string">'libfactorial.so'</span>); <span class="hljs-comment">// Linux</span>

  <span class="hljs-comment">// 3. Look Up the Native Function</span>
  <span class="hljs-keyword">final</span> DartFactorialMemoFunc nativeFactorialMemo =
      dylib.lookupFunction&lt;NativeFactorialMemoFunc, DartFactorialMemoFunc&gt;(<span class="hljs-string">'factorial_memo'</span>);

  <span class="hljs-comment">// 4. Call the Native Function (from Dart)</span>
  <span class="hljs-keyword">final</span> result = nativeFactorialMemo(<span class="hljs-number">5</span>);
  <span class="hljs-built_in">print</span>(<span class="hljs-string">'Factorial of 5 is: <span class="hljs-subst">$result</span>'</span>); <span class="hljs-comment">// Output: 120</span>
}
</code></pre>
<p>So if we run the app. We get the following output:</p>
<pre><code class="lang-bash">dart run ffi_factorial.dart
<span class="hljs-comment"># Factorial of 5 is: 120</span>
</code></pre>
<h3 id="heading-factorial-using-user-input">Factorial Using User Input:</h3>
<p>Let's create a new file named <code>factorial_user_input.dart</code> inside our <code>bin/</code></p>
<pre><code class="lang-bash">code factorial_user_input.dart
</code></pre>
<p>Go ahead and copy the code from our existing <code>ffi_factorial.dart</code>.</p>
<p>Now since we want to get the value from user terminal: We'll use <code>stdin.readLineSync()</code>. Here is our new code:</p>
<pre><code class="lang-dart"><span class="hljs-keyword">import</span> <span class="hljs-string">'dart:ffi'</span>;
<span class="hljs-keyword">import</span> <span class="hljs-string">'dart:io'</span>;

<span class="hljs-comment">// 2. Define FFI Function Signature</span>
<span class="hljs-keyword">typedef</span> NativeFactorialMemoFunc = Int32 <span class="hljs-built_in">Function</span>(Int32 n);
<span class="hljs-keyword">typedef</span> DartFactorialMemoFunc = <span class="hljs-built_in">int</span> <span class="hljs-built_in">Function</span>(<span class="hljs-built_in">int</span> n);

<span class="hljs-keyword">void</span> main(<span class="hljs-built_in">List</span>&lt;<span class="hljs-built_in">String</span>&gt; arguments) {

  <span class="hljs-comment">// 1. Load the Dynamic Library (dylib)</span>
  <span class="hljs-comment">// Ensure to use the correct extension for your platform (.dll for Windows, .dylib for macOS, .so for Linux)</span>
  <span class="hljs-keyword">final</span> dylib = Platform.isWindows
      ? DynamicLibrary.open(<span class="hljs-string">'libfactorial.dll'</span>)
      : Platform.isMacOS
          ? DynamicLibrary.open(<span class="hljs-string">'libfactorial.dylib'</span>)
          : DynamicLibrary.open(<span class="hljs-string">'libfactorial.so'</span>); <span class="hljs-comment">// Linux</span>

  <span class="hljs-comment">// 3. Look Up the Native Function</span>
  <span class="hljs-keyword">final</span> DartFactorialMemoFunc nativeFactorialMemo =
      dylib.lookupFunction&lt;NativeFactorialMemoFunc, DartFactorialMemoFunc&gt;(<span class="hljs-string">'factorial_memo'</span>);

  <span class="hljs-comment">// Get user input</span>
  <span class="hljs-built_in">print</span>(<span class="hljs-string">'Enter a number to calculate its factorial: '</span>);
  <span class="hljs-keyword">final</span> input = stdin.readLineSync();

  <span class="hljs-keyword">if</span> (input != <span class="hljs-keyword">null</span>) {
    <span class="hljs-keyword">final</span> number = <span class="hljs-built_in">int</span>.tryParse(input);
    <span class="hljs-keyword">if</span> (number != <span class="hljs-keyword">null</span>) {
      <span class="hljs-comment">// 4. Call the Native Function (from Dart)</span>
      <span class="hljs-keyword">final</span> result = nativeFactorialMemo(number);
      <span class="hljs-built_in">print</span>(<span class="hljs-string">'Factorial of <span class="hljs-subst">$number</span> is: <span class="hljs-subst">$result</span>'</span>); <span class="hljs-comment">// Output: 120 (for 5)</span>
    } <span class="hljs-keyword">else</span> {
      <span class="hljs-built_in">print</span>(<span class="hljs-string">'Please enter a valid integer.'</span>);
    }
  } <span class="hljs-keyword">else</span> {
    <span class="hljs-built_in">print</span>(<span class="hljs-string">'Input cannot be null.'</span>);
  }
}
</code></pre>
<p>Here's the output:</p>
<pre><code class="lang-bash">dart run factorial_user_input.dart
<span class="hljs-comment"># Enter a number to calculate its factorial:</span>
<span class="hljs-comment"># 23</span>
<span class="hljs-comment"># Factorial of 23 is: 862453760</span>
</code></pre>
<p>Perfect. So this covers our introduction to FFI. I'll keep writing more about FFI and platform channels as these are some of the most interesting aspects of the flutter app. So please subscribe to my blog for more interesting Flutter posts.</p>
<p>And Happy Coding 🐦</p>
]]></content:encoded></item><item><title><![CDATA[Unit Testing in Flutter With Examples]]></title><description><![CDATA[You can find the source code for the examples here: Github Link A unit test is a test that verifies the behavior of an isolated piece of code. It can be…]]></description><link>https://harishkunchala.com/unit-testing-in-flutter-with-examples</link><guid isPermaLink="true">https://harishkunchala.com/unit-testing-in-flutter-with-examples</guid><category><![CDATA[Flutter]]></category><category><![CDATA[unit testing]]></category><dc:creator><![CDATA[Harish Kunchala]]></dc:creator><pubDate>Sat, 13 Jul 2024 03:09:13 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1720839207570/0d9cf16c-1131-42ca-9469-70b175c19907.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>You can find the source code for the examples here: <a target="_blank" href="https://github.com/khkred/flutter_testing_examples">Github Link</a></p>
<h3 id="heading-what-is-a-unit-test">What is a Unit Test?</h3>
<p>A unit test is a test that verifies the behavior of an isolated piece of code. It can be used to test a single function, method or class.</p>
<p><mark>Remember: "unit" is another name for a function, method or a class</mark></p>
<p>Let's start with the basic Counter app we get as the default app in Flutter.</p>
<h2 id="heading-example-1-basic-counter-app">Example 1: Basic Counter App:</h2>
<h3 id="heading-actual-code">Actual Code:</h3>
<p>This is the default app we get with flutter.</p>
<p>Initially separate the counter code from the UI code. So we just put it in a file named <code>counter.dart</code>:</p>
<pre><code class="lang-dart"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Counter</span> </span>{  
  <span class="hljs-built_in">int</span> _counter = <span class="hljs-number">0</span>;  

  <span class="hljs-built_in">int</span> <span class="hljs-keyword">get</span> count =&gt; _counter;  

  <span class="hljs-keyword">void</span> incrementCount() {  
    _counter += <span class="hljs-number">1</span>;  
  }  
}
</code></pre>
<h3 id="heading-testing">Testing:</h3>
<ul>
<li><p>Now we can write a unit test for this in a file named <code>counter_test.dart</code>.</p>
</li>
<li><p><mark>As for the name convention it always must end in </mark> <code>_test.dart</code> <mark> with the start being any name.</mark></p>
</li>
<li><p>In order to test. We'll always have to import <code>'package:flutter_test/flutter_test.dart';</code></p>
</li>
</ul>
<p>Tests are defined using the top-level <code>test</code> functions and you can check if the results are correct using the top-level <code>expect</code> function. So we can call a <code>test(description,body)</code> function inside our <code>main()</code>.</p>
<h3 id="heading-testdescription-body"><code>test(description, body)</code>:</h3>
<p><strong>Description:</strong> The standard convention when describing a test class is:</p>
<p><mark>GIVEN WHEN THEN</mark></p>
<p>For example in the current scenario we want to check if the count value is 0 when the counter class is instantiated.</p>
<p>So we'll write: <em>Given counter class when it is instantiated then the value of the count should be 0.</em></p>
<p><strong>Body</strong>: In here we are going to do three things: <mark>ARRANGE ACT ASSERT</mark></p>
<p>ARRANGE: We will declare an object of the class</p>
<p>ACT: We will get the value of the count</p>
<p>ASSERT: We will check if the value is 0</p>
<h4 id="heading-testing-code">Testing Code:</h4>
<h5 id="heading-count-test">Count Test:</h5>
<p>And here's the final <code>counter_test.dart</code>:</p>
<pre><code class="lang-dart"><span class="hljs-keyword">import</span> <span class="hljs-string">'package:basic_counter/counter.dart'</span>;  
<span class="hljs-keyword">import</span> <span class="hljs-string">'package:flutter_test/flutter_test.dart'</span>;  
<span class="hljs-keyword">void</span> main() {  
  <span class="hljs-comment">// given when then  </span>
  test(<span class="hljs-string">'Given counter class when it is instantiated then value of the count should be 0'</span>, (){  
    <span class="hljs-comment">// Arrange  </span>
    <span class="hljs-keyword">final</span> Counter counter = Counter();  
    <span class="hljs-comment">// Act  </span>
    <span class="hljs-keyword">final</span> val = counter.count;  
    <span class="hljs-comment">// Assert  </span>
    expect(val, <span class="hljs-number">0</span>);  
  });  
}
</code></pre>
<p>We can test the code using the following command:</p>
<pre><code class="lang-bash">flutter <span class="hljs-built_in">test</span>
</code></pre>
<h5 id="heading-incrementcount-test"><code>incrementCount()</code> test</h5>
<p>We can also test the <code>incrementCount()</code>: using the following code:</p>
<pre><code class="lang-dart"> <span class="hljs-comment">// given when then  </span>
  test(<span class="hljs-string">'Given counter class when incrementCount() is called then the value of the count should be 1'</span>,(){  
    <span class="hljs-comment">// Arrange  </span>
    <span class="hljs-keyword">final</span> Counter counter = Counter();  
    <span class="hljs-comment">// Act  </span>
    counter.incrementCount();  
    <span class="hljs-keyword">final</span> val = counter.count;  

    <span class="hljs-comment">// Assert  </span>
    expect(val, <span class="hljs-number">1</span>);  
  });  
}
</code></pre>
<h5 id="heading-grouping-tests">Grouping Tests</h5>
<p>Since both of the tests are for the <code>Counter</code> class. we can group them together like this:</p>
<pre><code class="lang-dart"><span class="hljs-comment">// Given When Then  </span>
group(<span class="hljs-string">'Test start, increment'</span>, () {  
  <span class="hljs-comment">// Arrange  </span>
  <span class="hljs-keyword">final</span> Counter counter = Counter();  
  test(  
      <span class="hljs-string">'Given counter class when it is instantiated then value of the count should be 0'</span>,  
      () {  

    <span class="hljs-comment">// Act  </span>
    <span class="hljs-keyword">final</span> val = counter.count;  
    <span class="hljs-comment">// Assert  </span>
    expect(val, <span class="hljs-number">0</span>);  
  });  

  <span class="hljs-comment">// given when then  </span>
  test(  
      <span class="hljs-string">'Given counter class when incrementCount() is called then the value of the count should be 1'</span>,  
      () {  
    <span class="hljs-comment">// Act  </span>
    counter.incrementCount();  
    <span class="hljs-keyword">final</span> val = counter.count;  

    <span class="hljs-comment">// Assert  </span>
    expect(val, <span class="hljs-number">1</span>);  
  });  
});
</code></pre>
<p>To run all the tests you put in a <code>group</code>, run the following command:</p>
<pre><code class="lang-bash">flutter <span class="hljs-built_in">test</span> --plain-name <span class="hljs-string">"Test start, increment"</span>
</code></pre>
<h3 id="heading-pre-test-and-post-test">Pre-test and Post-test:</h3>
<p>Imagine if we added another function to <code>Counter</code> called <code>decrementCounter()</code>:</p>
<pre><code class="lang-dart"><span class="hljs-keyword">void</span> decrementCounter() {
    _counter--;
}
</code></pre>
<p>Now we'll have to again add another test:</p>
<pre><code class="lang-dart">test(  
    <span class="hljs-string">'Given counter class when decrementCount() is called then the value of the count should be -1'</span>,  
    () {  

  counter.decrementCount();  
  <span class="hljs-keyword">final</span> val = counter.count;  

  expect(val, <span class="hljs-number">-1</span>);  
});
</code></pre>
<p><mark>The problem is that the above test will fail because in the incrementCount test we've increased the value to 1. So now val will be 0. This is why Flutter provides us with pre-test and post-test functions.</mark></p>
<h4 id="heading-pre-test-functions">Pre-test Functions:</h4>
<p>There are two pretest functions:</p>
<ul>
<li><p><code>setUp()</code></p>
</li>
<li><p><code>setUpAll()</code></p>
</li>
</ul>
<h5 id="heading-setup"><code>setUp()</code>:</h5>
<p>This function will run before every test. So let's say we have 3 tests:</p>
<p>Then it'll be <code>setUp --&gt; test --&gt; setUp --&gt; test --&gt; setUp --&gt; test</code></p>
<p>So in order to solve the above problem of running multiple tests with the same instance of the Counter() we can declare it like this:</p>
<pre><code class="lang-dart"><span class="hljs-keyword">void</span> main() {
    <span class="hljs-keyword">late</span> Counter counter;
    setUp((){
    counter = Counter();
    });

    test()...
....
}
</code></pre>
<h5 id="heading-setupall"><code>setUpAll()</code>:</h5>
<p>This function will run only once.</p>
<p>So it'll be: <code>setUpAll --&gt; test --&gt; test --&gt; test</code></p>
<h4 id="heading-post-test-functions">Post-test Functions:</h4>
<p>There are two post-test functions:</p>
<ul>
<li><p><code>tearDown()</code></p>
</li>
<li><p><code>tearDownAll()</code></p>
</li>
</ul>
<h5 id="heading-teardown"><code>tearDown()</code>:</h5>
<p>The function will run after every test.</p>
<p><code>test -&gt; tearDown -&gt; test -&gt; tearDown</code></p>
<h5 id="heading-teardownall"><code>tearDownAll()</code>:</h5>
<p>The function will only run once after all the tests are done.</p>
<p><code>test -&gt; test -&gt; test -&gt; tearDownAll</code></p>
<p>And thanks to using the pre-test functions. We are able to run all the tests successfully. You can find the source code for the project here: <a target="_blank" href="https://github.com/khkred/flutter_testing_examples/tree/main/unit_testing/basic_counter">Github Link</a></p>
<h2 id="heading-example-2-http-user-app">Example 2: HTTP User App</h2>
<p>In this app we are goin to test some fundamental network calls using <code>http</code> from pub.dev.</p>
<p>We are going to call a user from <a target="_blank" href="https://jsonplaceholder.typicode.com/users/1">JsonPlaceHolder</a> site.</p>
<p>Imagine we have define a basic <code>User</code> Model:</p>
<pre><code class="lang-dart"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">User</span> </span>{  
  <span class="hljs-built_in">int</span> id;  
  <span class="hljs-built_in">String</span> name;  
  <span class="hljs-built_in">String</span> username;  
  <span class="hljs-built_in">String</span> email;  
  <span class="hljs-built_in">String</span> phone;
  }
</code></pre>
<h4 id="heading-getuser">getUser():</h4>
<p>Now we can define a <code>UserRepository</code> class where we can get the user from network from jsonPlaceholder:</p>
<pre><code class="lang-dart"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">UserRepository</span> </span>{  
  Future&lt;User&gt; getUser() <span class="hljs-keyword">async</span> {  
    <span class="hljs-keyword">final</span> response = <span class="hljs-keyword">await</span> http.<span class="hljs-keyword">get</span>(  
      <span class="hljs-built_in">Uri</span>.parse(<span class="hljs-string">'https://jsonplaceholder.typicode.com/users/1'</span>),  
    );  

    <span class="hljs-keyword">if</span> (response.statusCode == <span class="hljs-number">200</span>) {  
      <span class="hljs-keyword">final</span> responseBody = jsonDecode(response.body);  
      <span class="hljs-keyword">return</span> User.fromJson(responseBody);  
    }  
    <span class="hljs-keyword">throw</span> Exception(<span class="hljs-string">'Some Error Occurred'</span>);  
  }  
}
</code></pre>
<h3 id="heading-testing-1">Testing:</h3>
<p>We have multiple testing scenarios</p>
<h4 id="heading-test-if-it-returns-an-object-of-the-type-isuser">Test if it returns an object of the type isUser</h4>
<pre><code class="lang-dart"><span class="hljs-keyword">void</span> main() {  
  <span class="hljs-keyword">late</span> UserRepository userRepository;  
  <span class="hljs-comment">// Pre-test function  </span>
  setUp(() {  
    userRepository = UserRepository();  
  });  
  group(<span class="hljs-string">'User Repository -'</span>, () {  
    group(<span class="hljs-string">'getUser Function -'</span>, () {  
      test(  
          <span class="hljs-string">'given UserRepository class when getUser function is called and status code is 200 then the returned object should be a User Model'</span>,  
          () <span class="hljs-keyword">async</span> {  
        <span class="hljs-comment">// Act  </span>
        <span class="hljs-keyword">final</span> user = <span class="hljs-keyword">await</span> userRepository.getUser();  

        <span class="hljs-comment">// Assert  </span>
        expect(user, isA&lt;User&gt;());  
      });  
    });  
  });  
}
</code></pre>
<p><mark>If you look at the </mark> <code>expect()</code> <mark> The way we check if it is an object is by using </mark> <code>isA&lt;User&gt;()</code> <mark> function.</mark></p>
<h4 id="heading-test-if-it-returns-an-exception-when-the-status-code-is-not-200">Test if it returns an Exception when the status code is not 200</h4>
<pre><code class="lang-dart">test(  
    <span class="hljs-string">'given userRepository class when getUser function is called and the status code is not 200 then the function throws an exception'</span>,  
    () <span class="hljs-keyword">async</span> {  
  <span class="hljs-comment">// Act  </span>
  <span class="hljs-keyword">final</span> user = <span class="hljs-keyword">await</span> userRepository.getUser();  

  <span class="hljs-comment">// Assert  </span>
  expect(user, throwsException);  
});
</code></pre>
<p><mark>We can check for an exception using </mark> <code>throwsException</code></p>
<p>But the problems is when we run it. The test it is obviously going to fail because the status code is going to be 200. So how do we test the exception test block ?</p>
<p>We are going to use external packages for testing. Some of the best ones are <a target="_blank" href="https://pub.dev/packages/mockito">mockito</a> and <a target="_blank" href="https://pub.dev/packages/mocktail">mocktail</a>.</p>
<p>In this scenario we are going to use mocktail.</p>
<h3 id="heading-dependency-injection-for-testing">Dependency Injection for Testing:</h3>
<p>If we take a look at our <a target="_blank" href="https://github.com/khkred/flutter_testing_examples/blob/main/unit_testing/users_http_test/lib/user_repository.dart">getUser()</a> function. We see that it is dependent on <code>http</code> package.</p>
<p><mark>So whenever there is an external dependency we need to get control over them so that we can test them out properly. This is basically dependency injection.</mark></p>
<p>Since our main dependency is http. Let's put in the constructor so that we can inject it from anywhere so we are going to change the <code>UserRepository</code> to this</p>
<pre><code class="lang-dart"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">UserRepository</span> </span>{  
  <span class="hljs-keyword">final</span> http.Client client;  

  UserRepository(<span class="hljs-keyword">this</span>.client);  

  Future&lt;User&gt; getUser() <span class="hljs-keyword">async</span> {  
    <span class="hljs-keyword">final</span> response = <span class="hljs-keyword">await</span> client.<span class="hljs-keyword">get</span>(  
      <span class="hljs-built_in">Uri</span>.parse(<span class="hljs-string">'https://jsonplaceholder.typicode.com/users/1'</span>),  
    );  

    <span class="hljs-keyword">if</span> (response.statusCode == <span class="hljs-number">200</span>) {  
      <span class="hljs-keyword">final</span> responseBody = jsonDecode(response.body);  
      <span class="hljs-keyword">return</span> User.fromJson(responseBody);  
    }  
    <span class="hljs-keyword">throw</span> Exception(<span class="hljs-string">'Some Error Occurred'</span>);  
  }  
}
</code></pre>
<p>Since we are calling a constructor, we can switch the http client to a mock client if we want for testing purposes. A mock client allows us to modify its behavior.</p>
<p>For now we will be using the <a target="_blank" href="https://pub.dev/packages/mocktail">Mocktail</a> from <a target="_blank" href="https://pub.dev">pub.dev</a> as we can pass in a mock client.</p>
<p>We are going to add Mocktail to the dev dependency</p>
<pre><code class="lang-bash">flutter pub add -d mocktail
</code></pre>
<h3 id="heading-why-do-we-need-external-mock-packages">Why do we need external Mock packages?</h3>
<p>Imagine if we wanted to create a <code>MockHTTPClient</code> of <code>Client</code> from HTTP. We get the following:</p>
<p><img src="https://i.postimg.cc/vH25Sd5f/Screenshot-2024-07-12-at-7-09-17-PM.png" alt /></p>
<p>The problem is that we'll have to implement 10 missing overrides just to create the client which obviously is an extremely heavy task.</p>
<p>This is where Mocktail comes into play. So we can write the following code:</p>
<pre><code class="lang-dart"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MockHTTPClient</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Mock</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">Client</span> </span>{}
</code></pre>
<p>and it doesn't cause any errors.</p>
<h3 id="heading-using-mocktail-inside-the-test-function">Using Mocktail inside the test function.</h3>
<p>We have to use the <code>when()</code> to declare the expected output for the <code>mockHTTPClient</code></p>
<h5 id="heading-statuscode-200-test">StatusCode 200 test:</h5>
<pre><code class="lang-dart">test(  
          <span class="hljs-string">'given UserRepository class when getUser function is called and status code is 200 then the returned object should be a User Model'</span>,  
          () <span class="hljs-keyword">async</span> {  
        <span class="hljs-comment">// Arrange  </span>
        when(() =&gt; mockHTTPClient  
                .<span class="hljs-keyword">get</span>(<span class="hljs-built_in">Uri</span>.parse(<span class="hljs-string">'https://jsonplaceholder.typicode.com/users/1'</span>)))  
            .thenAnswer((invocation) <span class="hljs-keyword">async</span> {  
          <span class="hljs-keyword">return</span> Response(<span class="hljs-string">'''  
              {  "id": 1,  "name": "Leanne Graham",  "username": "Bret",  "email": "Sincere@april.biz",  "phone": "1-770-736-8031 x56442",  "website": "hildegard.org"}  
              '''</span>, <span class="hljs-number">200</span>);  
        });  
        <span class="hljs-comment">// Act  </span>
        <span class="hljs-keyword">final</span> user = <span class="hljs-keyword">await</span> userRepository.getUser();  

        <span class="hljs-comment">// Assert  </span>
        expect(user, isA&lt;User&gt;());  
      });
</code></pre>
<h5 id="heading-throw-exception-test">Throw Exception test:</h5>
<pre><code class="lang-dart">test(  
      <span class="hljs-string">'given userRepository class when getUser function is called and the status code is not 200 then the function throws an exception'</span>,  
      () <span class="hljs-keyword">async</span> {  
    <span class="hljs-comment">// Arrange  </span>
    when(  
      () =&gt; mockHTTPClient.<span class="hljs-keyword">get</span>(  
        <span class="hljs-built_in">Uri</span>.parse(<span class="hljs-string">'https://jsonplaceholder.typicode.com/users/1'</span>),  
      ),  
    ).thenAnswer(  
      (invocation) <span class="hljs-keyword">async</span> =&gt; Response(<span class="hljs-string">''</span>, <span class="hljs-number">500</span>),  
    );  
    <span class="hljs-comment">// Act  </span>
    <span class="hljs-keyword">final</span> user =  userRepository.getUser();  

    <span class="hljs-comment">// Assert  </span>
    expect(user, throwsException);  
  });  
});
</code></pre>
<p>As you can see here i just changed the status code and this resulted in a exception which satisfies our test case.</p>
<p>And this basically covers Unit Testing basics. Also these are just my notes after watching the excellent video from Rivan Ranawat. You can find the video here: Youtube Link</p>
<p>Happy Coding 🐦</p>
]]></content:encoded></item><item><title><![CDATA[Dynamic Programming Part -2: Grid Traveler Memoization]]></title><description><![CDATA[Hey everyone we are back with another Memoization Problem. How many can a person travel from the top left corner of the grid to the bottom right corner…]]></description><link>https://harishkunchala.com/dynamic-programming-part-2-grid-traveler-memoization</link><guid isPermaLink="true">https://harishkunchala.com/dynamic-programming-part-2-grid-traveler-memoization</guid><category><![CDATA[Dynamic Programming]]></category><category><![CDATA[Python]]></category><category><![CDATA[DSA]]></category><dc:creator><![CDATA[Harish Kunchala]]></dc:creator><pubDate>Wed, 10 Jul 2024 21:54:57 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1720648444330/db9e2134-b682-4d24-8964-099428591b8a.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hey everyone we are back with another Memoization Problem.</p>
<h2 id="heading-grid-problem">Grid Problem:</h2>
<p>How many can a person travel from the top left corner of the grid to the bottom right corner. The only restriction is that we can only move down or right.l</p>
<h3 id="heading-general-grid-travel">General Grid Travel:</h3>
<p>Let's look at an example of the following grid:</p>
<p><code>gridTraveler(2,3)</code> -&gt; 3.</p>
<ul>
<li><p>a(1,1) <strong>to</strong> a(1,2) <strong>to</strong> a(1,3) <strong>to</strong> a(2,3)</p>
</li>
<li><p>a(1,1) <strong>to</strong> a(2,1) <strong>to</strong> a(2,2) <strong>to</strong> a(2,3)</p>
</li>
<li><p>a(1,1) <strong>to</strong> a(1,2) <strong>to</strong> a(2,2) <strong>to</strong> a(2,3)</p>
</li>
</ul>
<h3 id="heading-basic-case">Basic Case:</h3>
<p>Let's take the basic case</p>
<p><code>gridTraveler(1,1)</code> -&gt; 1.</p>
<p>Here since it's just a Grid with One column and One Row. We don't have to do anything.</p>
<p>Now we have some illogical cases, where there is no answer such as:</p>
<ul>
<li><p><code>gridTraveler(1,0)</code> -&gt; 0 . We cannot do anything if there are no columns</p>
</li>
<li><p><code>gridTraveler(0,1)</code> -&gt; 0. We cannot do anything if there are no rows</p>
</li>
</ul>
<p>So for all the illogical cases, we'll return 0.</p>
<h4 id="heading-node-diagram">Node Diagram:</h4>
<p>If we look at the node diagram for <code>gridTraveler(2,3)</code>:</p>
<p><img src="https://i.postimg.cc/Wb0gPLg3/JPEG-image-4-CC2-AA66-C2-0.jpg" alt /></p>
<p>We can see that it basically a fibonacci. Where we are adding the values of the children to the parent.</p>
<p><strong>Time complexity</strong> = O(2 ^(m + n))</p>
<p><strong>Space complexity</strong> = O(m + n)</p>
<p>So we can write: <code>gridTraveler(2,3)</code> = <code>gridTraveler(1,3)</code> + <code>gridTraveler(2,2)</code></p>
<p>This is similar to our <a target="_blank" href="https://harishkunchala.com/dynamic-programming-part-1-basic-memoization#heading-fibonacci-series">fibonacci</a>: <code>fib(n)</code> = <code>fib(n-1)</code> + <code>fib(n-2)</code></p>
<p>So we can apply a similar algorithm here using memoization.</p>
<h3 id="heading-recursion-algorithm">Recursion Algorithm:</h3>
<p>Here's the Recursion algorithm:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">gridTraveler</span>(<span class="hljs-params">m, n</span>):</span>
    <span class="hljs-keyword">if</span> m == <span class="hljs-number">1</span> <span class="hljs-keyword">and</span> n == <span class="hljs-number">1</span>:
        <span class="hljs-keyword">return</span> <span class="hljs-number">1</span>
    <span class="hljs-keyword">if</span> m == <span class="hljs-number">0</span> <span class="hljs-keyword">or</span> n == <span class="hljs-number">0</span>:
        <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>
    <span class="hljs-keyword">return</span> gridTraveler(m - <span class="hljs-number">1</span>, n) + gridTraveler(m, n - <span class="hljs-number">1</span>)
</code></pre>
<p>And as we said before :</p>
<p><strong>Time complexity</strong> = O(2 ^(m + n))</p>
<p><strong>Space complexity</strong> = O(m + n)</p>
<h3 id="heading-memoized-algorithm">Memoized Algorithm</h3>
<p>And here's the memoized algorithm:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">grid_traveler</span>(<span class="hljs-params">m, n, memo={}</span>):</span>
    <span class="hljs-keyword">if</span> (m, n) <span class="hljs-keyword">in</span> memo:
        <span class="hljs-keyword">return</span> memo[(m, n)]
    <span class="hljs-keyword">if</span> m == <span class="hljs-number">1</span> <span class="hljs-keyword">and</span> n == <span class="hljs-number">1</span>:
        <span class="hljs-keyword">return</span> <span class="hljs-number">1</span>
    <span class="hljs-keyword">if</span> m == <span class="hljs-number">0</span> <span class="hljs-keyword">or</span> n == <span class="hljs-number">0</span>:
        <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>
    memo[(m, n)] = grid_traveler(m - <span class="hljs-number">1</span>, n, memo) + grid_traveler(m, n
            - <span class="hljs-number">1</span>, memo)

    <span class="hljs-keyword">return</span> memo[(m, n)]
</code></pre>
<p><strong>New Time Complexity</strong> = O(m * n)</p>
<p><strong>New Space Complexity</strong> = O(m + n)</p>
<p>Since memoization is one of the fundamental blocks of dynamic programming. Make sure to practice lots of problems in it as a lot of interviews generally ask this.</p>
]]></content:encoded></item><item><title><![CDATA[Dynamic Programming Part 1: Basic Memoization]]></title><description><![CDATA[We are going to learn two concepts over the course of this series: Memoization Tabulation So let's start with the basics. Write a function fib(n) that…]]></description><link>https://harishkunchala.com/dynamic-programming-part-1-basic-memoization</link><guid isPermaLink="true">https://harishkunchala.com/dynamic-programming-part-1-basic-memoization</guid><category><![CDATA[Dynamic Programming]]></category><category><![CDATA[Python]]></category><dc:creator><![CDATA[Harish Kunchala]]></dc:creator><pubDate>Sun, 07 Jul 2024 00:13:11 GMT</pubDate><content:encoded><![CDATA[<p>We are going to learn two concepts over the course of this series:</p>
<ol>
<li><p>Memoization</p>
</li>
<li><p>Tabulation</p>
</li>
</ol>
<p>So let's start with the basics.</p>
<h3 id="heading-fibonacci-series">Fibonacci Series:</h3>
<p>Write a function <code>fib(n)</code> that takes in a number as an argument. The function should return the nth number of the Fibonacci sequence.</p>
<p>Let's look at the series:</p>
<pre><code class="lang-dart">n:     <span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>,<span class="hljs-number">4</span>,<span class="hljs-number">5</span>,<span class="hljs-number">6</span>,<span class="hljs-number">7</span>,<span class="hljs-number">8</span>
fib(n): <span class="hljs-number">1</span>,<span class="hljs-number">12</span>,<span class="hljs-number">3</span>,<span class="hljs-number">5</span>,<span class="hljs-number">8</span>,<span class="hljs-number">13</span>,<span class="hljs-number">21</span>
</code></pre>
<h4 id="heading-fib-using-basic-recursion">Fib using Basic Recursion</h4>
<p>Alright so let's look at the basic Fibonacci series. We are going to implement it in a basic recursive function:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">fibonacci_recur</span>(<span class="hljs-params">n</span>):</span>
    <span class="hljs-keyword">if</span> n &lt;= <span class="hljs-number">2</span>:
        <span class="hljs-keyword">return</span> <span class="hljs-number">1</span>
    <span class="hljs-keyword">return</span> fibonacci_recur(n<span class="hljs-number">-1</span>) + fibonacci_recur(n<span class="hljs-number">-2</span>)
</code></pre>
<p>The problem is that let's say if we want to call <code>fibonacci_recur(50)</code> you'll see that the program executes for a while. In fact we can even time the program and see how long it is taking to execute.</p>
<h4 id="heading-lets-draw-our-the-fibonacci-tree">Let's draw our the Fibonacci Tree:</h4>
<p>So when we see the tree for 7. This is what we get:</p>
<p><img src="https://i.postimg.cc/0Q4tvxfD/Screenshot-2024-07-06-at-3-45-09-PM.png" alt /></p>
<p>So for all of the base cases we know that they are going to return 1.</p>
<p><img src="https://i.postimg.cc/qgVjtLW7/Screenshot-2024-07-06-at-3-48-32-PM.png" alt /></p>
<p>And remember: The time complexity of Fibonacci recursion is O( 2^n )</p>
<p>Let's look another basic algorithm. That really doesn't do anything but we want to calculate the number of calls and find out it's time complexity.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">dib</span>(<span class="hljs-params">n</span>):</span>
    <span class="hljs-keyword">if</span> n &lt;= <span class="hljs-number">1</span>:
        <span class="hljs-keyword">return</span>
    dib(n<span class="hljs-number">-1</span>)
    dib(n<span class="hljs-number">-1</span>)
</code></pre>
<p>Now if we call <code>dib(5)</code> this is going to be the tree:</p>
<p><img src="https://i.postimg.cc/Dz8jM8Qn/Screenshot-2024-07-06-at-4-19-16-PM.png" alt /></p>
<p>So the total number of levels = 4. Starting with 0 Level at the top. So now we know that the program's time complexity is again O( 2^n ). But the space complexity of the above program is O(n)</p>
<p>Now if we look at <code>fib(50)</code> we have to make 2^50 calls which is a quadrillion. Clearly we need a better way.</p>
<p>Now if we look back again at the tree for <code>fib(7)</code> we get the following:</p>
<p><img src="https://i.postimg.cc/KY6NpQvD/Screenshot-2024-07-06-at-4-33-20-PM.png" alt /></p>
<p>We see that a lot of calculations are being repeated. So we don't need to do them twice, we'll have to device a way to store the calculation for instance <code>fib(5)</code> and store the value and get it from there for future calculations. This is called Dynamic Programming.</p>
<h4 id="heading-fibonacci-using-memoization">Fibonacci using Memoization</h4>
<p>Since we want to store the values. The trick is to use Memoization.</p>
<p>In order to implement Memoization we need a fast data structure preferably one with O(1) access time. So let's use Dictionary in python.</p>
<pre><code class="lang-python"><span class="hljs-comment"># Memoization</span>
<span class="hljs-comment"># Using Dictionary, Keys will be arg to the fn, value will be the retun value</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">fib</span>(<span class="hljs-params">n, memo = {}</span>):</span>
    <span class="hljs-comment"># First we check if the value is in the dict</span>
    <span class="hljs-keyword">if</span> n <span class="hljs-keyword">in</span> memo:
        <span class="hljs-keyword">return</span> memo[n]
    <span class="hljs-comment"># This is the base case</span>
    <span class="hljs-keyword">if</span> n &lt;= <span class="hljs-number">2</span>:
        <span class="hljs-keyword">return</span> <span class="hljs-number">1</span>
    <span class="hljs-comment"># Since we'll have to calculate at least once. We are going to store the value in our dict</span>
    memo[n] = fib(n - <span class="hljs-number">1</span>, memo) + fib(n - <span class="hljs-number">2</span>, memo)
    <span class="hljs-comment"># Finally we return our value through dict</span>
    <span class="hljs-keyword">return</span> memo[n]
</code></pre>
<p>If we run the program now we can see that this is going to be Blazingly fast. As this won't take long.</p>
<p>So this is going to be an ongoing series in my journey of dynamic programming.<br />You can find the repo here: <a target="_blank" href="https://github.com/khkred/dp_algorithms">https://github.com/khkred/dp_algorithms</a></p>
<p>It also has my notes under the notes/ folder. Happy Programming!!!</p>
]]></content:encoded></item><item><title><![CDATA[LinkedList Interview patterns Part 1]]></title><description><![CDATA[LinkedLists are one of the most common interview topics that we see in interviews. This is one of most common interview questions that we've seen in the…]]></description><link>https://harishkunchala.com/linkedlist-interview-patterns-part-1</link><guid isPermaLink="true">https://harishkunchala.com/linkedlist-interview-patterns-part-1</guid><category><![CDATA[#linkedlists]]></category><category><![CDATA[DSA]]></category><category><![CDATA[interview preparations]]></category><dc:creator><![CDATA[Harish Kunchala]]></dc:creator><pubDate>Wed, 03 Jul 2024 20:21:49 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1720038072711/c49ff30d-adf4-4ca7-b984-8b25945474b7.gif" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>LinkedLists are one of the most common interview topics that we see in interviews.</p>
<h2 id="heading-nth-place-from-end">nth Place from End</h2>
<p>This is one of most common interview questions that we've seen in the past from companies like Adobe, AWS, Amazon.</p>
<p>You can find this question pretty much any code practice site like Leetcode, Hackerrank or any other site.</p>
<p>For instance here's a slight variation of the problem on Leetcode: <a target="_blank" href="https://leetcode.com/problems/remove-nth-node-from-end-of-list/description/">Problem</a></p>
<h3 id="heading-strategy">Strategy:</h3>
<p>To find the nth node from the end of a linked list in Python using O(1) space, you can use the two-pointer technique. Here's a step-by-step explanation and implementation:</p>
<ol>
<li><p>Initialize two pointers, <code>first</code> and <code>second</code>, both pointing to the head of the linked list.</p>
</li>
<li><p><mark>Move the first pointer n steps ahead.</mark></p>
</li>
<li><p>Move both pointers one step at a time until the <code>first</code> pointer reaches the end of the list.</p>
</li>
<li><p>At this point, the <code>second</code> pointer will be pointing to the nth node from the end.</p>
</li>
</ol>
<p>Here's the simplest way to implement it:</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ListNode</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self, value=<span class="hljs-number">0</span>, next=None</span>):</span>
        self.value = value
        self.next = next

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">find_nth_from_end</span>(<span class="hljs-params">head: ListNode, n: int</span>) -&gt; ListNode:</span>
    first = head
    second = head

    <span class="hljs-comment"># Move the first pointer n steps ahead</span>
    <span class="hljs-keyword">for</span> _ <span class="hljs-keyword">in</span> range(n):
        <span class="hljs-comment"># If our list is smaller than the n. Return None</span>
        <span class="hljs-keyword">if</span> first <span class="hljs-keyword">is</span> <span class="hljs-literal">None</span>:
            <span class="hljs-keyword">return</span> <span class="hljs-literal">None</span> <span class="hljs-comment"># Out of Bounds</span>
        first = first.next

    <span class="hljs-comment"># Move both pointers until the first pointer reaches the end</span>
    <span class="hljs-keyword">while</span> first:
        first = first.next
        second = second.next

    <span class="hljs-keyword">return</span> second
</code></pre>
<p><strong><mark>Note: </mark></strong> There is another way to implement it using Arrays but it'll take up Space Complexity of O(n), which generally is constrained in lot of big interviews.</p>
<h2 id="heading-find-middle-of-a-linkedlist">Find middle of a LinkedList:</h2>
<p>This is another common recurring question in LinkedList interviews.</p>
<p>Here's the question on Leetcode: <a target="_blank" href="https://leetcode.com/problems/middle-of-the-linked-list/description/">Middle of List</a></p>
<h3 id="heading-strategy-1">Strategy:</h3>
<p>To find the middle of a linked list in Python using O(1) space complexity, you can use the "tortoise and hare" algorithm.</p>
<p>This algorithm involves using two pointers:</p>
<ul>
<li><p>a slow pointer that moves one step at a time</p>
</li>
<li><p>a fast pointer that moves two steps at a time.</p>
</li>
</ul>
<p>When the fast pointer reaches the end of the list, the slow pointer will be at the middle.</p>
<p>Here's the easiest implementation:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">find_middle</span>(<span class="hljs-params">head: ListNode</span>) -&gt; ListNode:</span>
    slow = head
    fast = head

    <span class="hljs-keyword">while</span> fast <span class="hljs-keyword">and</span> fast.next:
        slow = slow.next
        fast = fast.next.next

    <span class="hljs-keyword">return</span> slow
</code></pre>
<p><mark>This algorithm ensures that the space complexity is O(1) since only a constant amount of extra space is used.</mark></p>
<h2 id="heading-reverse-a-linkedlist">Reverse a LinkedList:</h2>
<p>Another common question we get asked is to reverse an existing LinkedList using either recursion or using regular way. So in this tutorial we'll cover both:</p>
<h3 id="heading-iterative-strategy">Iterative Strategy:</h3>
<ul>
<li><p><strong>Initialize Three Pointers</strong>:</p>
<ul>
<li><p><code>prev</code> to <code>None</code></p>
</li>
<li><p><code>current</code> to the head of the list</p>
</li>
<li><p><code>next</code> to <code>None</code> (will be used to store the next node)</p>
</li>
</ul>
</li>
<li><p><strong>Iterate Through the List</strong>:</p>
<ul>
<li><p>Update <code>next</code> to <a target="_blank" href="http://current.next"><code>current.next</code></a></p>
</li>
<li><p>Set <a target="_blank" href="http://current.next"><code>current.next</code></a> to <code>prev</code> (this reverses the link)</p>
</li>
<li><p>Move <code>prev</code> to <code>current</code></p>
</li>
<li><p>Move <code>current</code> to <code>next</code></p>
</li>
</ul>
</li>
<li><p><strong>Set the New Head</strong>:</p>
<ul>
<li>After the loop, <code>prev</code> will be the new head of the reversed list.</li>
</ul>
</li>
</ul>
<p>Perfect and here's the code</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">reverse_list</span>(<span class="hljs-params">head: ListNode</span>):</span>
    prev = <span class="hljs-literal">None</span>
    current = head

    <span class="hljs-keyword">while</span> current:
        next = current.next
        current.next = prev
        prev = current
        current = current.next

    <span class="hljs-comment"># This is the head    </span>
    <span class="hljs-keyword">return</span> prev
</code></pre>
<h3 id="heading-recursion-strategy">Recursion Strategy:</h3>
<ul>
<li><p><strong>Base Case</strong>:</p>
<ul>
<li>If the node is <code>None</code> or the next node is <code>None</code>, return the node.</li>
</ul>
</li>
<li><p><strong>Recursive Step</strong>:</p>
<ul>
<li><p>Reverse the rest of the list from the second node.</p>
</li>
<li><p>Set the next node’s next pointer to the current node.</p>
</li>
<li><p>Set the current node’s next pointer to <code>None</code>.</p>
</li>
</ul>
</li>
<li><p><strong>Return the New Head</strong>:</p>
<ul>
<li>The new head will be returned from the base case</li>
</ul>
</li>
</ul>
<p>Perfect and here's the code:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">reverse_list_recursion</span>(<span class="hljs-params">head</span>):</span>
    <span class="hljs-keyword">if</span> head <span class="hljs-keyword">is</span> <span class="hljs-literal">None</span> <span class="hljs-keyword">or</span> head.next <span class="hljs-keyword">is</span> <span class="hljs-literal">None</span>:
        <span class="hljs-keyword">return</span> head
    rest = reverse_list_recursion(head.next)
    head.next.next = head
    head.next = <span class="hljs-literal">None</span>
    <span class="hljs-keyword">return</span> rest
</code></pre>
<p>These are but some of the concepts we need in LinkedLists. In the remaining series we'll cover easy patterns for:</p>
<ul>
<li><p>Detect a Cycle in a Linked List</p>
</li>
<li><p>Merge two sorted Linked Lists</p>
</li>
<li><p>Check if a LinkedList is Palindrome</p>
</li>
<li><p>Remove duplicates from a sorted LinkedList</p>
</li>
<li><p>Intersection of two LinkedLists</p>
</li>
<li><p>Flatten a multilevel doubly LinkedList</p>
</li>
<li><p>Partion List</p>
</li>
<li><p>Rotate List</p>
</li>
<li><p>Add two numbers represented by linked lists</p>
</li>
</ul>
<p>While the code would be important we'll also go through identify common patterns so that we can hack away at any questions the interviewer throws at us.</p>
<p>I hope to hear more from you guys in the Journey and good luck with you #DSA preparations.</p>
]]></content:encoded></item><item><title><![CDATA[Connecting my Google Domain/ Squarespace to Firebase App and a Subdomain to HashNode Blog]]></title><description><![CDATA[This week I wanted to update my website. The problem arose because my website is already setup with Hashnode as its main page. So let's do step by step. I…]]></description><link>https://harishkunchala.com/connecting-my-google-domain-squarespace-to-firebase-app-and-a-subdomain-to-hashnode-blog</link><guid isPermaLink="true">https://harishkunchala.com/connecting-my-google-domain-squarespace-to-firebase-app-and-a-subdomain-to-hashnode-blog</guid><category><![CDATA[Firebase]]></category><category><![CDATA[squarespace]]></category><dc:creator><![CDATA[Harish Kunchala]]></dc:creator><pubDate>Tue, 18 Jun 2024 23:19:54 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1718752762721/3b18d307-a2ef-416a-aeae-1c0b86ae4dcd.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>This week I wanted to update my <a target="_blank" href="https://harishkunchala.com">website</a>. The problem arose because my website is already setup with Hashnode as its main page. So let's do step by step.</p>
<h3 id="heading-step-1-connect-our-google-domain-to-our-firebase-app">Step 1: Connect our Google domain to our Firebase App</h3>
<p>I will be following some of the steps mentioned in my previous article:</p>
<p>You can read my article on GoDaddy connection here: <a target="_blank" href="https://harishkunchala.com/seamlessly-connecting-your-godaddy-domain-to-firebase-hosting-a-step-by-step-guide">Seamlessly Connecting Your GoDaddy Domain to Firebase Hosting: A Step-by-Step Guide</a></p>
<p>I have followed the commands and now finally I am able to setup my website on Squarespace by adding the DNS records provided by Firebase into my Squarespace.</p>
<h3 id="heading-step-2-connect-my-blog-to-hashnode">Step 2: Connect my blog to hashnode</h3>
<p>Now I want <a target="_blank" href="https://blog.harishkunchala.com">blog.harishkunchala.com</a> to redirect to my Hashnode Blog. So in my case here are the steps:</p>
<ul>
<li><p>Go to your Hashnode dashboard.</p>
</li>
<li><p>Navigate to the blog settings and find the option to set a custom domain.</p>
</li>
<li><p>Enter <a target="_blank" href="http://blog.harishkunchala.com"><code>blog.harishkunchala.com</code></a>.</p>
</li>
</ul>
<p>After I entered the domain. I was greeted with the following instructions:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1718752176560/02a49732-7869-4b8e-89bc-9b37f1910770.png" alt class="image--center mx-auto" /></p>
<p>So we can login to our Squarespace and add the cname record.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1718752330544/16a1a105-a233-4f89-ac72-37795d04a8b0.png" alt class="image--center mx-auto" /></p>
<p>Perfect. Now we just have to wait for couple of hours and finally our website and blog are going to point to different services.</p>
<p>NOTE: Generally Firebase and Hashnode provided free SSL certificates for our website. So I'd recommend waiting for couple of hours and we'll see the changes propagated across the entire site.</p>
]]></content:encoded></item><item><title><![CDATA[Step-by-Step Guide to Setting Up Firebase Phone Authentication in Flutter for Android and iOS (APNs, Push Notification and Xcode Setup)]]></title><description><![CDATA[Setting up Phone Verification allows various forms of User Credentials. Let's see how to setup it up. Also make sure that the app is already connected to…]]></description><link>https://harishkunchala.com/step-by-step-guide-to-setting-up-firebase-phone-authentication-in-flutter-for-android-and-ios-apns-push-notification-and-xcode-setup</link><guid isPermaLink="true">https://harishkunchala.com/step-by-step-guide-to-setting-up-firebase-phone-authentication-in-flutter-for-android-and-ios-apns-push-notification-and-xcode-setup</guid><category><![CDATA[Flutter]]></category><category><![CDATA[Firebase]]></category><category><![CDATA[Mobile Development]]></category><dc:creator><![CDATA[Harish Kunchala]]></dc:creator><pubDate>Wed, 12 Jun 2024 21:11:28 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1718227344435/fb463962-474b-4976-8730-0a844d028e73.gif" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Setting up Phone Verification allows various forms of User Credentials.</p>
<p>Let's see how to setup it up. Also make sure that the app is already connected to the firebase. You can read the following article on how to setup Firebase on your app : <a target="_blank" href="https://harishkunchala.com/flutter-on-fire-connect-your-app-to-firebase-now">Flutter on Fire</a></p>
<h2 id="heading-step-1-add-phone-provider-to-firebase">Step 1: Add Phone Provider to Firebase</h2>
<h3 id="heading-11-go-to-firebase-consolehttpsconsolefirebasegooglecomu0">1.1 Go to <a target="_blank" href="https://console.firebase.google.com/u/0/">Firebase Console</a></h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1717622170536/837317ce-1f02-4f53-ba28-3e68f941b83e.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-12-navigate-to-your-project">1.2 Navigate to your Project</h3>
<p>In our scenario, we'll be selecting kaida:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1717622216980/a2562049-92c1-4df0-9e5f-4731b305bcc3.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-13-select-authentication-from-the-sidebar">1.3 Select Authentication from the sidebar</h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1717622273279/566d31b1-f1b5-4e0c-aeb7-cd201e66fc8c.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-14-go-to-sign-in-method-tab">1.4 Go to Sign-in method tab.</h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1717622322068/614f2e21-6a04-44db-9a25-89efd267e41e.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-15-enable-the-phone-sign-in-and-save">1.5 Enable the Phone sign-in and save</h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1717622371730/24eceea2-929d-42bc-8903-647aeac8d1be.png" alt class="image--center mx-auto" /></p>
<p>This is my final sign-in methods:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1717622397072/1d51c6c1-b813-48e9-ac22-2bad1b634548.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-step-2-configure-android-for-phone-verification-setup">Step 2: Configure Android for Phone Verification setup</h2>
<h3 id="heading-setup-sha-1-has-in-firebase-console"><strong>Setup SHA-1 has in Firebase Console:</strong></h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1717622600592/c2b961dc-2d9e-4c40-a3e7-71e77d3fcf20.png" alt class="image--center mx-auto" /></p>
<p>If you want to learn how to generate SHA-1 and SHA-256 for our app. Make sure to check out the following link: <a target="_blank" href="https://harishkunchala.com/level-up-your-flutter-app-security-how-to-add-firebase-app-check#heading-step-4-registering-android">Registering Android App</a> Checkout Step 5 inside the link.</p>
<h2 id="heading-step-3-configure-ios-for-phone-verification-setup">Step 3: Configure iOS for Phone Verification Setup</h2>
<h3 id="heading-open-xcode"><strong>Open Xcode:</strong></h3>
<p>First open the app in Xcode by clicking on iOS folder and then selecting "Open in Xcode" (Similar options on both VSCode as well as Android Studio).</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1717624729981/66b9a6c2-c8a8-4b13-98f7-e4ee6ebc6037.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-setup-url-types"><strong>Setup URL Types:</strong></h3>
<p>Go to the info tab and click on URL Types</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1717624924399/3c5ce301-7d9b-4832-a630-c169c763d81c.png" alt class="image--center mx-auto" /></p>
<p>We need couple of url Types:</p>
<ol>
<li><strong>Reverse Client Id:</strong></li>
</ol>
<p>You can find it under our Runner in GoogleService-Info File:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1717625544539/cef94ec0-c065-4714-bcc4-d72c566d7f79.png" alt class="image--center mx-auto" /></p>
<p>So let's go ahead and add our Reverse Client Id. Just copy the value and then create an object in URL types:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1717625770457/aae90cfd-9be5-421b-927d-bc41b8b166b4.png" alt class="image--center mx-auto" /></p>
<ol start="2">
<li><strong>Encoded App ID:</strong></li>
</ol>
<p>The next step is to copy the Encoded App ID. We can find it on our Firebase Project Settings:</p>
<p><mark>We are using Encode App ID for reCAPTCHA verification</mark></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1717626027983/dbbf3483-e178-4b2a-a5a0-1ece27c2bd4a.png" alt class="image--center mx-auto" /></p>
<p>Now we just have to past the value in our URL Types:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1717626150677/ae19718e-adc3-4da1-9d8e-44d1619bdc52.png" alt class="image--center mx-auto" /></p>
<ol start="3">
<li><strong>Bundle ID:</strong></li>
</ol>
<p>Finally we just have to paste the bundle ID. we can get the Bundle ID from the general tab:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1717626383968/f0b636af-4802-4d20-8f06-265538d3c31c.png" alt class="image--center mx-auto" /></p>
<p>Let's paste it in the URL Types:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1717626506195/9f713261-6703-486d-a159-98f523dbbfbd.png" alt class="image--center mx-auto" /></p>
<p>Perfect, now with the URL Types added. Let's add APNs and other things to avoid Captcha in real devices.</p>
<h2 id="heading-apn-keys">APN Keys:</h2>
<h3 id="heading-download-apn-key">Download APN Key</h3>
<p>In order for the OTP to work without Captcha. We need to upload our APN key to our Firebase Project.</p>
<p>So first let's go to our <a target="_blank" href="https://developer.apple.com/account">Apple Developer Member Center</a> and the go ahead and click on Keys:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1718162796512/f12a6a21-f039-4168-a427-c5a8f387bd0c.png" alt class="image--center mx-auto" /></p>
<p><strong>Keys Page:</strong></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1718162843581/f1ed72dc-5f5e-4235-b3b0-5ccd0b6434fa.png" alt class="image--center mx-auto" /></p>
<p>Click on Create a Key.</p>
<p>And then enable Apple Push Notification Service</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1718162932391/6155e667-52db-4f28-9f57-b839391dd9e4.png" alt class="image--center mx-auto" /></p>
<p>After you click continue. You are taken to the new key registration page and just click on register.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1718163053858/dd37efeb-098f-4f01-9b9a-2191c740caa9.png" alt class="image--center mx-auto" /></p>
<p><mark>Make sure to download your key and store it in a secure place. As it cannot be redownloaded again.</mark></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1718163272276/da801321-1dd4-43b8-8fb4-7bd7877c0989.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-upload-apn-key-to-firebase-console">Upload APN Key to Firebase console:</h3>
<p>Now that the key has been downloaded. Let's upload it to Firebase console.</p>
<h3 id="heading-push-notifications">Push Notifications:</h3>
<ol>
<li>Inside your project in the Firebase console, select the gear icon, select <strong>Project Settings</strong>, and then select the <strong>Cloud Messaging</strong> tab.</li>
</ol>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1718163562059/7890eb95-6e35-4422-ba71-96366262d667.png" alt class="image--center mx-auto" /></p>
<p>Make sure to enter the Key ID as well as the Team ID when you upload the APN key:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1718163917789/c58ed176-dbd4-4ce3-9577-5f69f0c25f80.png" alt class="image--center mx-auto" /></p>
<p>Perfect now we can finally see our APN key in our Firebase console</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1718164103256/d40f39df-5ad3-493a-82cd-bd8fce07edb6.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-push-notifications-1">Push Notifications:</h2>
<p>Before our app can start to receive messages. We must explicitly enable "Push Notifications" and "Background Modes" within Xcode</p>
<h3 id="heading-open-our-ios-module-in-xcode"><strong>Open our iOS module in Xcode:</strong></h3>
<p>You can do it in Android Studio by clicking on iOS module and then from the menu (Tools --&gt; Flutter --&gt; open iOS / macOS module in Xcode)</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1718164606854/d4646200-5bb7-4e4f-a4f2-149a002a6671.png" alt class="image--center mx-auto" /></p>
<p>So we get Xcode:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1718164741021/f3e47382-df87-4dea-a706-89488d6f0366.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-xcode-settings">Xcode Settings:</h3>
<p>So follow the steps below:</p>
<ol>
<li><p>Select Project</p>
</li>
<li><p>Select the Project target.</p>
</li>
<li><p>Select the "Signing &amp; Capabilities" tab.</p>
</li>
</ol>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1718164986565/365ee645-b7e8-45ab-824c-d670e4f1fde8.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-enable-push-notifications">Enable Push Notifications</h3>
<p>Next the "Push Notifications" capability needs to be added to the project. This can be done via the "Capability" option on the "Signing &amp; Capabilities" tab:</p>
<ol>
<li><p>Click on the "+ Capabilities" button.</p>
</li>
<li><p>Search for "Push Notifications"</p>
</li>
</ol>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1718165248557/a88a6613-8e28-4a25-8c6f-d55b270a7c30.png" alt class="image--center mx-auto" /></p>
<p>Once selected, the capability will be shown below the other enabled capabilities. If no option appears when searching, the capability may already be enabled.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1718165299839/c7abaa38-6376-49b5-af16-2a9257cf595a.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-enable-background-modes">Enable Background Modes</h3>
<p>Next the "Background Modes" capability needs to be enabled, along with "Background fetch" and "Remote notifications" sub-modes. This can be again added via the "Capability" option on the "Signing &amp; Capabilities: tab:</p>
<ol>
<li><p>Click on the "+ Capabilities" button.</p>
</li>
<li><p>Search for "Background Modes".</p>
</li>
</ol>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1718165883400/ecbf5430-8c92-4a2f-bcbd-d3d27a8f3030.png" alt class="image--center mx-auto" /></p>
<p>Once selected we can see the "Background Modes" with other capabilities too.</p>
<p><mark>Now ensure that both the "Background fetch" and the "Remote notifications" sub-modes are enabled:</mark></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1718166009098/6090d8a3-a0be-42b1-bdaf-daffaf798e0c.png" alt class="image--center mx-auto" /></p>
<p>If you want, you can enable Background processing too.</p>
<h2 id="heading-implementing-phone-number-verification">Implementing Phone Number Verification</h2>
<h3 id="heading-add-phone-authentication-dependency">Add Phone Authentication Dependency</h3>
<p>While we have already added it to our <a target="_blank" href="https://github.com/khkred/kaida">Kaida</a> before. Let's make sure to get the latest version into our app.</p>
<pre><code class="lang-bash">flutter pub add firebase_auth
</code></pre>
<h3 id="heading-implement-phone-verification-method-in-authrepository">Implement Phone Verification Method in AuthRepository</h3>
<p><strong>AuthRepository:</strong></p>
<p>I have created an <a target="_blank" href="https://github.com/khkred/kaida/blob/main/lib/src/features/auth/repository/auth_repository.dart">AuthRepository</a> in Kaida. So we are going to add this to our AuthRepository</p>
<pre><code class="lang-dart"><span class="hljs-keyword">import</span> <span class="hljs-string">'package:firebase_auth/firebase_auth.dart'</span>;
<span class="hljs-keyword">import</span> <span class="hljs-string">'package:cloud_firestore/cloud_firestore.dart'</span>;
<span class="hljs-keyword">import</span> <span class="hljs-string">'package:google_sign_in/google_sign_in.dart'</span>;
<span class="hljs-keyword">import</span> <span class="hljs-string">'package:kaida/src/features/auth/domain/models/app_user.dart'</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">AuthRepository</span> </span>{
  <span class="hljs-keyword">final</span> FirebaseAuth _firebaseAuth;
  <span class="hljs-keyword">final</span> FirebaseFirestore _firestore;

  AuthRepository(<span class="hljs-keyword">this</span>._firebaseAuth, <span class="hljs-keyword">this</span>._firestore);

  <span class="hljs-comment">// Existing methods...</span>

  Future&lt;<span class="hljs-keyword">void</span>&gt; verifyPhoneNumber(
      <span class="hljs-built_in">String</span> phoneNumber,
      PhoneVerificationCompleted verificationCompleted,
      PhoneVerificationFailed verificationFailed,
      PhoneCodeSent codeSent,
      PhoneCodeAutoRetrievalTimeout codeAutoRetrievalTimeout) <span class="hljs-keyword">async</span> {
    <span class="hljs-keyword">await</span> _firebaseAuth.verifyPhoneNumber(
      phoneNumber: phoneNumber,
      verificationCompleted: verificationCompleted,
      verificationFailed: verificationFailed,
      codeSent: codeSent,
      codeAutoRetrievalTimeout: codeAutoRetrievalTimeout,
    );
  }

  Future&lt;UserCredential&gt; signInWithPhoneNumber(<span class="hljs-built_in">String</span> verificationId, <span class="hljs-built_in">String</span> smsCode) <span class="hljs-keyword">async</span> {
    <span class="hljs-keyword">final</span> credential = PhoneAuthProvider.credential(verificationId: verificationId, smsCode: smsCode);
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">await</span> _firebaseAuth.signInWithCredential(credential);
  }
}
</code></pre>
<p><strong>AuthNotifier:</strong></p>
<p>Now let's add the verify <code>phoneNumber()</code> in <a target="_blank" href="https://github.com/khkred/kaida/blob/main/lib/src/features/auth/provider/auth_notifier.dart">AuthNotifier</a></p>
<pre><code class="lang-dart"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">AuthNotifier</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">StateNotifier</span>&lt;<span class="hljs-title">AuthState</span>&gt; </span>{
  <span class="hljs-keyword">final</span> AuthRepository _authRepository;

  AuthNotifier(<span class="hljs-keyword">this</span>._authRepository) : <span class="hljs-keyword">super</span>(<span class="hljs-keyword">const</span> AuthStateInitial());

  <span class="hljs-comment">// Existing methods...</span>

  Future&lt;<span class="hljs-keyword">void</span>&gt; verifyPhoneNumber(
    <span class="hljs-built_in">String</span> phoneNumber,
    PhoneVerificationCompleted verificationCompleted,
    PhoneVerificationFailed verificationFailed,
    PhoneCodeSent codeSent,
    PhoneCodeAutoRetrievalTimeout codeAutoRetrievalTimeout,
  ) <span class="hljs-keyword">async</span> {
    <span class="hljs-keyword">try</span> {
      <span class="hljs-keyword">await</span> _authRepository.verifyPhoneNumber(
        phoneNumber,
        verificationCompleted,
        verificationFailed,
        codeSent,
        codeAutoRetrievalTimeout,
      );
    } <span class="hljs-keyword">catch</span> (e) {
      <span class="hljs-built_in">print</span>(<span class="hljs-string">'VerifyPhoneNumber Error: <span class="hljs-subst">$e</span>'</span>);
      <span class="hljs-keyword">throw</span> e;
    }
  }

  Future&lt;<span class="hljs-keyword">void</span>&gt; signInWithPhoneNumber(<span class="hljs-built_in">String</span> verificationId, <span class="hljs-built_in">String</span> smsCode) <span class="hljs-keyword">async</span> {
    <span class="hljs-keyword">try</span> {
      <span class="hljs-keyword">await</span> _authRepository.signInWithPhoneNumber(verificationId, smsCode);
    } <span class="hljs-keyword">catch</span> (e) {
      <span class="hljs-built_in">print</span>(<span class="hljs-string">'SignInWithPhoneNumber Error: <span class="hljs-subst">$e</span>'</span>);
      <span class="hljs-keyword">throw</span> e;
    }
  }
}
</code></pre>
<p><strong>PhoneVerificationPage:</strong></p>
<p>We are creating a basic Phone Verification Page that'll take a code and verify it. Make sure to create separate forms for both phone text form field and verification code text form field</p>
<pre><code class="lang-dart"><span class="hljs-keyword">import</span> <span class="hljs-string">'package:firebase_auth/firebase_auth.dart'</span>;
<span class="hljs-keyword">import</span> <span class="hljs-string">'package:flutter/material.dart'</span>;
<span class="hljs-keyword">import</span> <span class="hljs-string">'package:flutter_hooks/flutter_hooks.dart'</span>;
<span class="hljs-keyword">import</span> <span class="hljs-string">'package:go_router/go_router.dart'</span>;
<span class="hljs-keyword">import</span> <span class="hljs-string">'package:hooks_riverpod/hooks_riverpod.dart'</span>;
<span class="hljs-keyword">import</span> <span class="hljs-string">'package:kaida/src/features/auth/provider/auth_providers.dart'</span>;

<span class="hljs-keyword">import</span> <span class="hljs-string">'../../../../constants/routes.dart'</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">PhoneVerificationPage</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">HookConsumerWidget</span> </span>{
  <span class="hljs-keyword">const</span> PhoneVerificationPage({<span class="hljs-keyword">super</span>.key});

  <span class="hljs-meta">@override</span>
  Widget build(BuildContext context, WidgetRef ref) {
    <span class="hljs-keyword">final</span> phoneFormKey = useMemoized(() =&gt; GlobalKey&lt;FormState&gt;());
    <span class="hljs-keyword">final</span> codeFormKey = useMemoized(() =&gt; GlobalKey&lt;FormState&gt;());
    <span class="hljs-keyword">final</span> phoneController = useTextEditingController();
    <span class="hljs-keyword">final</span> codeController = useTextEditingController();
    <span class="hljs-keyword">final</span> verificationId = useState&lt;<span class="hljs-built_in">String?</span>&gt;(<span class="hljs-keyword">null</span>);
    <span class="hljs-keyword">final</span> errorMessage = useState&lt;<span class="hljs-built_in">String?</span>&gt;(<span class="hljs-keyword">null</span>);

    <span class="hljs-keyword">final</span> authNotifier = ref.read(authNotifierProvider.notifier);

    <span class="hljs-built_in">String</span> formatPhoneNumber(<span class="hljs-built_in">String</span> phoneNumber) {

      <span class="hljs-keyword">if</span>(phoneNumber.startsWith(<span class="hljs-string">'+1'</span>)){
        <span class="hljs-keyword">return</span> phoneNumber;
      } <span class="hljs-keyword">else</span> {
        <span class="hljs-keyword">return</span> <span class="hljs-string">'+1<span class="hljs-subst">$phoneNumber</span>'</span>;
      }
    }

    <span class="hljs-keyword">return</span> Scaffold(
      appBar: AppBar(
        title: <span class="hljs-keyword">const</span> Text(<span class="hljs-string">'Verify Phone Number'</span>),
      ),
      body: Padding(
        padding: <span class="hljs-keyword">const</span> EdgeInsets.all(<span class="hljs-number">16.0</span>),
        child: Column(
          children: [
            Form(
              key: phoneFormKey,
              child: Column(
                children: [
                  TextFormField(
                    controller: phoneController,
                    decoration:
                        <span class="hljs-keyword">const</span> InputDecoration(labelText: <span class="hljs-string">'Phone Number'</span>),
                    keyboardType: TextInputType.phone,
                    validator: (value) {
                      <span class="hljs-keyword">if</span> (value == <span class="hljs-keyword">null</span> || value.isEmpty) {
                        <span class="hljs-keyword">return</span> <span class="hljs-string">'Please enter your phone number'</span>;
                      }
                      <span class="hljs-keyword">if</span> (!<span class="hljs-built_in">RegExp</span>(<span class="hljs-string">r'^\+?\d{10,}$'</span>).hasMatch(value)) {
                        <span class="hljs-keyword">return</span> <span class="hljs-string">'Please enter a valid phone number'</span>;
                      }
                      <span class="hljs-keyword">return</span> <span class="hljs-keyword">null</span>;
                    },
                  ),
                  <span class="hljs-keyword">const</span> SizedBox(height: <span class="hljs-number">20</span>),
                  ElevatedButton(
                      onPressed: () <span class="hljs-keyword">async</span> {
                        <span class="hljs-keyword">if</span> (phoneFormKey.currentState?.validate() == <span class="hljs-keyword">true</span>) {
                          <span class="hljs-keyword">try</span> {
                            <span class="hljs-keyword">await</span> authNotifier
                                .verifyPhoneNumber(formatPhoneNumber(phoneController.text.trim()),
                                    (PhoneAuthCredential credential) <span class="hljs-keyword">async</span> {
                              <span class="hljs-keyword">await</span> FirebaseAuth.instance
                                  .signInWithCredential(credential);
                              ScaffoldMessenger.of(context).showSnackBar(
                                  <span class="hljs-keyword">const</span> SnackBar(
                                      content: Text(<span class="hljs-string">'Phone number verified'</span>)));
                              context.go(Routes.profile);
                            }, (FirebaseAuthException e) {
                              errorMessage.value = e.toString();
                            }, (<span class="hljs-built_in">String</span> mVerificationId, <span class="hljs-built_in">int?</span> resendToken) {
                              verificationId.value = mVerificationId;

                              ScaffoldMessenger.of(context).showSnackBar(
                                  <span class="hljs-keyword">const</span> SnackBar(
                                      content: Text(<span class="hljs-string">'Verification code sent'</span>)));
                            }, (<span class="hljs-built_in">String</span> mVerificationId) {
                              verificationId.value = mVerificationId;
                            });
                          } <span class="hljs-keyword">catch</span> (e) {
                            errorMessage.value = e.toString();
                          }
                        }
                      },
                      child: <span class="hljs-keyword">const</span> Text(<span class="hljs-string">'Send Verification Code'</span>)),
                ],
              ),
            ),
            <span class="hljs-keyword">const</span> SizedBox(height: <span class="hljs-number">20</span>),
            <span class="hljs-keyword">if</span> (verificationId.value != <span class="hljs-keyword">null</span>)
              Form(
                key: codeFormKey,
                child: Column(
                  children: [
                    TextFormField(
                      controller: codeController,
                      decoration:
                          <span class="hljs-keyword">const</span> InputDecoration(labelText: <span class="hljs-string">'Verification Code'</span>),
                      keyboardType: TextInputType.number,
                      validator: (value) {
                        <span class="hljs-keyword">if</span> (value == <span class="hljs-keyword">null</span> || value.isEmpty) {
                          <span class="hljs-keyword">return</span> <span class="hljs-string">'Please enter the verification code'</span>;
                        }
                        <span class="hljs-keyword">return</span> <span class="hljs-keyword">null</span>;
                      },
                    ),
                    <span class="hljs-keyword">const</span> SizedBox(height: <span class="hljs-number">20</span>),
                    ElevatedButton(
                        onPressed: () <span class="hljs-keyword">async</span> {
                          <span class="hljs-keyword">if</span> (codeFormKey.currentState?.validate() == <span class="hljs-keyword">true</span>) {
                            <span class="hljs-keyword">try</span> {
                              <span class="hljs-keyword">await</span> authNotifier.signInWithPhoneNumber(
                                  verificationId.value!, codeController.text);
                              ScaffoldMessenger.of(context).showSnackBar(
                                  <span class="hljs-keyword">const</span> SnackBar(
                                      content: Text(<span class="hljs-string">'Phone Number Verified'</span>)));
                             context.go(Routes.profile);
                            } <span class="hljs-keyword">catch</span> (e) {
                              errorMessage.value = e.toString();
                            }
                          }
                        },
                        child: <span class="hljs-keyword">const</span> Text(<span class="hljs-string">'Verify Code'</span>)),
                  ],
                ),
              ),
            <span class="hljs-keyword">if</span> (errorMessage.value != <span class="hljs-keyword">null</span>)
              Padding(
                padding: <span class="hljs-keyword">const</span> EdgeInsets.only(top: <span class="hljs-number">20</span>),
                child: Text(
                  errorMessage.value!,
                  style: <span class="hljs-keyword">const</span> TextStyle(color: Colors.red),
                ),
              ),
          ],
        ),
      ),
    );
  }
}
</code></pre>
<p><strong>UserProfilePage:</strong></p>
<p>For now I am just adding a button to go the Phone Verification Page from our existing <a target="_blank" href="https://github.com/khkred/kaida/blob/main/lib/src/features/profile/presentation/pages/user_profile_page.dart">user_profile_page.dart</a></p>
<pre><code class="lang-dart"><span class="hljs-keyword">import</span> <span class="hljs-string">'package:flutter/material.dart'</span>;
<span class="hljs-keyword">import</span> <span class="hljs-string">'package:hooks_riverpod/hooks_riverpod.dart'</span>;
<span class="hljs-keyword">import</span> <span class="hljs-string">'package:kaida/src/features/auth/provider/auth_providers.dart'</span>;
<span class="hljs-keyword">import</span> <span class="hljs-string">'package:kaida/src/constants/routes.dart'</span>;
<span class="hljs-keyword">import</span> <span class="hljs-string">'package:go_router/go_router.dart'</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">UserProfilePage</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">HookConsumerWidget</span> </span>{
  <span class="hljs-keyword">const</span> UserProfilePage({Key? key}) : <span class="hljs-keyword">super</span>(key: key);

  <span class="hljs-meta">@override</span>
  Widget build(BuildContext context, WidgetRef ref) {
    <span class="hljs-keyword">final</span> authState = ref.watch(authNotifierProvider);

    <span class="hljs-keyword">if</span> (authState <span class="hljs-keyword">is</span>! AuthStateAuthenticated) {
      <span class="hljs-comment">// Redirect to sign-in if not authenticated</span>
      WidgetsBinding.instance.addPostFrameCallback((_) {
        context.go(Routes.signIn);
      });
      <span class="hljs-keyword">return</span> <span class="hljs-keyword">const</span> SizedBox.shrink();
    }

    <span class="hljs-keyword">return</span> Scaffold(
      appBar: AppBar(
        title: <span class="hljs-keyword">const</span> Text(<span class="hljs-string">'User Profile'</span>),
        actions: [
          IconButton(
            icon: <span class="hljs-keyword">const</span> Icon(Icons.edit),
            onPressed: () {
              context.go(Routes.editProfile);
            },
          ),
          IconButton(
            icon: <span class="hljs-keyword">const</span> Icon(Icons.lock),
            onPressed: () {
              context.go(Routes.changePassword);
            },
          ),
          IconButton(
            icon: <span class="hljs-keyword">const</span> Icon(Icons.phone),
            onPressed: () {
              context.go(Routes.phoneVerification);
            },
          ),
          IconButton(
            icon: <span class="hljs-keyword">const</span> Icon(Icons.logout),
            onPressed: () {
              ref.read(authNotifierProvider.notifier).signOut();
            },
          ),
        ],
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(<span class="hljs-string">'User ID: <span class="hljs-subst">${authState.userId}</span>'</span>),
            <span class="hljs-keyword">const</span> SizedBox(height: <span class="hljs-number">20</span>),
            ElevatedButton(
              onPressed: () {
                context.go(Routes.editProfile);
              },
              child: <span class="hljs-keyword">const</span> Text(<span class="hljs-string">'Edit Profile'</span>),
            ),
            ElevatedButton(
              onPressed: () {
                context.go(Routes.changePassword);
              },
              child: <span class="hljs-keyword">const</span> Text(<span class="hljs-string">'Change Password'</span>),
            ),
            ElevatedButton(
              onPressed: () {
                context.go(Routes.phoneVerification);
              },
              child: <span class="hljs-keyword">const</span> Text(<span class="hljs-string">'Verify Phone Number'</span>),
            ),
            ElevatedButton(
              onPressed: () {
                ref.read(authNotifierProvider.notifier).signOut();
              },
              child: <span class="hljs-keyword">const</span> Text(<span class="hljs-string">'Logout'</span>),
            ),
          ],
        ),
      ),
    );
  }
}
</code></pre>
<h2 id="heading-testing">Testing:</h2>
<p>Finally let's test the app. We are going to test it on an iPhone in order for the app to send a code to the user and also to ensure that our verification works on actual device.</p>
<p><img src="https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExejdsMXY4c2J3YXdhYmo5am92OGI0aHdpazM4bjhiNmU0aGowZzZndSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/coeagaoyKpznCpZgRW/giphy.gif" alt="Phone Verification" class="image--center mx-auto" /></p>
<p>Perfect. Finally the app is working as intended. You can find the code here: <a target="_blank" href="https://github.com/khkred/kaida">https://github.com/khkred/kaida</a></p>
]]></content:encoded></item><item><title><![CDATA[Flutter Riverpod Tutorial Part 8: Dependency injection]]></title><description><![CDATA[In this tutorial, we'll explore how to set up dependency injection with Riverpod, manage dependencies across your app, and test with dependency injection…]]></description><link>https://harishkunchala.com/flutter-riverpod-tutorial-part-8-dependency-injection</link><guid isPermaLink="true">https://harishkunchala.com/flutter-riverpod-tutorial-part-8-dependency-injection</guid><category><![CDATA[Flutter]]></category><category><![CDATA[Riverpod]]></category><category><![CDATA[State Management ]]></category><dc:creator><![CDATA[Harish Kunchala]]></dc:creator><pubDate>Tue, 04 Jun 2024 07:00:48 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1717039479749/dff42c24-8747-4063-aca1-5651797b9d67.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In this tutorial, we'll explore how to set up dependency injection with Riverpod, manage dependencies across your app, and test with dependency injection.</p>
<p>Dependency injection is a technique where an object receives its dependencies from an external source rather than creating them itself, promoting loose coupling and easier testing.</p>
<h4 id="heading-sections-covered"><strong>Sections Covered:</strong></h4>
<ol>
<li><p>Setting up Dependency Injection with Riverpod</p>
</li>
<li><p>Managing Dependencies Across the App</p>
</li>
<li><p>Testing with Dependency Injection</p>
</li>
</ol>
<h3 id="heading-1-setting-up-dependency-injection-with-riverpod"><strong>1. Setting up Dependency Injection with Riverpod</strong></h3>
<p><strong>Step 1: Define Dependencies</strong></p>
<p>Let's create a service class that you'll use as a dependency. For example we will use this <code>AuthService</code></p>
<pre><code class="lang-dart"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">AuthService</span> </span>{
  <span class="hljs-built_in">String</span> login(<span class="hljs-built_in">String</span> login, <span class="hljs-built_in">String</span> password) {
    <span class="hljs-comment">//Mock Login Service</span>
    <span class="hljs-keyword">if</span> (login == <span class="hljs-string">'admin'</span> &amp;&amp; password == <span class="hljs-string">'admin'</span>) {
      <span class="hljs-keyword">return</span> <span class="hljs-string">'Login successful!'</span>;
    } <span class="hljs-keyword">else</span> {
      <span class="hljs-keyword">return</span> <span class="hljs-string">'Login failed!'</span>;
    }
  }
}
</code></pre>
<p><strong>Step 2: Create a Provider for the Service</strong></p>
<p>Since we are going to test the code we need to create the provider in a separate file. like <a target="_blank" href="https://github.com/khkred/go_router_riverpod_tutorials/blob/rp_advance_dependency_injection/riverpod_advanced/lib/providers/auth_service_provider.dart">auth_service_provider.dart</a>.</p>
<pre><code class="lang-dart"><span class="hljs-keyword">final</span> authServiceProvider = Provider&lt;AuthService&gt;((ref) =&gt; AuthService());
</code></pre>
<h3 id="heading-2-managing-dependencies-across-the-app"><strong>2. Managing Dependencies Across the App</strong></h3>
<p>So in here let's use the <code>authServiceProvider</code> in our <code>LoginPage</code></p>
<pre><code class="lang-dart"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">LoginPage</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">HookConsumerWidget</span> </span>{
  <span class="hljs-keyword">const</span> LoginPage({<span class="hljs-keyword">super</span>.key});

  <span class="hljs-meta">@override</span>
  Widget build(BuildContext context, WidgetRef ref) {
    <span class="hljs-keyword">final</span> authService = ref.watch(authServiceProvider);
    <span class="hljs-keyword">final</span> usernameController = useTextEditingController();
    <span class="hljs-keyword">final</span> passwordController = useTextEditingController();
    <span class="hljs-keyword">final</span> message = useState(<span class="hljs-string">''</span>);

    <span class="hljs-keyword">return</span> Scaffold(
      appBar: AppBar(
        title: <span class="hljs-keyword">const</span> Text(<span class="hljs-string">'Login'</span>),
      ),
      body: Padding(
        padding: <span class="hljs-keyword">const</span> EdgeInsets.all(<span class="hljs-number">20</span>),
        child: Column(
          children: [
            TextField(
              controller: usernameController,
              decoration: <span class="hljs-keyword">const</span> InputDecoration(labelText: <span class="hljs-string">'Username'</span>),
            ),
            <span class="hljs-keyword">const</span> SizedBox(
              height: <span class="hljs-number">20</span>,
            ),
            TextField(
              controller: passwordController,
              decoration: <span class="hljs-keyword">const</span> InputDecoration(labelText: <span class="hljs-string">'Password'</span>),
            ),
            <span class="hljs-keyword">const</span> SizedBox(
              height: <span class="hljs-number">20</span>,
            ),
            ElevatedButton(
                onPressed: () {
                  <span class="hljs-keyword">final</span> result = authService.login(
                      usernameController.text, passwordController.text);
                  message.value = result;
                },
                child: <span class="hljs-keyword">const</span> Text(<span class="hljs-string">'Login'</span>)),
            <span class="hljs-keyword">const</span> SizedBox(
              height: <span class="hljs-number">20</span>,
            ),
            Text(
              message.value,
              style: <span class="hljs-keyword">const</span> TextStyle(fontSize: <span class="hljs-number">24</span>),
            ),
          ],
        ),
      ),
    );
  }
}
</code></pre>
<h3 id="heading-3-testing-with-dependency-injection"><strong>3. Testing with Dependency Injection</strong></h3>
<p><strong>Step 1: Write Tests for the AuthService</strong></p>
<p>Create a test file, <code>auth_service_test.dart</code>. Make sure to put this under the <mark>test/</mark> directory.</p>
<pre><code class="lang-dart"><span class="hljs-keyword">import</span> <span class="hljs-string">'package:flutter_test/flutter_test.dart'</span>;
<span class="hljs-keyword">import</span> <span class="hljs-string">'package:my_app/auth_provider.dart'</span>; <span class="hljs-comment">// Adjust the import as per your project structure</span>
<span class="hljs-keyword">import</span> <span class="hljs-string">'package:hooks_riverpod/hooks_riverpod.dart'</span>;

<span class="hljs-keyword">void</span> main() {
  test(<span class="hljs-string">'AuthService login test'</span>, () {
    <span class="hljs-keyword">final</span> container = ProviderContainer();
    <span class="hljs-keyword">final</span> authService = container.read(authServiceProvider);

    expect(authService.login(<span class="hljs-string">'admin'</span>, <span class="hljs-string">'admin'</span>), <span class="hljs-string">'Login successful!'</span>);
    expect(authService.login(<span class="hljs-string">'user'</span>, <span class="hljs-string">'wrong_password'</span>), <span class="hljs-string">'Login failed!'</span>);
  });
}
</code></pre>
<p>So <code>ProviderContainer()</code> assists us with managing Providers and overriding them if needed. We don't need to do it in our regular files because <code>ProviderScope()</code> we using in <code>main.dart</code> already encompasses our entire application.</p>
<p><strong>Step 2: Mock Dependencies for Testing</strong></p>
<p>Create a mock version of <code>AuthService</code> for more complex testing scenarios.</p>
<pre><code class="lang-dart"><span class="hljs-keyword">import</span> <span class="hljs-string">'package:flutter_test/flutter_test.dart'</span>;
<span class="hljs-keyword">import</span> <span class="hljs-string">'package:my_app/auth_provider.dart'</span>;
<span class="hljs-keyword">import</span> <span class="hljs-string">'package:hooks_riverpod/hooks_riverpod.dart'</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MockAuthService</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">AuthService</span> </span>{
  <span class="hljs-meta">@override</span>
  <span class="hljs-built_in">String</span> login(<span class="hljs-built_in">String</span> username, <span class="hljs-built_in">String</span> password) {
    <span class="hljs-keyword">return</span> <span class="hljs-string">'Mock login for <span class="hljs-subst">$username</span>'</span>;
  }
}

<span class="hljs-keyword">void</span> main() {
  test(<span class="hljs-string">'AuthService mock test'</span>, () {
    <span class="hljs-keyword">final</span> container = ProviderContainer(
      overrides: [
        authServiceProvider.overrideWithValue(MockAuthService()),
      ],
    );
    <span class="hljs-keyword">final</span> authService = container.read(authServiceProvider);

    expect(authService.login(<span class="hljs-string">'test'</span>, <span class="hljs-string">'test'</span>), <span class="hljs-string">'Mock login for test'</span>);
  });
}
</code></pre>
<p>Perfect Now. If we want to execute the test. Just run the following command</p>
<pre><code class="lang-bash">flutter <span class="hljs-built_in">test</span>
</code></pre>
<h3 id="heading-summary">Summary:</h3>
<p>In this tutorial, we explored how to set up dependency injection with Riverpod, manage dependencies across your app, and write tests using dependency injection. These techniques help create modular, testable, and maintainable applications.</p>
]]></content:encoded></item><item><title><![CDATA[Flutter Riverpod Tutorial Part 7: Advanced Riverpod Patterns]]></title><description><![CDATA[In this tutorial we'll dive into advanced Riverpod patterns. Using the family Modifier Using the AutoDispose Modifier Keeping Providers Alive with…]]></description><link>https://harishkunchala.com/flutter-riverpod-tutorial-part-7-advanced-riverpod-patterns</link><guid isPermaLink="true">https://harishkunchala.com/flutter-riverpod-tutorial-part-7-advanced-riverpod-patterns</guid><category><![CDATA[Flutter]]></category><category><![CDATA[Riverpod]]></category><category><![CDATA[State Management ]]></category><dc:creator><![CDATA[Harish Kunchala]]></dc:creator><pubDate>Sun, 02 Jun 2024 07:00:25 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1717023406549/3a0e0580-0cad-48b9-a436-ccb1db42c238.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In this tutorial we'll dive into advanced Riverpod patterns.</p>
<h4 id="heading-sections-covered"><strong>Sections Covered:</strong></h4>
<ol>
<li><p>Using the <code>family</code> Modifier</p>
</li>
<li><p>Using the <code>AutoDispose</code> Modifier</p>
</li>
<li><p>Keeping Providers Alive with <code>keepAlive</code></p>
</li>
<li><p>Declaring Dependencies with <code>dependencies</code></p>
</li>
</ol>
<h3 id="heading-1-using-thefamily-modifier"><strong>1. Using the</strong><code>family</code> Modifier</h3>
<p>The <code>family</code> modifier allows you to create parameterized providers. This is useful when the provider's logic depends on external parameters.</p>
<p><strong>User Model Class:</strong></p>
<p>Let's create a user model class:</p>
<pre><code class="lang-dart"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">User</span> </span>{
  <span class="hljs-keyword">final</span> <span class="hljs-built_in">int</span> id;
  <span class="hljs-keyword">final</span> <span class="hljs-built_in">String</span> name;
  <span class="hljs-keyword">final</span> <span class="hljs-built_in">String</span> email;

  User({<span class="hljs-keyword">required</span> <span class="hljs-keyword">this</span>.id, <span class="hljs-keyword">required</span> <span class="hljs-keyword">this</span>.name, <span class="hljs-keyword">required</span> <span class="hljs-keyword">this</span>.email});

  <span class="hljs-keyword">factory</span> User.fromJson(<span class="hljs-built_in">Map</span>&lt;<span class="hljs-built_in">String</span>, <span class="hljs-built_in">dynamic</span>&gt; jsonUser) =&gt; User(
      id: jsonUser[<span class="hljs-string">'id'</span>], name: jsonUser[<span class="hljs-string">'name'</span>], email: jsonUser[<span class="hljs-string">'email'</span>]);
}
</code></pre>
<p><strong>userProvider with family:</strong></p>
<p>Now that we have the <code>User</code> let's also create a FutureProvider that gives us the user.</p>
<p>So couple of point in the following code</p>
<ol>
<li><p>We are using the family modifier.</p>
</li>
<li><p>Thanks to the family modifier, we are able to pass an argument to the FutureProvider.</p>
</li>
<li><p>In here we are passing <code>int userId</code></p>
</li>
<li><p>Now we are using the userId in the <code>http.get()</code> to get JSON data associated with the particular <code>userId</code></p>
</li>
</ol>
<pre><code class="lang-dart">
<span class="hljs-keyword">final</span> userProvider = FutureProvider.family&lt;User, <span class="hljs-built_in">int</span>&gt;((ref, userId) <span class="hljs-keyword">async</span> {
  <span class="hljs-keyword">final</span> apiResponse = <span class="hljs-keyword">await</span> http
      .<span class="hljs-keyword">get</span>(<span class="hljs-built_in">Uri</span>.parse(<span class="hljs-string">'https://jsonplaceholder.typicode.com/users/<span class="hljs-subst">$userId</span>'</span>));

  <span class="hljs-keyword">if</span> (apiResponse.statusCode == <span class="hljs-number">200</span>) {
    <span class="hljs-keyword">return</span> User.fromJson(jsonDecode(apiResponse.body));
  } <span class="hljs-keyword">else</span> {
    <span class="hljs-keyword">throw</span> Exception(<span class="hljs-string">'Unable to fetch the user'</span>);
  }
});
</code></pre>
<p><strong>userWidget:</strong></p>
<p>Let's create a <code>ConsumerWidget</code> that takes <code>userId</code> as a parameters and populates the users details in a <code>ListTile</code></p>
<pre><code class="lang-dart"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">UserWidget</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">HookConsumerWidget</span> </span>{
  <span class="hljs-keyword">final</span> <span class="hljs-built_in">int</span> userId;

  <span class="hljs-keyword">const</span> UserWidget({<span class="hljs-keyword">super</span>.key, <span class="hljs-keyword">required</span> <span class="hljs-keyword">this</span>.userId});

  <span class="hljs-meta">@override</span>
  Widget build(BuildContext context, WidgetRef ref) {
    <span class="hljs-keyword">final</span> userAsyncValue = ref.watch(userProvider(userId));
    <span class="hljs-keyword">return</span> Padding(
      padding: <span class="hljs-keyword">const</span> EdgeInsets.all(<span class="hljs-number">8</span>),
      child: userAsyncValue.when(
          data: (user) =&gt; ListTile(
                title: Text(user.name),
                subtitle: Text(user.email),
              ),
          error: (error, stackTrace) =&gt; Text(<span class="hljs-string">'Error: <span class="hljs-subst">${error.toString()}</span>'</span>),
          loading: () =&gt; <span class="hljs-keyword">const</span> CircularProgressIndicator()),
    );
  }
}
</code></pre>
<p>Finally I am creating a Screen where I can call multiple users</p>
<pre><code class="lang-dart"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">UsersFamilyList</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">StatelessWidget</span> </span>{
  <span class="hljs-keyword">const</span> UsersFamilyList({<span class="hljs-keyword">super</span>.key});

  <span class="hljs-meta">@override</span>
  Widget build(BuildContext context) {
    <span class="hljs-keyword">return</span> Scaffold(
      appBar: AppBar(
        title: <span class="hljs-keyword">const</span> Text(<span class="hljs-string">'Users List with Family Modifier'</span>),
      ),
      body: <span class="hljs-keyword">const</span> Column(
        children: [
          UserWidget(userId: <span class="hljs-number">1</span>),
          UserWidget(userId: <span class="hljs-number">2</span>),
          UserWidget(userId: <span class="hljs-number">3</span>),
        ],
      ),
    );
  }
}
</code></pre>
<p>Always remember that in this tutorial. We have covered two things:</p>
<ul>
<li><p><strong>family</strong>: Creates a parameterized provider that takes a user ID.</p>
</li>
<li><p><a target="_blank" href="http://FutureProvider.family"><strong>FutureProvider.family</strong></a>: Fetches user data based on the provided ID.</p>
</li>
</ul>
<p>Perfect Now we can see the output here:</p>
<p><img src="https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExb2x0a3Jqc2JxOHMxdGNlYjJwbHdkOTFsenJjN3dhb2p3cGFlcnNvNSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/BVtKcIf4L4VmoRXeDI/giphy.gif" alt="Family Provider" class="image--center mx-auto" /></p>
<p>You can find the source code here: <a target="_blank" href="https://github.com/khkred/go_router_riverpod_tutorials/commit/9111076854f1567b9dc3a564b4869f15a06f465e">Family Modifier</a></p>
<h3 id="heading-2-using-theautodispose-modifier"><strong>2. Using the</strong><code>AutoDispose</code> Modifier</h3>
<p>The <code>AutoDispose</code> modifier helps manage resources by automatically disposing of providers when they are no longer needed.</p>
<p><strong>State Provider with autoDispose modifier:</strong></p>
<p>First of all let's create a <code>StateProvider</code> with a autoDispose modifier. In here we are creating a basic counterProvider that also has auto dispose. So due to that the app should dispose of the provider whenever we are not using it.</p>
<pre><code class="lang-dart"><span class="hljs-keyword">final</span> counterAutoDisposeProvider = StateProvider.autoDispose((ref) =&gt; <span class="hljs-number">0</span>);
</code></pre>
<p><strong>Counter Page:</strong></p>
<p>Let's create a page where we will use the above provider. We'll create a basic page with a FAB that'll increment the value of the counter</p>
<pre><code class="lang-dart"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CounterPage</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">HookConsumerWidget</span> </span>{
  <span class="hljs-keyword">const</span> CounterPage({<span class="hljs-keyword">super</span>.key});

  <span class="hljs-meta">@override</span>
  Widget build(BuildContext context, WidgetRef ref) {
    <span class="hljs-keyword">final</span> count = ref.watch(counterAutoDisposeProvider);
    <span class="hljs-keyword">return</span> Scaffold(
      appBar: AppBar(
        title: <span class="hljs-keyword">const</span> Text(<span class="hljs-string">'Counter Auto Dispose'</span>),
      ),
      body: Center(
        child: Text(
          <span class="hljs-string">'Count: <span class="hljs-subst">$count</span>'</span>,
          style: <span class="hljs-keyword">const</span> TextStyle(fontSize: <span class="hljs-number">24</span>, fontWeight: FontWeight.bold),
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () =&gt; ref.read(counterAutoDisposeProvider.notifier).state++,
        child: <span class="hljs-keyword">const</span> Icon(Icons.add),
      ),
    );
  }
}
</code></pre>
<p>You can find the source code for the above section here: <a target="_blank" href="https://github.com/khkred/go_router_riverpod_tutorials/commit/ff7041514e5aab362360cb35bb727a98395c678c">autoDipose Modifier</a></p>
<p><mark>And as you can see the counter resets to 0. Every time we leave the screen</mark></p>
<p><img src="https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExOXBodW0wZGZ1N3Y4anE3aTJmZnI3Nm90NGw0Nmx0NWRiNzg2ODBqMyZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/CFc2akWWH9S8Lnt4IS/giphy.gif" alt="autoDispose Modifier" class="image--center mx-auto" /></p>
<h3 id="heading-3-keeping-providers-alive-with-keepalive"><strong>3. Keeping Providers Alive with</strong> <code>keepAlive</code></h3>
<p>The <code>keepAlive</code> method ensures that a provider remains active even when there are no listeners.</p>
<p><strong>Create the keepAlive Provider:</strong></p>
<pre><code class="lang-dart"><span class="hljs-keyword">final</span> counterKeepAliveProvider = StateProvider.autoDispose&lt;<span class="hljs-built_in">int</span>&gt;((ref) {
  ref.keepAlive();
  <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
});
</code></pre>
<p><strong>keepAlive Page:</strong></p>
<p>Let's create a basic page that'll read the counter similar to our previous page</p>
<pre><code class="lang-dart"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">KeepAliveCounterPage</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">HookConsumerWidget</span> </span>{
  <span class="hljs-keyword">const</span> KeepAliveCounterPage({<span class="hljs-keyword">super</span>.key});

  <span class="hljs-meta">@override</span>
  Widget build(BuildContext context, WidgetRef ref) {
    <span class="hljs-keyword">final</span> count = ref.watch(counterKeepAliveProvider);
    <span class="hljs-keyword">return</span> Scaffold(
      appBar: AppBar(
        title: <span class="hljs-keyword">const</span> Text(<span class="hljs-string">'Counter Auto Dispose'</span>),
      ),
      body: Center(
        child: Text(
          <span class="hljs-string">'Count: <span class="hljs-subst">$count</span>'</span>,
          style: <span class="hljs-keyword">const</span> TextStyle(fontSize: <span class="hljs-number">24</span>, fontWeight: FontWeight.bold),
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () =&gt; ref.read(counterKeepAliveProvider.notifier).state++,
        child: <span class="hljs-keyword">const</span> Icon(Icons.add),
      ),
    );
  }
}
</code></pre>
<p>You can find the source code here: <a target="_blank" href="https://github.com/khkred/go_router_riverpod_tutorials/commit/7985277d9ddff16d9bd7d8f9ab507f51164d2107">keepAlive Provider</a></p>
<p>And as you can see that the counter retains the value despite exiting the screen:</p>
<p><img src="https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExaHpzdWZ4YzNrMTRmMm5samU4MGoybTM5Z3V6Y280MjJqMDV4ZWRkeSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/yHPbDzZsTVL8rpED4F/giphy.gif" alt="keepAlive Provider" class="image--center mx-auto" /></p>
<h3 id="heading-4-declaring-dependencies-with-dependencies"><strong>4. Declaring Dependencies with</strong> <code>dependencies</code></h3>
<p>Declaring dependencies ensures that a provider depends on another provider and rebuilds when the dependent provider changes.</p>
<p><strong>Define a configProvider:</strong></p>
<pre><code class="lang-dart"><span class="hljs-keyword">import</span> <span class="hljs-string">'package:hooks_riverpod/hooks_riverpod.dart'</span>;

<span class="hljs-keyword">final</span> configProvider = StateProvider&lt;<span class="hljs-built_in">String</span>&gt;((ref) =&gt; <span class="hljs-string">'Config'</span>);

<span class="hljs-keyword">final</span> dependentProvider = Provider&lt;<span class="hljs-built_in">String</span>&gt;((ref) {
  <span class="hljs-keyword">final</span> config = ref.watch(configProvider);

  <span class="hljs-keyword">return</span> <span class="hljs-string">'Depends on <span class="hljs-subst">$config</span>'</span>;
});
</code></pre>
<p>Let's change the value on a screen and see if it changes it.</p>
<p><strong>Dependent Provider Page:</strong></p>
<p>In the following screen. Let's change the value of <code>configProvider</code> when a button is clicked. So that we can see the new value from <code>dependentProvider</code></p>
<pre><code class="lang-dart"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">DependentProviderPage</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">HookConsumerWidget</span> </span>{
  <span class="hljs-keyword">const</span> DependentProviderPage({<span class="hljs-keyword">super</span>.key});

  <span class="hljs-meta">@override</span>
  Widget build(BuildContext context, WidgetRef ref) {
    <span class="hljs-keyword">final</span> dependentString = ref.watch(dependentProvider);
    <span class="hljs-keyword">return</span> Scaffold(
        appBar: AppBar(
          title: <span class="hljs-keyword">const</span> Text(<span class="hljs-string">'Dependent Provider'</span>),
        ),
        body: SizedBox(
          width: <span class="hljs-built_in">double</span>.infinity,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text(
                dependentString,
                style: <span class="hljs-keyword">const</span> TextStyle(fontSize: <span class="hljs-number">24</span>),
              ),
              <span class="hljs-keyword">const</span> SizedBox(height: <span class="hljs-number">20</span>),
              ElevatedButton(
                  onPressed: () =&gt;
                      ref.read(configProvider.notifier).state = <span class="hljs-string">"New Config"</span>,
                  child: <span class="hljs-keyword">const</span> Text(<span class="hljs-string">'Change Config'</span>))
            ],
          ),
        ));
  }
}
</code></pre>
<p>You can find the source code here: <a target="_blank" href="https://github.com/khkred/go_router_riverpod_tutorials/commit/344b4a5e817ae6f2e0c9953576ccadf4535b21b8">dependent_provider</a></p>
<p>There you go:</p>
<p><img src="https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExa21yeTQ4MmJ2ZnpxNHdnZDdjNnVzcmluaHBxenV1cHdqZnFiaDF2eCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/0FYaVwRhlhHzJBf5Vh/giphy.gif" alt="Dependent Provider" class="image--center mx-auto" /></p>
<h3 id="heading-summary">Summary:</h3>
<p>So finally we have looked at various modifiers and advanced patterns from Riverpod. I hope these tutorials help you in better maintenance of your application state.</p>
]]></content:encoded></item><item><title><![CDATA[Flutter Riverpod Tutorial Part 6: Riverpod Scopes and Overriding Providers]]></title><description><![CDATA[In this tutorial, we'll explore the use of ProviderScope for creating isolated sections in your app and learn how to override providers for different…]]></description><link>https://harishkunchala.com/flutter-riverpod-tutorial-part-6-riverpod-scopes-and-overriding-providers</link><guid isPermaLink="true">https://harishkunchala.com/flutter-riverpod-tutorial-part-6-riverpod-scopes-and-overriding-providers</guid><category><![CDATA[Riverpod]]></category><category><![CDATA[Flutter]]></category><category><![CDATA[State Management ]]></category><dc:creator><![CDATA[Harish Kunchala]]></dc:creator><pubDate>Sat, 01 Jun 2024 07:00:52 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1717018223702/650b828c-1393-4ea3-8ee2-c1da480d144d.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In this tutorial, we'll explore the use of <code>ProviderScope</code> for creating isolated sections in your app and learn how to override providers for different configurations and testing. We'll also look at practical examples to illustrate these concepts.</p>
<h4 id="heading-sections-covered"><strong>Sections Covered:</strong></h4>
<ol>
<li><p>Using <code>ProviderScope</code> for Isolated Sections</p>
</li>
<li><p>Overriding Providers</p>
</li>
<li><p>Practical Examples</p>
</li>
</ol>
<h3 id="heading-section-1-using-providerscope-for-isolated-sections">Section 1: Using <code>ProviderScope</code> for Isolated Sections</h3>
<ul>
<li><p><strong>ProviderScope</strong> is used to create a scope within which providers can be accessed and managed.</p>
</li>
<li><p><mark>This allows for creating isolated sections in your app where specific providers can be overridden or reset without affecting the rest of the app.</mark></p>
</li>
</ul>
<p>Here's our code :</p>
<pre><code class="lang-dart"><span class="hljs-keyword">import</span> <span class="hljs-string">'package:flutter/material.dart'</span>;
<span class="hljs-keyword">import</span> <span class="hljs-string">'package:hooks_riverpod/hooks_riverpod.dart'</span>;


<span class="hljs-comment">//Let's define a simple counterProvider</span>
<span class="hljs-keyword">final</span> counterProvider = StateProvider&lt;<span class="hljs-built_in">int</span>&gt;((ref) =&gt; <span class="hljs-number">0</span>);

<span class="hljs-keyword">void</span> main() {
  runApp(
     <span class="hljs-keyword">const</span> ProviderScope(child: MyApp()),
  );
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyApp</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">StatelessWidget</span> </span>{
  <span class="hljs-keyword">const</span> MyApp({<span class="hljs-keyword">super</span>.key});

  <span class="hljs-meta">@override</span>
  Widget build(BuildContext context) {
    <span class="hljs-keyword">return</span> MaterialApp(
      darkTheme: ThemeData.dark(),
      themeMode: ThemeMode.dark,
      debugShowCheckedModeBanner: <span class="hljs-keyword">false</span>,
      home: <span class="hljs-keyword">const</span> HomePage(),
    );
  }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">HomePage</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">StatelessWidget</span> </span>{
  <span class="hljs-keyword">const</span> HomePage({<span class="hljs-keyword">super</span>.key});

  <span class="hljs-meta">@override</span>
  Widget build(BuildContext context) {
    <span class="hljs-keyword">return</span>  Scaffold(
      appBar: AppBar(title: <span class="hljs-keyword">const</span> Text(<span class="hljs-string">'Riverpod ProviderScope Example'</span>),
      ),
      body: SizedBox(width: <span class="hljs-built_in">double</span>.infinity,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          <span class="hljs-keyword">const</span> ProviderScope(child: CounterWidget()),
          ProviderScope(
              overrides: [counterProvider.overrideWith((ref) =&gt; <span class="hljs-number">100</span>)],
              child: <span class="hljs-keyword">const</span> CounterWidget()),
        ],
      ),),
    );
  }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CounterWidget</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">HookConsumerWidget</span> </span>{
  <span class="hljs-keyword">const</span> CounterWidget({<span class="hljs-keyword">super</span>.key});

  <span class="hljs-meta">@override</span>
  Widget build(BuildContext context, WidgetRef ref) {

    <span class="hljs-keyword">final</span> counter = ref.watch(counterProvider);
    <span class="hljs-keyword">return</span> Column(
      children: [
        Text(<span class="hljs-string">'Value: <span class="hljs-subst">$counter</span>'</span>,
        style: <span class="hljs-keyword">const</span> TextStyle(fontWeight: FontWeight.bold,
        fontSize: <span class="hljs-number">24</span>),),

        ElevatedButton(onPressed: (){
          ref.read(counterProvider.notifier).state++;
        }, child: <span class="hljs-keyword">const</span> Text(<span class="hljs-string">'Increment'</span>),)
      ],
    );
  }
}
</code></pre>
<p>So these are the two things we used in the above code:</p>
<ul>
<li><p><strong>ProviderScope</strong>: Creates an isolated scope for providers.</p>
</li>
<li><p><strong>overrides</strong>: Allows you to override providers within the scope.<br />  You can find the source code here: <a target="_blank" href="https://github.com/khkred/go_router_riverpod_tutorials/tree/95ad2a63e25a5748630cbde2ddee526e0e0d3ade">ProviderScope Override</a></p>
</li>
</ul>
<p>And as you can see the app works perfectly with different values</p>
<p>You can see the output here:</p>
<p><img src="https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExc3FjNXhxMjR2b3pib28wNTJoZTBkdDlxOXZhb3U2Ymx4MGRlZmc5MCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/a8PwJQYwfWlafdoumT/giphy.gif" alt="Override ProviderScope" class="image--center mx-auto" /></p>
<h3 id="heading-section-2-overriding-providers">Section 2: Overriding Providers</h3>
<p>Overriding providers is useful for testing or when you need different configurations for specific parts of your app.</p>
<p><mark>You can override providers by using the </mark> <code>overrides</code> <mark> parameter in </mark> <code>ProviderScope</code><mark>.</mark></p>
<pre><code class="lang-dart"><span class="hljs-keyword">import</span> <span class="hljs-string">'package:flutter/material.dart'</span>;
<span class="hljs-keyword">import</span> <span class="hljs-string">'package:hooks_riverpod/hooks_riverpod.dart'</span>;

<span class="hljs-keyword">void</span> main() {
  runApp(
    <span class="hljs-keyword">const</span> ProviderScope(child: MyApp()),
  );
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyApp</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">StatelessWidget</span> </span>{
  <span class="hljs-keyword">const</span> MyApp({<span class="hljs-keyword">super</span>.key});

  <span class="hljs-meta">@override</span>
  Widget build(BuildContext context) {
    <span class="hljs-keyword">return</span> MaterialApp(
      darkTheme: ThemeData.dark(),
      themeMode: ThemeMode.dark,
      debugShowCheckedModeBanner: <span class="hljs-keyword">false</span>,
      home: <span class="hljs-keyword">const</span> HomePage(),
    );
  }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">HomePage</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">StatelessWidget</span> </span>{
  <span class="hljs-keyword">const</span> HomePage({<span class="hljs-keyword">super</span>.key});

  <span class="hljs-meta">@override</span>
  Widget build(BuildContext context) {
    <span class="hljs-keyword">return</span>  Scaffold(
      appBar: AppBar(title: <span class="hljs-keyword">const</span> Text(<span class="hljs-string">'Overriding Providers Example'</span>),
      ),
      body: Column(
        children: [
          <span class="hljs-keyword">const</span> ProviderScope(child: GreetingWidget()),
          ProviderScope(
              overrides: [greetingProvider.overrideWithValue(<span class="hljs-string">'Hello Riverpod'</span>)],
              child: <span class="hljs-keyword">const</span> GreetingWidget()),
        ],
      ),
    );
  }
}

<span class="hljs-keyword">final</span> greetingProvider = Provider&lt;<span class="hljs-built_in">String</span>&gt;((ref) =&gt; <span class="hljs-string">'Hello Word!!'</span>);

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">GreetingWidget</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">HookConsumerWidget</span> </span>{
  <span class="hljs-keyword">const</span> GreetingWidget({<span class="hljs-keyword">super</span>.key});

  <span class="hljs-meta">@override</span>
  Widget build(BuildContext context, WidgetRef ref) {
    <span class="hljs-keyword">final</span> greeting = ref.watch(greetingProvider);

    <span class="hljs-keyword">return</span> Padding(
      padding: <span class="hljs-keyword">const</span> EdgeInsets.all(<span class="hljs-number">16.0</span>),
      child: Text(
        greeting,
        style: <span class="hljs-keyword">const</span> TextStyle(fontSize: <span class="hljs-number">24</span>),
      ),
    );
  }
}
</code></pre>
<p>You can find the source code here: <a target="_blank" href="https://github.com/khkred/go_router_riverpod_tutorials/commit/06dd88370c951ddac907cd1e69baea0225741bed">Overriding</a></p>
<p>Use cases for the Overriding:</p>
<ol>
<li><p>Isolated configurations</p>
</li>
<li><p>Overriding for Testing</p>
</li>
</ol>
]]></content:encoded></item></channel></rss>