<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Soo Kim on Medium]]></title>
        <description><![CDATA[Stories by Soo Kim on Medium]]></description>
        <link>https://medium.com/@mookypoo?source=rss-a32d589adcc9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*acDAdNojxjpFElKHV1W41Q.jpeg</url>
            <title>Stories by Soo Kim on Medium</title>
            <link>https://medium.com/@mookypoo?source=rss-a32d589adcc9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 15:03:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mookypoo/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Spring Boot : Connect to Multiple Databases]]></title>
            <link>https://mookypoo.medium.com/spring-boot-connect-to-multiple-databases-4cd56773fbcc?source=rss-a32d589adcc9------2</link>
            <guid isPermaLink="false">https://medium.com/p/4cd56773fbcc</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[configuration]]></category>
            <category><![CDATA[jpa]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Soo Kim]]></dc:creator>
            <pubDate>Thu, 25 Apr 2024 00:13:25 GMT</pubDate>
            <atom:updated>2024-04-25T00:13:25.323Z</atom:updated>
            <content:encoded><![CDATA[<h3>Spring Boot : Connect to Multiple Databases</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/585/1*69OXNxfqIfRNhnBRqTH0Gg.png" /></figure><p>During my project, I wanted to connect to both my local database and another database, and while I did find a plethora of information online, I had still struggled to make the code work because none of them worked perfectly.</p><p>In the end, it was a pretty simple configuration that to be honest, I still need to properly understand why. But for anyone else struggling, here’s how I did it. <a href="https://github.com/mookypoo/multiple-databases">(Full Code)</a></p><h4><strong>Project Structure</strong></h4><p>I created two entities: student and teacher, each of which will connect to a different database — demo and demo_teacher respectively.</p><p>This is my<strong> application.yml</strong>.</p><pre>server:<br>  port: 9202<br><br>spring:<br>  &#39;profiles.active&#39;: dev<br>  config:<br>    import: secrets.yml<br><br>  jpa:<br>    hibernate:<br>      ddl-auto: none<br>    show-sql: true<br>    properties:<br>      hibernate:<br>        &#39;[format_sql]&#39;: true<br>        # CamelCase to Underscores naming is not done by default with multiple db<br>        &#39;[physical_naming_strategy]&#39;: org.hibernate.boot.model.naming.CamelCaseToUnderscoresNamingStrategy</pre><p>Although ‘<strong>jpa.properties.hibernate.physical_naming_strategy</strong>’ property is not necessary with just one database, I found that when I connected multiple databases, entity/table names (e.g. firstName) did not get converted to underscore naming (first_name), which is why I added the property (instead of using Column(name = “first_name”) everywhere).</p><p>Here’s my <strong>secret.yml</strong>.</p><pre># make sure this file is in gitignore!<br>spring:<br>  &#39;config.activate.on-profile&#39;: dev<br><br>  # make sure to create metadata <br>  datasource:<br>    student:<br>      driver-class-name: org.mariadb.jdbc.Driver<br>      # if you have multiple datasources --&gt; instead of url --&gt; jdbc-url<br>      jdbc-url: jdbc:{your_jdbc_url}/demo<br>      username: root<br>      password: your_password<br>    teacher:<br>      driver-class-name: org.mariadb.jdbc.Driver<br>      jdbc-url: jdbc:{your_jdbc_url}/demo_teacher<br>      username: root<br>      password: your_password</pre><p>Initially, your datasource properties would look like this:</p><pre>spring:<br>  datasource:<br>    driver-class-name: dcn<br>    url: url <br>    username: u<br>    password: p</pre><p>Whichever way you decide to format your database properties, make sure that you have the correct property names, including ‘<strong>jdbc-ur</strong>l’ (not url).</p><h4>Data Source Config</h4><p>Each of my data sources (the two databases) will have separate configuration files.</p><p><strong>StudentDataSourceConfig.java <br></strong>This will be the primary — or default — datasource. Note that each bean has a <strong>Primary</strong> annotation.</p><pre>package com.mooky.multipledatabases.global.config;<br><br>import javax.sql.DataSource;<br><br>import org.springframework.beans.factory.annotation.Qualifier;<br>import org.springframework.boot.context.properties.ConfigurationProperties;<br>import org.springframework.boot.jdbc.DataSourceBuilder;<br>import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;<br>import org.springframework.context.annotation.Bean;<br>import org.springframework.context.annotation.Configuration;<br>import org.springframework.context.annotation.Primary;<br>import org.springframework.data.jpa.repository.config.EnableJpaRepositories;<br>import org.springframework.orm.jpa.JpaTransactionManager;<br>import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;<br>import org.springframework.transaction.PlatformTransactionManager;<br><br>import jakarta.persistence.EntityManagerFactory;<br><br>@EnableJpaRepositories(<br>  basePackages = {&quot;com.mooky.multipledatabases.domain.student&quot;},<br>  entityManagerFactoryRef = &quot;studentEntityManagerFactory&quot;,<br>  transactionManagerRef = &quot;studentTransactionManager&quot;<br>)<br>@Configuration<br>public class StudentDataSourceConfig {<br><br>  @Primary<br>  @Bean<br>  @ConfigurationProperties(prefix = &quot;spring.datasource.student&quot;)<br>  DataSource studentDataSource() {<br>    return DataSourceBuilder.create().build();<br>  }<br><br>  @Primary<br>  @Bean<br>  LocalContainerEntityManagerFactoryBean studentEntityManagerFactory(<br>      EntityManagerFactoryBuilder builder,<br>      @Qualifier(&quot;studentDataSource&quot;) DataSource dataSource) {<br>    return builder<br>        .dataSource(dataSource)<br>        .packages(&quot;com.mooky.multipledatabases.domain&quot;)<br>        .persistenceUnit(&quot;student&quot;)<br>        .build();<br>  }<br><br>  @Bean<br>  PlatformTransactionManager studentTransactionManager(<br>      @Qualifier(&quot;studentEntityManagerFactory&quot;) EntityManagerFactory localEntityManagerFactory) {<br>    return new JpaTransactionManager(localEntityManagerFactory);<br>  }<br><br>}</pre><p><strong>‘@EnableJpaRepositories’ </strong><br>(1) declare which packages to attach this data source<br>(2) link EntityManagerFactory and TransactionManager</p><p>‘<strong>studentDataSource()’<br></strong>(3) create the datasource and and bind it to the correct property</p><p>‘<strong>studentEntityManagerFactory()</strong>’<br>(4) create <strong>JPA EntityManager,</strong> which manages and searches for entities <br>- There are two types of EntityManager: <strong>container-managed</strong> and application-managed. This method create the a container-managed entity manager.<br>- <strong>attach datasource, packages to scan</strong>, and not necessary but as advised by the docs, give separate persistence unit names</p><p>‘<strong>studentTransactionManager()’<br></strong>(5) create a <strong>PlatformTransactionManager,</strong> which allows you to do transactional work (such as creating, updating, and deleting) on the entities</p><h4><strong>TeacherDataSourceConfig.java</strong></h4><p>This is basically the same as the student data source config but with different datasource and names.</p><pre>@Configuration<br>@EnableJpaRepositories(<br>    basePackages = { &quot;com.mooky.multipledatabases.domain.teacher&quot; },<br>    entityManagerFactoryRef = &quot;teacherEntityManagerFactory&quot;,<br>    transactionManagerRef = &quot;teacherTransactionManager&quot;<br>  )<br>public class TeacherDataSourceConfig {<br>  <br>  @Bean<br>  @ConfigurationProperties(prefix = &quot;spring.datasource.teacher&quot;)<br>  DataSource teacherDataSource() {<br>    return DataSourceBuilder.create().build();<br>  }<br><br>  @Bean<br>  LocalContainerEntityManagerFactoryBean teacherEntityManagerFactory(<br>      EntityManagerFactoryBuilder builder,<br>      @Qualifier(&quot;teacherDataSource&quot;) DataSource dataSource) {<br>    return builder<br>        .dataSource(dataSource)<br>        .packages(&quot;com.mooky.multipledatabases.domain&quot;)<br>        .persistenceUnit(&quot;teacher&quot;)<br>        .build();<br>  }<br><br>  @Bean<br>  PlatformTransactionManager teacherTransactionManager(<br>      @Qualifier(&quot;teacherEntityManagerFactory&quot;) EntityManagerFactory teacherEntityManagerFactory) {<br>    return new JpaTransactionManager(teacherEntityManagerFactory);<br>  }<br>}</pre><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4cd56773fbcc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tips for Flutter: HTTP, Factory, List]]></title>
            <link>https://mookypoo.medium.com/tips-for-flutter-http-factory-list-238bc6ab14b6?source=rss-a32d589adcc9------2</link>
            <guid isPermaLink="false">https://medium.com/p/238bc6ab14b6</guid>
            <category><![CDATA[https]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[isolate]]></category>
            <category><![CDATA[json]]></category>
            <dc:creator><![CDATA[Soo Kim]]></dc:creator>
            <pubDate>Mon, 11 Dec 2023 01:39:25 GMT</pubDate>
            <atom:updated>2023-12-11T01:39:25.081Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MApYKNI2uEdDvIBwIihOow.jpeg" /><figcaption><a href="https://www.freecodecamp.org/news/what-is-http/">https://www.freecodecamp.org/news/what-is-http/</a></figcaption></figure><p>I’ve decided to move on from Flutter professionally…but before I do, I wanted to make some posts about practices that I have implemented in my coding. This is mostly for personal use, in case I want to come back to Flutter and need a quick reminder, but maybe it might help others improve their coding skills too :)</p><p>Today, I will be showing my go-to file for HTTP requests, and some methods I use to ease the process of converting the response to classes. I will not be posting the full github repository as these are snippets from different projects.</p><p>Here’s my <strong>folder structure .</strong></p><pre>lib<br>- class<br>- providers<br>- repository <br>  - connect (http request)<br>  - custom_types (json, conversion methods)<br>  - sqflite_repo <br>  ..etc<br>- service (methods to be utilized in provider)<br>- views<br></pre><pre>typedef Json&lt;Key, Value&gt; = Map&lt;String, dynamic&gt;;<br><br>enum ReqMethod {<br>  get, post, put, delete, patch<br>}<br><br>----------------------------<br><br>Connect(){<br>  if (kDebugMode || kProfileMode) {<br>    this._baseUrl = &quot;&quot;;<br>  }<br>}<br><br>String _baseUrl = &quot;&quot;;<br><br>String _path(String path){<br>  String _path = path.trim();<br>  if (!_path.startsWith(&quot;/&quot;)) _path = &quot;/&quot; + _path;<br>  return _path;<br>}</pre><p>Some basics:<br>1. <strong>typedef Json</strong> —shortens my coding from Map&lt;String, dynamic&gt; → Json everywhere</p><p>2. <strong>ReqMethod </strong>— enum for different types of http request methods, because I am not a fan of using String (eg. method: “POST”). <strong>This allows me to make ONE request method </strong>instead of making multiple methods for each http request method.</p><p>3. <strong>baseUrl </strong>— I set my baseUrl to dev server url when I’m developing or testing on profile mode, so that I don’t have to constantly change it</p><p>4.<strong> path()</strong> — we are bound to make mistakes, and this method <strong>allows all paths to start with “/” and trim for any spaces</strong></p><p>Here is my <strong>all-in-one method for API requests</strong>. Because this method has a try catch block, you will not have to implement a try-catch anywhere else. There’s definitely room for improvement and please let me know of any suggestions!</p><pre>/// default request method: get<br>Future&lt;Json&gt; reqAPIServer({<br>  ReqMethod reqMethod = ReqMethod.get,<br>  required String path,<br>  void Function(ReqModel)? cb,<br>  Map&lt;String, String&gt;? headers,<br>  dynamic body,<br>  required String? accessToken,<br>}) async {<br>  try {<br>    final Uri _url = Uri.parse(this._baseUrl + this._path(path));<br>    final Map&lt;String, String&gt; _headers = {...headers ?? {}, &quot;content-type&quot;:&quot;application/json&quot;, if (accessToken != null) &quot;authorization&quot;: &quot;Bearer $accessToken&quot;};<br>    const Duration _timeOutLimit = Duration(seconds: 13);<br>    FutureOr&lt;http.Response&gt; _onTimeOut() =&gt; http.Response(json.encode({&quot;error&quot;: &quot;timeout&quot;}), 408);<br><br>    http.Response? _res;<br>    if (reqMethod == ReqMethod.get) {<br>      _res = await http.get(_url, headers: _headers).timeout(_timeOutLimit, onTimeout: _onTimeOut);<br>    } else if (reqMethod == ReqMethod.post) {<br>      _res = await http.post(_url, headers: _headers, body: json.encode(body)).timeout(_timeOutLimit, onTimeout: _onTimeOut);<br>    } else if (reqMethod == ReqMethod.delete) {<br>      _res = await http.delete(_url, headers: _headers).timeout(_timeOutLimit, onTimeout: _onTimeOut);<br>    } else if (reqMethod == ReqMethod.put) {<br>      _res = await http.put(_url, headers: _headers, body: json.encode(body)).timeout(_timeOutLimit, onTimeout: _onTimeOut);<br>    } else if (reqMethod == ReqMethod.patch) {<br>      _res = await http.patch(_url, headers: _headers, body: json.encode(body)).timeout(_timeOutLimit, onTimeout: _onTimeOut);<br>    }<br><br>    if (_res == null) return {&quot;error&quot;: &quot;no valid request method provided&quot;};<br>    if (cb != null) cb(ReqModel(statusCode: _res.statusCode));<br>    <br>    /// error from server <br>    if (_res.headers[&quot;content-type&quot;] == &quot;text/html; charset=utf-8&quot;) return {&quot;error&quot;: _res.body, &quot;statusCode&quot;: _res.statusCode };<br>    /// 한국어 때문에 utf8.decode()<br>    final Json _decodedBody = json.decode(utf8.decode(_res.bodyBytes)) as Json; <br>    if (kDebugMode|| kProfileMode) print(&quot;API RES: path - $path, body: $body&quot;);<br>    <br>    /// the keys (&quot;error&quot;, &quot;response&quot;) will differ depending on your own server responses<br>    if (_decodedBody.containsKey(&quot;error&quot;)) {<br>      if (kDebugMode|| kProfileMode) print(_decodedBody[&quot;error&quot;]);<br>      return {&quot;error&quot;: _decodedBody[&quot;error&quot;], &quot;statusCode&quot;: _res.statusCode };<br>    }<br><br>    if (kDebugMode|| kProfileMode) {<br>      final String _resToString = _decodedBody[&quot;response&quot;].toString();<br>      /// android has a maximum log size so divide up the log to print everything (there&#39;s gaps in between...)<br>      if (Platform.isAndroid &amp;&amp; _resToString.length &gt; 853) {<br>        final int _splitLength = (_resToString.length / 853).ceil();<br>        List.generate(_splitLength, (int index) {<br>          print(_resToString.substring(index * 853, index == _splitLength - 1 ? _resToString.length : (index + 1) * 853));<br>        });<br>      } else {<br>        print(&quot;response: ${_resToString}\n&quot;);<br>      }<br>    }<br>    return {&quot;success&quot;: _decodedBody[&quot;response&quot;]};<br>  } catch (e) {<br>    if (e.runtimeType == SocketException) return { &quot;error&quot;: &quot;서버와 연결이 원활하지 않습니다. 다시 시도해주세요.&quot; }; <br>    return { &quot;error&quot;: e };  <br>  }<br>}</pre><p>Obviously, you would need to tune the method depending on how you receive responses from your server, but I think it can serve as a general template.</p><h4>Converting Response to Class</h4><p>For me, most of this happens in the “service” files. Here is an example of a SocialAccount class I’ll be using throughout this part.</p><pre>class SocialAccount {<br>  final SocialType socialType;<br>  final String accountName;<br>  final String socialLink;<br><br>  const SNSAccount({required this.socialLink, required this.socialType, required this.accountName});<br><br>  String get linkText =&gt; this.socialType == SNSType.instagram ?  &quot;@&quot; + this.socialLink : &quot;website&quot;;<br><br>  factory SocialAccount.fromJson(Json json){<br>    SocialType _socialType;<br>    switch ((json[&quot;socialType&quot;] ?? &quot;&quot;).toString().toLowerCase()) {<br>      case &quot;instagram&quot; : _snsType = SocialType.instagram;<br>      case &quot;youtube&quot;: _snsType = SocialType.youtube;<br>      default : _snsType = SocialType.website;<br>    }<br>    return SocialAccount(<br>      socialLink: (json[&quot;socialLink&quot;] ?? &quot;&quot;).toString(),<br>      socialType: _snsType,<br>      accountName: (json[&quot;accountName&quot;] ?? &quot;&quot;).toString(),<br>    );<br>  }<br>}</pre><p>FYI: <br>- for my json, <strong>I always assume the key might be nullable due to a mistake</strong>, which is why in all my json conversion methods, I make it null-proof (eg. (json[“socialLink”] ?? “”).toString())</p><ol><li><strong>Converting response to class using factory method</strong><br>This portion is pretty straightforward. You just put respective json as the factory argument.</li></ol><pre>Future&lt;Json&gt; fetchSocialInfo() async {<br>  final Json _res = await this._connect.reqAPIServer(path: &quot;...&quot;, accessToken: accessToken);<br>  if (true for successful response) {<br>    return {&quot;socialAccount&quot;: SocialAccount.fromJson(_res[&quot;&quot;]) };<br>  }<br>  if (false for error) {<br>    /// account for respective errors and its error messages <br>    return {&quot;error&quot;: _errorMsg };<br>  }<br>  return _res;<br>}</pre><p>2. <strong>Converting Json list to a list of a class</strong></p><p>After writing about 5 individual methods for converting json list to a specific class using the factory constructor, I wanted to be more efficient. For example, a user might have several social accounts (hence, a json list of social accounts and its info). Therefore, I made a method that takes a json list and the factory constructor, which returns List&lt;T&gt;.</p><pre>static List&lt;T&gt; convertJsonListToClass&lt;T&gt;({required List&lt;dynamic&gt; jsonList, required T Function(Json) factory}) {<br>  final List&lt;Json&gt; _jsonList = List&lt;Json&gt;.from(jsonList);<br>  List&lt;T&gt; _list = [];<br>  _jsonList.forEach((Json json) =&gt; _list.add(factory(json)));<br>  return _list;<br>}<br><br>---------------------------------------------<br><br>class User {<br>  List&lt;SocialAccount&gt; socialAccounts;<br><br>  factory User.fromJson(Json json) =&gt; User(<br>    socialAccounts: convertJsonListToClass&lt;SocialAccount&gt;(jsonList: json[&quot;socialAccounts&quot;], factory: SocialAccounts.fromJson)<br>  );<br>}</pre><p>3. <strong>Using Isolate to convert Json list</strong></p><p>I use the method in 2 mostly within other factories, and in most “service” files, I use an isolate to convert the json list. Although I implemented the Isolate in hopes that it would increase performance, I did not have time to actually compare the results.</p><pre>static Future&lt;List&lt;T&gt;?&gt; convertJsonToClassInIsolate&lt;T&gt;({required List&lt;dynamic&gt; jsonList, required T Function(Json) factory}) async {<br>  try {<br>    return await Isolate.run(() {<br>      final List&lt;Json&gt; _jsonList = List&lt;Json&gt;.from(jsonList);<br>      List&lt;T&gt; _list = [];<br>      _jsonList.forEach((Json json) =&gt; _list.add(factory(json)));<br>      return _list;<br>    });<br>  } catch (e) {<br>    if (kDebugMode|| kProfileMode) print(&quot;error - convertJsonInIsolate: ${e.toString()}&quot;);<br>    return null;<br>  }<br>}</pre><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=238bc6ab14b6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter: Custom Draggable Bottom Sheet (2)]]></title>
            <link>https://mookypoo.medium.com/flutter-custom-draggable-bottom-sheet-2-da64694b706e?source=rss-a32d589adcc9------2</link>
            <guid isPermaLink="false">https://medium.com/p/da64694b706e</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[custom]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[bottomsheet]]></category>
            <category><![CDATA[dart]]></category>
            <dc:creator><![CDATA[Soo Kim]]></dc:creator>
            <pubDate>Sat, 10 Jun 2023 07:41:06 GMT</pubDate>
            <atom:updated>2023-06-10T07:41:06.527Z</atom:updated>
            <content:encoded><![CDATA[<h4>Follow slow drag movements &amp; scroll fast swipes &amp; control inner scrollable view</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IWdgSIJKoMaB_MGnfrztpg.jpeg" /></figure><p>My l<a href="https://medium.com/@mookypoo/flutter-custom-draggable-bottom-sheet-94274ee91008">ast custom draggable bottom sheet post</a> was a pretty simple one where the bottom sheet automatically goes up or down depending on the user’s scroll. This time, it’s slightly more advanced in that it follows the user’s finger movements (drag) when its slow, and when the user swipes fast, the bottom sheet scrolls up or down automatically. Also, the inner part of the bottom sheet, which is a scrollable view, is controlled.</p><p><a href="https://youtube.com/shorts/dLDTkOIHJkc?feature=share">Custom Draggable Bottom Sheet (2)</a></p><p>Here is the <a href="https://github.com/mookypoo/custom_draggable_bottom_sheet">Github repository</a>.</p><p>Table of Contents:</p><ul><li>Main.dart</li><li>Bottom Sheet Container UI</li><li>Controlling the Bottom Sheet Container <br>- save initial position<br>- following drag gesture</li><li>Continuing the User’s Drag Gesture<br>- scroll to top after certain point<br>- continue scroll based on user’s velocity</li><li>Body as List<br>- main.dart<br>- bottom sheet body<br>- _isAtTop<br>- following drag gesture <br>- continue scroll</li></ul><h3>Main.dart</h3><p>This is Main.dart (body is not a list).</p><pre>class Home extends StatelessWidget {<br>  Home({Key? key}) : super(key: key);<br><br>  final Widget _header = Container(<br>    alignment: Alignment.center,<br>    decoration: const BoxDecoration(<br>      color: Colors.white,<br>      borderRadius: BorderRadius.only(topLeft: Radius.circular(25.0), topRight: Radius.circular(25.0)),<br>    ),<br>    child: Column(<br>      crossAxisAlignment: CrossAxisAlignment.center,<br>      children: &lt;Widget&gt;[<br>        Container(<br>          margin: const EdgeInsets.only(top: 6.0, bottom: 8.0),<br>          width: 40.0, // 10.w<br>          height: 6.5, // 0.8.h<br>          decoration: BoxDecoration(color: Colors.black45, borderRadius: BorderRadius.circular(50)),<br>        ),<br>        Text(&quot;Drag the header to see bottom sheet&quot;),<br>      ],<br>    ),<br>  );<br><br>  @override<br>  Widget build(BuildContext context) {<br>    final Size _size = MediaQuery.of(context).size;<br><br>    return Scaffold(<br>      backgroundColor: Colors.white,<br>      body: Stack(<br>        children: &lt;Widget&gt;[<br>          Container(height: _size.height),<br>          Positioned(<br>            left: 0.0,<br>            right: 0.0,<br>            bottom: 0.0,<br>            child: CustomBottomSheet(<br>              maxHeight: _size.height * 0.745,<br>              headerHeight: 50.0,<br>              header: this._header,<br>              borderRadius: BorderRadius.only(topLeft: Radius.circular(25.0), topRight: Radius.circular(25.0)),<br>              boxShadow: &lt;BoxShadow&gt;[<br>                BoxShadow(color: Colors.black26, blurRadius: 10.0, spreadRadius: -1.0, offset: Offset(0.0, 3.0)),<br>                BoxShadow(color: Colors.black26, blurRadius: 4.0, spreadRadius: -1.0, offset: Offset(0.0, 0.0)),<br>              ],<br>              body: Container(<br>                decoration: const BoxDecoration(<br>                  border: Border(top: BorderSide(color: Colors.grey, width: 1.0)),<br>                ),<br>                alignment: Alignment.center,<br>                width: _size.width,<br>                height: _size.height * 0.6,<br>                child: Text(&quot;body&quot;),<br>              ),<br>            ),<br>          )<br>        ],<br>      ),<br>    );<br>  }<br>}</pre><h3>Bottom Sheet Container UI</h3><p>Here is the UI of the bottom sheet itself (the container). It is constrained by maxHeight and minHeight, both including the header, if any. The actual height of the bottom sheet is as follows:</p><p>headerHeight + <strong>_bodyHeight (which will be defined as the user drags the bottom sheet)</strong> + bottomViewPadding</p><p>The boolean “_isAtTop” is there to distinguish the bottom sheet container from the inner list and the scroll controller is for the list as well. So if you don’t plan on having a list as the body, that part is unnecessary.</p><pre>final ScrollController _scrollController = ScrollController();<br>Animation? _animation;<br>AnimationController? _animationController;<br><br>double _bodyHeight = 0.0;<br>bool _isAtTop = false;<br>double _initPosition = 0.0;<br><br>@override<br>Widget build(BuildContext context) {<br>  return GestureDetector(<br>    onVerticalDragStart: this._saveInitPosition,<br>    onVerticalDragUpdate: this._followDrag,<br>    child: SingleChildScrollView(<br>      controller: this._isAtTop ? null : this._scrollController,<br>      child: Container(<br>        padding: this.widget.hasBottomViewPadding ? EdgeInsets.only(bottom: MediaQuery.of(context).viewPadding.bottom) : null,<br>        width: MediaQuery.of(context).size.width,<br>        constraints: BoxConstraints(<br>          maxHeight: this.widget.maxHeight + this.widget.headerHeight,<br>          minHeight: this.widget.headerHeight + this.widget.minHeight<br>        ),<br>        decoration: BoxDecoration(<br>          color: this.widget.bgColor,<br>          borderRadius: this.widget.borderRadius,<br>          boxShadow: this.widget.boxShadow,<br>        ),<br>        height: this.widget.headerHeight + this._bodyHeight + (this.widget.hasBottomViewPadding ? MediaQuery.of(context).viewPadding.bottom : 0.0),<br>        child: Column(<br>          mainAxisSize: MainAxisSize.min,<br>          children: &lt;Widget&gt;[<br>            Container(<br>              height: this.widget.headerHeight,<br>              alignment: Alignment.center,<br>              child: this.widget.header,<br>            ),<br>            Expanded(<br>              child: this.widget.body,<br>            ),<br>          ],<br>        ),<br>      ),<br>    ),<br>  );<br>}</pre><h3>Controlling the Bottom Sheet Container</h3><p>I will initially go over this section under the assumption that the body is not a list and therefore, you do not need to use the _isAtTop boolean.</p><h4>Save Initial Position</h4><p>First, use GestureDetector’s <strong>onVerticalDragStart</strong> to save the initial position.</p><pre>void _saveInitPosition(DragStartDetails d) =&gt; this._initPosition = d.globalPosition.dy;</pre><h4>Following Drag Gesture</h4><p>When the drag updates, find out the <strong>difference between the initial position and the updated position</strong>. If the difference is positive, the user dragged up, and if the difference is negative, the user has dragged down. Then, you want to add this difference to the current _bodyHeight. Set state the new _bodyHeight and reassign _initPosition to be the current offset.</p><p>Below, you’ll also find conditional statements to constrain _bodyHeight.</p><pre>void _followDrag(DragUpdateDetails d) {<br>  final double _movedAmount = this._initPosition - d.globalPosition.dy; <br>  <br>  double _newHeight = this._bodyHeight + _movedAmount;<br>  if (_newHeight &lt; 0.0) _newHeight = 0.0; // makes sure the bodyHeight does not fall under 0.0<br>  if (_newHeight &gt; this.widget.maxHeight) _newHeight = this.widget.maxHeight; // makes sure the bodyHeight does not go above max height<br>  this._bodyHeight = _newHeight;<br>  this.setState(() {});<br>  this._initPosition = d.globalPosition.dy;<br>}</pre><h3>Continuing the User’s Drag Gesture</h3><p>Depending on the user’s drag velocity, or the position at which the user stopped dragging, you might want to continue the drag and scroll to a certain position. In order to do this,<strong> I assigned a value to _animation, and as it animates, assign a value to _bodyHeight and set state until it reaches the desired position.</strong></p><p>**There was one problem that I couldn’t figure out how to solve: sometimes when the user lets go of the screen, the finger comes off the screen after slightly touching the other direction…so even with velocity or _movedAmount, there was room for error.</p><h4>Scroll to Top After Certain Point</h4><p>This is the code to scroll the bottom sheet to the top when the user dragged past half of desired max height.</p><pre>@override<br>void initState() {<br>  super.initState();<br>  this._animationController = AnimationController(vsync: this, duration: const Duration(milliseconds: 300))<br>    ..addListener(() {<br>      this._bodyHeight = this._animation!.value;<br>      this.setState(() {});<br>    });<br>}<br><br>Future&lt;void&gt; _onDragEnd(DragEndDetails d) async {<br>  // scroll the bottom sheet to the top when the user dragged past a certain point.<br>  if (this._bodyHeight &gt;= this.widget.maxHeight * 1/2) {<br>    this._animation = Tween&lt;double&gt;(begin: this._bodyHeight, end: this.widget.maxHeight).animate(this._animationController!);<br>    this._animationController?.reset();<br>    this._animationController!.forward();<br>  }<br>}</pre><h4>Continue Scroll Based On User’s Velocity</h4><p>DragEndDetail has primaryVelocity property: if it is negative, the user swiped up and if it is positive, the user swiped down. So <strong>according to the velocity, I decided how much to scroll the bottom sheet and how fast the animation would be.</strong> As someone who knows nothing about velocity and any math or science related to it, I fiddled around to find numbers that I liked.</p><p>For fast speed (&lt; -2000.0 or &gt; 2000.0), the bottom sheet scrolls all the way up for down respectively for 300 milliseconds. For moderate speed (anywhere in between), the bottom sheet animates to certain position (again…very non-precise but the best I could do) for 100 milliseconds.</p><pre>Future&lt;void&gt; _onDragEnd(DragEndDetails d) async {<br>  if (d.primaryVelocity == null) return;<br>  <br>  double _animateTo = this._bodyHeight - d.primaryVelocity! / 20.0; // to be used for moderate swipe speed<br>  Duration _duration = const Duration(milliseconds: 100); // 100 for moderate swipe, 300 for fast swipe<br><br>  if (d.primaryVelocity!.isNegative) {<br>    if (d.primaryVelocity! &lt; - 2000.0) {<br>      _duration = const Duration(milliseconds: 300);<br>      _animateTo = this.widget.maxHeight; /// scroll up all the way up<br>    } else {<br>      if (_animateTo &gt; this.widget.maxHeight) _animateTo = this.widget.maxHeight; /// makes sure does not go past max height<br>    }<br>  } else {<br>    if (d.primaryVelocity! &gt; 2000.0) {<br>      _duration = const Duration(milliseconds: 300);<br>      _animateTo = 0.0; /// scroll all the way down<br>    } else {<br>      if (_animateTo &lt; 100.0) _animateTo = 0.0; /// make sure does not go below 0.0<br>    }<br>  }<br>  <br>  this._animationController?.duration = _duration;<br>  this._animation = Tween&lt;double&gt;(begin: this._bodyHeight, end: _animateTo).animate(this._animationController!);<br>  this._animationController?.reset();<br>  await this._animationController?.forward();<br><br>}</pre><h4>Combining the Two Methods</h4><p>I simplified the scroll based on velocity method and combined the two.</p><pre><br>Future&lt;void&gt; _onDragEndPosition(DragEndDetails d) async {<br>  this._animationController!.duration = const Duration(milliseconds: 300);<br>  if (this._bodyHeight &gt;= this.widget.maxHeight * 1/3) {<br>    this._animation = Tween&lt;double&gt;(begin: this._bodyHeight, end: this.widget.maxHeight).animate(this._animationController!);<br>    this._animationController?.reset();<br>    await this._animationController?.forward();<br>  }<br>  if (this._bodyHeight &lt; this.widget.maxHeight * 1/3) {<br>    this._animation = Tween&lt;double&gt;(begin: this._bodyHeight, end: 0.0).animate(this._animationController!);<br>    this._animationController?.reset();<br>    await this._animationController?.forward();<br>  }<br>}<br><br>Future&lt;void&gt; _onDragEndVelocitySimple(DragEndDetails d) async {<br>  double _end;<br>  if (d.primaryVelocity! &lt; 0.0) {<br>    _end = this.widget.maxHeight;<br>  } else {<br>    _end = 0.0;<br>  }<br>  this._animation = Tween&lt;double&gt;(begin: this._bodyHeight, end: _end).animate(this._animationController!);<br>  this._animationController?.reset();<br>  await this._animationController?.forward();<br>}<br><br>Future&lt;void&gt; _onDragEnd(DragEndDetails d) async {<br>  if (d.primaryVelocity == null) return;<br>  if (d.primaryVelocity == 0) await this._onDragEndPosition(d);<br>  if (d.primaryVelocity != 0) await this._onDragEndVelocitySimple(d);<br>}</pre><h3>Body as List</h3><h4>Main.dart</h4><pre>Widget _listItem(String text) =&gt; Container(<br>  width: double.infinity,<br>  height: 40.0,<br>  alignment: Alignment.center,<br>  child: Text(text),<br>);<br>...<br>CustomBottomSheet(children: List.generate(20, (int index) =&gt; this._listItem(&quot;list item $index&quot;))</pre><h4>Bottom Sheet Body</h4><p>With the body as a list, the physics will be <strong>NeverScrollableScrollPhysics</strong> and it will only be controlled with a scroll controller.</p><pre>...<br>height: this.widget.headerHeight + this._bodyHeight + (this.widget.hasBottomViewPadding ? MediaQuery.of(context).viewPadding.bottom : 0.0),<br>child: Column(<br>  mainAxisSize: MainAxisSize.min,<br>  children: &lt;Widget&gt;[<br>    Container(<br>      height: this.widget.headerHeight,<br>      alignment: Alignment.center,<br>      child: this.widget.header,<br>    ),<br>    Expanded(<br>      child: this.widget.body ?? ListView.builder(<br>        physics: const NeverScrollableScrollPhysics(),<br>        controller: this._scrollController,<br>        padding: const EdgeInsets.only(bottom: 45.0),<br>        itemCount: this.widget.children!.length,<br>        itemBuilder: (_, int index) =&gt; this.widget.children![index]<br>      ),<br>    )<br>  ],<br>),</pre><h4>_isAtTop</h4><p>The boolean _<strong>isAtTop</strong> becomes very important as it will decide whether the bottom sheet container is dragged or the inner list. There are a few areas where this value has to change.</p><p><strong>(1) Animation Controller Listener<br></strong>When the bottom sheet container is animated, _isAtTop needs to change accordingly. It needs to be when the animation <strong>status is completed</strong>!!</p><pre>@override<br>  void initState() {<br>  super.initState();<br>  this._animationController = AnimationController(vsync: this, duration: const Duration(milliseconds: 300), )<br>    ..addListener(() {<br>      this._bodyHeight = this._animation!.value;<br>      this.setState(() {});<br>    })..addStatusListener((AnimationStatus status) {<br>      if (status == AnimationStatus.completed &amp;&amp; this._bodyHeight &gt;= this.widget.maxHeight) this._isAtTop = true;<br>    });<br>  }</pre><p><strong>(2) onDragEnd<br></strong>There are instances where the bottom sheet container is not animated but controlled by drag only, and in that case,<strong> </strong>_isAtTop needs to change accordingly.</p><p><strong>(3) onDragUpdate</strong><br>This will be covered below.</p><h4>Following Drag Gesture</h4><p>Mainly, in onDragUpdate, we need to know whether the bottom sheet is moving or the inner list, which can be determined with “<strong>scrollController.position.extentBefore == 0.0”</strong>. If it is 0.0, the inner list has not been scrolled yet.</p><p>Then, if _isAtTop is true and primaryDelta is negative, we know the bottom sheet has been fully opened and the user is swiping upwards. Therefore, the inner list needs to be moved, which I did using <strong>this._scrollController.jumpTo(_scrollTo)</strong>.</p><p>If that is not the case, the method that follows drag gesture as described above is used, but!! make sure that _isAtTop is set to false here.</p><pre>void _followDragWithBodyAsList(DragUpdateDetails d) {<br>  final double _movedAmount = this._initPosition - d.globalPosition.dy; /// negative = drag down, positive = drag up<br>  final double _scrollTo = this._scrollController.offset + _movedAmount; /// needed for scrolling the inner list<br><br>  /// the list inside has not been touched yet<br>  if (this._scrollController.position.extentBefore == 0.0) {<br>    if (this._isAtTop &amp;&amp; d.primaryDelta!.isNegative) { /// bottom sheet has been scrolled to the top and the user is scrolling more upwards<br>      this._scrollController.jumpTo(_scrollTo);<br>    } else {<br>      /// follow drag gesture<br>      double _newHeight = this._bodyHeight + _movedAmount;<br>      if (_newHeight &lt; 0.0) _newHeight = 0.0; /// makes sure the bodyHeight does not fall under 0.0<br>      if (_newHeight &gt; this.widget.maxHeight) _newHeight = this.widget.maxHeight; /// makes sure the bodyHeight does not go above max height<br>      this._bodyHeight = _newHeight;<br>      this.setState(() {});<br>      this._isAtTop = false;<br>    }<br><br>  } else {<br>    /// user is scrolling the inner list<br>    if (_scrollTo &gt; this._scrollController.position.maxScrollExtent) return;<br>    this._scrollController.jumpTo(_scrollTo);<br>  }<br>  this._initPosition = d.globalPosition.dy;<br>}</pre><p>If the scroll controller’s position.extentBefore property is not 0.0, once again use the jumpTo method. Here, <strong>_scrollTo </strong>is different from _movedTo because _scrollTo considers the current offset of the inner list.</p><h4>Continue Scroll (Inner List and Bottom Sheet Container)</h4><p>Last but not least…automating scroll. I am actually very tired after writing this post…so I will come back to writing the explanation but here is the code.</p><pre>Future&lt;void&gt; _onDragEndWithBodyAsList(DragEndDetails d) async {<br>  if (d.primaryVelocity == null) return;<br><br>  if (!this._isAtTop) { /// scrolls the bottom sheet container<br>    if (d.primaryVelocity == 0) await this._onDragEndPosition(d);<br>    if (d.primaryVelocity != 0) await this._onDragEndVelocitySimple(d);<br>  } else {<br>    /// scrolls the inner list<br>    double _animateTo = this._scrollController.offset - d.primaryVelocity! / 5;<br><br>    if (d.primaryVelocity! &gt; 0.0 &amp;&amp; _animateTo &lt; 0.0) _animateTo = 0.0; /// does not overscroll upwards<br>    if (d.primaryVelocity! &lt; 0.0 &amp;&amp; _animateTo &gt; this._scrollController.position.maxScrollExtent) {<br>      _animateTo = this._scrollController.position.maxScrollExtent; /// does not overscroll downwards<br>    }<br><br>    int _duration = 1600; /// scroll duration for inner parts<br>    /// change scroll duration depending on offset <br>    if (_animateTo == 0.0 &amp;&amp; this._scrollController.offset - _animateTo &lt; _duration) _duration = 600;<br>    if (_animateTo == this._scrollController.offset &amp;&amp; this._scrollController.offset - _animateTo &lt; _duration) _duration = 300;<br>    await this._scrollController.animateTo(_animateTo, duration: Duration(milliseconds: _duration), curve: Curves.easeOutCubic);<br>  }<br><br>  if (this._bodyHeight &gt;= this.widget.maxHeight) {<br>    this._isAtTop = true;<br>  } else {<br>    this._isAtTop = false;<br>  }<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=da64694b706e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Nuxt.js — How to handle CORS error]]></title>
            <link>https://mookypoo.medium.com/nuxt-js-how-to-handle-cors-error-a4c5022611d0?source=rss-a32d589adcc9------2</link>
            <guid isPermaLink="false">https://medium.com/p/a4c5022611d0</guid>
            <category><![CDATA[nuxtjs]]></category>
            <category><![CDATA[cors]]></category>
            <category><![CDATA[ipv4]]></category>
            <category><![CDATA[localhost]]></category>
            <category><![CDATA[ipv6]]></category>
            <dc:creator><![CDATA[Soo Kim]]></dc:creator>
            <pubDate>Tue, 18 Apr 2023 07:18:29 GMT</pubDate>
            <atom:updated>2023-04-18T07:18:29.769Z</atom:updated>
            <content:encoded><![CDATA[<h3>Nuxt.js — How to handle CORS error</h3><h4>answer: routeRules</h4><p>Yesterday, I started playing around with Nuxt.js but for several hours had a difficult time connecting my Nuxt.js app on port 3000 to my server on local host (port 9300). After almost a whole day of futile efforts, I finally found a solution and maybe someone might find it helpful :) I’ll post the solution first for anyone who wants a quick answer, and then I’ll go through steps I took to reach the answer.</p><p>Here’s the final code:</p><pre>// notice that its 127.0.0.1 and not localhost<br>// port number is your nuxt.js <br><br>const _res = await axios.get(&quot;http://127.0.0.1:3000/web/v1/stores?page=1&amp;pageSize=16&quot;);<br><br>// nuxt.config.ts<br>export default defineNuxtConfig((){<br>  routeRules: {<br>      &#39;/web/v1/**&#39;: {<br>          proxy: { to: &quot;http://127.0.0.1:9300/web/v1/**&quot;, },<br>      }<br>    }<br>})</pre><h3>Steps Taken</h3><h4>Connect Directly to localhost:9300</h4><p>If you try to just fetch directly from the server url like below, CORS policy prevents the request from going through.</p><pre>const _res = await axios.get(&quot;http://localhost:9300/web/v1/stores?page=1&amp;pageSize=16&quot;, {<br>    headers: { &quot;Access-Control-Allow-Origin&quot;: &quot;*&quot;, &#39;Access-Control-Allow-Headers&#39;: &#39;*&#39;, },<br>});</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ueu4DuGtfCgynxDJuhuFPg.png" /><figcaption>CORS error</figcaption></figure><h4>Set Nitro devProxy</h4><p>Then, I tried to set up a devProxy.</p><pre>// nuxt.config.ts<br>export default defineNuxtConfig((){<br>  nitro: {<br>    devProxy: {<br>      &quot;/web&quot;: {<br>          target: &quot;http://localhost:9300&quot;,<br>          Headers: { &quot;Access-Control-Allow-Origin&quot;: &quot;*&quot;, &#39;Access-Control-Allow-Headers&#39;: &#39;*&#39;, },<br>          prependPath: true,<br>          changeOrigin: true,<br>      },<br>    }<br>  }<br>})</pre><p>This time, a TCP connection error occurred.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xvx14cwocMvHimSZ7_4x4A.png" /></figure><p>According to this <a href="https://github.com/nodejs/node/issues/40702">github thread</a>, Node 17 had a breaking change with how DNS.lookup works: instead of ignoring your OS configuration and re-sorting IP address lookups, it returns them as-is. In my case, my server listens to the IPv4 address (127.0.0.1) but node 17 was returning IPv6 of localhost (::1).</p><p>So, I switched localhost to 127.0.0.1.</p><p>But…although the TCP connection error disappeared, now the erro was that the page couldn’t be found (404).</p><h4>Set routeRules</h4><p>Thanks to this <a href="https://github.com/nuxt/nuxt/issues/19325">github thread</a>, I found the solution: set routeRules in nuxt.config.ts.</p><pre>// nuxt.config.ts<br>export default defineNuxtConfig((){<br>  routeRules: {<br>      &#39;/web/v1/**&#39;: {<br>          proxy: { to: &quot;http://localhost:9300/web/v1/**&quot;, },<br>      }<br>    }<br>})</pre><p>I’m still not sure I completely understand the reason for the errors…but I’m just glad I was able to find the solution before I went crazy.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a4c5022611d0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter/Dart: Recursive & Callback Functions]]></title>
            <link>https://mookypoo.medium.com/flutter-dart-recursive-callback-functions-a1e90ca589cb?source=rss-a32d589adcc9------2</link>
            <guid isPermaLink="false">https://medium.com/p/a1e90ca589cb</guid>
            <category><![CDATA[callback-function]]></category>
            <category><![CDATA[recursive-function]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Soo Kim]]></dc:creator>
            <pubDate>Sat, 08 Apr 2023 02:04:48 GMT</pubDate>
            <atom:updated>2023-04-08T02:04:48.978Z</atom:updated>
            <content:encoded><![CDATA[<h4>and how to show dialogs regardless of the current page!</h4><p>This post consists of very concise example of recursive and callback functions so do keep in mind that the code is simplified for this post.</p><p><a href="https://github.com/mookypoo/recursive_callback_functions">Full Code</a> for anyone that wants to skip the explanation.</p><h3>Recursive Function Example</h3><p>I had never had the opportunity to use a recursive function until recently, so I wanted to share how and when I used it. The code that executes the below scenario is the recursive function.</p><p>Scenario: user goes to a new page to write a review → submits a review → page is popped → SnackBar appears with an option to modify → if clicked on modify, review page with data is shown.</p><p>The scenario gets repeated when the user clicks “modify”, hence becoming a recursive function.</p><h4><strong>Recursive Function</strong></h4><pre>class Home extends StatelessWidget {<br>  const Home({Key? key}) : super(key: key);<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      body: Center(<br>        child: ColoredTextButton(<br>          text: &quot;Write a Review&quot;,<br>          onPressed: () async {<br>  <br>            Future&lt;void&gt; _recursive({String review = &quot;&quot;}) async {<br>              final String _review = await Navigator.of(context).push&lt;String&gt;(MaterialPageRoute(<br>                  builder: (_) =&gt; WriteReviewPage(review: review)<br>              )) ?? &quot;&quot;;<br><br>              if (_review.isEmpty) return;<br>              ScaffoldMessenger.of(context).showSnackBar(<br>                SnackBar(content: const Text(&quot;Your review has been submitted.&quot;,<br>                  style: TextStyle(fontSize: 16.0 ),), duration: const Duration(seconds: 5),<br>                  action: SnackBarAction(<br>                    label: &quot;Modify&quot;,<br>                    onPressed: () async =&gt; await _recursive(review: _review),<br>                  ),<br>                ),<br>              );<br>            }<br><br>            await _recursive();<br>          },<br>        ),<br>      ),<br>    );<br>  }<br>}</pre><h4>Review Page</h4><pre>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:recursive_callback/color_button.dart&#39;;<br><br>class WriteReviewPage extends StatefulWidget {<br>  const WriteReviewPage({Key? key, required this.review}) : super(key: key);<br>  final String review;<br><br>  @override<br>  State&lt;WriteReviewPage&gt; createState() =&gt; _WriteReviewPageState();<br>}<br><br>class _WriteReviewPageState extends State&lt;WriteReviewPage&gt; {<br>  final TextEditingController _controller = TextEditingController();<br><br>  @override<br>  void initState() {<br>    super.initState();<br>    if (this.widget.review.isNotEmpty) this._controller.text = this.widget.review;<br>  }<br><br>  @override<br>  void dispose() {<br>    this._controller.dispose();<br>    super.dispose();<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return GestureDetector(<br>      onTap: FocusManager.instance.primaryFocus?.unfocus,<br>      child: Scaffold(<br>        appBar: AppBar(title: const Text(&quot;Write A Review!&quot;),),<br>        body: SizedBox(<br>          width: MediaQuery.of(context).size.width,<br>          child: Column(<br>            crossAxisAlignment: CrossAxisAlignment.center,<br>            mainAxisAlignment: MainAxisAlignment.center,<br>            children: &lt;Widget&gt;[<br>              Container(<br>                width: 300.0,<br>                height: 50.0,<br>                margin: const EdgeInsets.only(bottom: 20.0),<br>                child: TextField(<br>                  controller: this._controller,<br>                  decoration: const InputDecoration(<br>                    contentPadding: EdgeInsets.symmetric(vertical: 5.0, horizontal: 10.0),<br>                    constraints: BoxConstraints(),<br>                    border: OutlineInputBorder()<br>                  ),<br>                ),<br>              ),<br><br>              ColoredTextButton(<br>                  text: &quot;Submit&quot;,<br>                  onPressed: () async {<br>                    /// send data to server<br>                    Navigator.of(context).pop(this._controller.text.trim());<br>                  }<br>              ),<br>            ],<br>          ),<br>        ),<br>      ),<br>    );<br>  }<br>}</pre><h3>Callback Functions</h3><p>When I first started coding, it took me a few attempts to get used to callback functions. Basically, callback functions are functions passed as an argument into another function to (1) control the timing/order of functions and (2) use a value from another function.</p><p>One place I use callback functions the most is after receiving response from the server, passing the error or success messages as an argument. In this example, if it’s an error message, I show a pop up dialog, and if its a success message, I show a Snackbar.</p><h4><strong>API Service</strong></h4><pre>import &#39;dart:async&#39; show FutureOr;<br>import &#39;dart:convert&#39; show json, utf8;<br>import &#39;dart:io&#39; show SocketException;<br>import &#39;package:http/http.dart&#39; as http;<br><br>typedef Json = Map&lt;String, dynamic&gt;;<br><br>class APIService {<br>  final String _baseUrl = &quot;&quot;;<br><br>  String _path(String path){<br>    String _path = path.trim();<br>    if (!_path.startsWith(&quot;/&quot;)) _path = &quot;/&quot; + _path;<br>    return _path;<br>  }<br><br>  Map&lt;String, String&gt; _headers({required String? accessToken}) =&gt; {&quot;content-type&quot;:&quot;application/json&quot;, &quot;authorization&quot;: &quot;Bearer $accessToken&quot;};<br><br>  Future&lt;void&gt; postToServer({<br>    required String path,<br>    Map&lt;String, String&gt;? headers,<br>    required String? accessToken,<br>    required dynamic body,<br>    FutureOr&lt;void&gt; Function(String)? errorCb,<br>    FutureOr&lt;void&gt; Function(String)? successCb,<br>  }) async {<br>    try {<br>      final http.Response _res = await http.post(<br>        Uri.parse(this._baseUrl + this._path(path)),<br>        headers: {...headers ?? {}, ...this._headers(accessToken: accessToken)},<br>        body: json.encode(body),<br>      ).timeout(const Duration(seconds: 13), onTimeout: () =&gt; http.Response(&quot;null&quot;, 404));<br><br>      final Json _decodedBody = json.decode(utf8.decode(_res.bodyBytes)) as Json;<br>      if (_decodedBody.containsKey(&quot;error&quot;) &amp;&amp; errorCb != null) await errorCb(_decodedBody[&quot;error&quot;]);<br>      if (_decodedBody.containsKey(&quot;success&quot;) &amp;&amp; successCb != null) await successCb(_decodedBody[&quot;success&quot;]);<br>    } catch (e) {<br>      print(e);<br>      if (e.runtimeType == SocketException &amp;&amp; errorCb != null) await errorCb(&quot;Cannot connect to the server.&quot;);<br>    }<br>  }</pre><p>This way, the user can continue using the app without having to wait for the future to complete. When the future does complete, the user can be notified.</p><h4><strong>Review Page with Callback Function</strong></h4><p>Do note, the page will most likely be popped before the error or success callback function is executed. This means that the “context” your usually pass on to dialog or ScaffoldMessenger — which belongs to the current widget (in this case, Write Review Page State) — will not be available.</p><p>In order for you to show the dialog wherever the user is, you’d want to use the context of the app itself, which you can do by assigning a navigator key to the MaterialApp. Then, you can use this key to find the context of the app.</p><pre>final GlobalKey&lt;NavigatorState&gt; navigatorKey = GlobalKey&lt;NavigatorState&gt;();<br><br>class Main extends StatelessWidget {<br>  const Main({Key? key}) : super(key: key);<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return MaterialApp(<br>      home: Home(),<br>      navigatorKey: navigatorKey,<br>    );<br>  }<br>}</pre><pre>ColoredTextButton(<br>    text: &quot;Submit&quot;,<br>    onPressed: () async {<br>      final BuildContext? _appContext = navigatorKey.currentContext;<br>      if (_appContext == null) return;<br><br>      await _service.postToServer(<br>          path: &quot;/review&quot;,<br>          accessToken: &quot;&quot;,<br>          body: {&quot;review&quot;: this._controller.text.trim()},<br>          errorCb: (String errorMsg) async {<br>            await showDialog(<br>              /// if you use context of this WriteReviewPage, because the page already got disposed, an error occurs<br>                context: _appContext,<br>                builder: (_) =&gt; Dialog(child: Text(errorMsg))<br>            );<br>          },<br>          successCb: (String successMsg) async {<br>            ScaffoldMessenger.of(_appContext).showSnackBar(<br>              SnackBar(content: Text(successMsg,<br>                style: const TextStyle(fontSize: 16.0 ),), duration: const Duration(seconds: 1),<br>              ),<br>            );<br>          }<br>      );<br>      Navigator.of(context).pop();<br>    }<br>)</pre><p>Happy Coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a1e90ca589cb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter: Custom Dropdown Widget]]></title>
            <link>https://mookypoo.medium.com/flutter-custom-dropdown-widget-a96c772095be?source=rss-a32d589adcc9------2</link>
            <guid isPermaLink="false">https://medium.com/p/a96c772095be</guid>
            <category><![CDATA[widget]]></category>
            <category><![CDATA[dropdown]]></category>
            <category><![CDATA[rendering]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Soo Kim]]></dc:creator>
            <pubDate>Tue, 14 Feb 2023 23:28:28 GMT</pubDate>
            <atom:updated>2023-02-14T23:28:28.995Z</atom:updated>
            <content:encoded><![CDATA[<h4>Using RenderBox and PageRouteBuilder</h4><p>I’m not a big fan of Flutter’s built in Dropdown Widget’s UI and the lack of UI control, so I decided to make one myself. The widget works fine, but I couldn’t figure out how to properly animate it (gradually opening and closing the widget). Despite the fact that I feel like the widget is incomplete due to the lack of animation, I’m sharing this post today to share how to use <strong>RenderBox.</strong></p><p>I’ll be going over (1) how to find where your widget is on the screen using RenderBox, (2) the dropdown options, and (3) rendering the dropdown options with PageRouteBuilder.</p><h4>Dropdown Widget UI</h4><p>Here’s the UI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/666/1*Nxc5nm_jorFLwvNm-LFWAQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/666/1*wDhTfxvDFZ8sh0QZ9jWN3g.jpeg" /></figure><p><a href="https://youtube.com/shorts/eBhU4eECqMU?feature=share">dropdown widget</a></p><pre>class Main extends StatelessWidget {<br>  const Main({Key? key}) : super(key: key);<br><br>  @override<br>  Widget build(BuildContext context) {<br>    final DropdownProvider _provider = Provider.of&lt;DropdownProvider&gt;(context);<br>    return Scaffold(<br>      body: Center(<br>        child: Column(<br>          mainAxisAlignment: MainAxisAlignment.center,<br>          children: [<br>            DropdownWidget(<br>              initText: &quot;Select a Drink&quot;,<br>              options: _provider.drinks,<br>              onTap: (String text) {<br>                print(text);<br>                _provider.changeDrink(text);<br>              }<br>            ),<br>          ],<br>        ),<br>      ),<br>    );<br>  }<br>}</pre><h4>How to Find Where Your Widget Is on the Screen</h4><p>In order to do so, we need to understand that <strong>BuildContext</strong> is a<br>“<strong><em>handle to the location of a widget in the widget tree.</em></strong><em>” </em>So, each context refers to a widget, which we. can use to find offset of a widget. With the context of the given widget, we can use <strong>findRenderObject( ) to determine it’s offset. </strong>Then, use <strong>localToGlobal( )</strong> to find the offset of the top-left corner of the widget relative to the whole screen.</p><pre>final RenderBox _box = context.findRenderObject() as RenderBox;<br>final Offset _offset = _box.localToGlobal(Offset.zero);</pre><p>Note that findRenderObject( ) can only be <strong>called after the build process has been completed</strong>, and should be called from interaction handlers (like gesture detector) or paint call.</p><p>However, <strong>Rect </strong>is a much more convenient class to use since you can get offset of all corners of the widget and its size. Rect can be created with offset and size using &amp; operator. You would use this rect to decide where to render the dropdown options.</p><pre>final RenderBox _box = context.findRenderObject() as RenderBox;<br>final Rect _rect = _box.localToGlobal(Offset.zero) &amp; _box.size;<br>print(_rect.topLeft); // Offset(62.5, 386.0)<br>print(_rect.topRight); // Offset(312.5, 386.0)<br>print(_rect.bottom); // 426.0. (top y-axis + size.width) (386 + 40)<br>print(_rect.size); // Size(250.0, 40.0)</pre><h4>Dropdown Options</h4><p>Initially, use _rect to find the bottom and left values, and stack the dropdown option list below the dropdown widget. If an option is already selected, find it’s rect using the index and height of the individual options. The selected option will be shown with blue highlight.</p><pre>double _top = _rect.bottom;<br>if (this._selectedText != null) {<br>  final int _index = this.widget.options.indexOf(this._selectedText!);<br>  _top -= (_index + 1) * this.widget.height;<br>}<br><br>Widget _dropdowns = Stack(<br>  alignment: Alignment.topLeft,<br>  children: [<br>    Positioned(<br>      top: _top,<br>      height: _rect.height * this.widget.options.length + 1.0,<br>      left: _rect.left,<br>      child: Container(<br>        decoration: BoxDecoration(<br>          color: Colors.white,<br>          borderRadius: BorderRadius.circular(this.widget.borderRadius),<br>          border: Border.all(strokeAlign: StrokeAlign.inside),<br>          boxShadow: [<br>            BoxShadow(color: Colors.grey.withOpacity(0.5), blurRadius: 2.0, spreadRadius: 1.0, offset: Offset(0.0, 2.0)),<br>          ]<br>        ),<br>        width: this.widget.width,<br>        child: Column(<br>          mainAxisSize: MainAxisSize.min,<br>          children: this.widget.options.map&lt;Widget&gt;((String text) {<br>            final int _index = this.widget.options.indexOf(text);<br>            double _height = _rect.height;<br>            // the below portion was to account for the border widths <br>            // the dropdown option text was slightly off from the dropdown widget text <br>            if (_index == 0 || _index == this.widget.options.length) {<br>              _height -= 1.0;<br>            }<br>            return Material(<br>              // this color portion is for the dropdown option border corners<br>              // without it, the corners are not shown properly <br>              color: this._selectedText == text &amp;&amp; _index != this.widget.options.length -1 &amp;&amp; _index != 0<br>                ? Colors.white<br>                : Colors.transparent,<br>              child: InkWell(<br>                onTap: () {<br>                  Navigator.of(ctx).pop(text);<br>                },<br>                child: this._dropDownWidget(text, _height,),<br>              ),<br>            );<br>          }).toList(),<br>        ),<br>      ),<br>    ),<br>  ]);</pre><h4>How to Show the Dropdown Options</h4><p>So this is the tricky part. If you use just stack within the widget, the options either won’t be shown in the right place, or not shown at all (depending on whether you use Positioned or not).</p><p>We have all used things like showDialog or showBottomSheet before. What these do is basically push a Material widget (or Cupertino widget in the case of Cupertino actions) above the current screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*kknJTOKL7dhL9Nhch29_PA.png" /><figcaption>showDialog</figcaption></figure><p>Instead, we use <strong>PageRouteBuilder. </strong>Navigator.of(context).push takes the abstract class <strong>Route&lt;T&gt;</strong> as its argument, and PageRouteBuilder extends Route. It allows us to tweak the <strong>opacity</strong> (if true, the page from which the new widget was pushed will not be shown) and <strong>barrier</strong> (barrierDismissible, barrierColor).</p><p>The code below shows the dropdown options.</p><pre>onTap: () async {<br>    final RenderBox _box = context.findRenderObject() as RenderBox;<br>    final Rect _rect = _box.localToGlobal(Offset.zero) &amp; _box.size;<br><br>    // push the drop down options and return selected <br>    final String _text = await Navigator.of(context).push&lt;String&gt;(<br>      PageRouteBuilder(<br>        transitionsBuilder: (_, Animation&lt;double&gt; a1, Animation&lt;double&gt; a2, widget) {<br>          final CurvedAnimation _curvedAnimation = CurvedAnimation(parent: a1, curve: Curves.fastLinearToSlowEaseIn);<br>          return FadeTransition(<br>            opacity: Tween&lt;double&gt;(begin: 0.0, end: 1.0).animate(_curvedAnimation),<br>            child: widget,<br>          );<br>        },<br>        transitionDuration: const Duration(seconds: 1),<br>        reverseTransitionDuration: const Duration(milliseconds: 300),<br>        opaque: false,<br>        barrierDismissible: true,<br>        pageBuilder: (BuildContext ctx, Animation&lt;double&gt; a1, Animation&lt;double&gt; a2) {<br>          // the dropdown options code above <br>          return _dropdowns;<br>        }),<br>    ) ?? this._selectedText ?? this.widget.initText;<br>    this.setState(() {<br>      this._selectedText = _text;<br>    });<br>  },</pre><p>Happy Coding! Here’s the <a href="https://github.com/mookypoo/custom_dropdown_widget">full code.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a96c772095be" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Google Map Custom Icon — Part I.]]></title>
            <link>https://mookypoo.medium.com/google-map-custom-icon-part-i-f8cd845cab98?source=rss-a32d589adcc9------2</link>
            <guid isPermaLink="false">https://medium.com/p/f8cd845cab98</guid>
            <category><![CDATA[bitmapdescriptor]]></category>
            <category><![CDATA[google-map-marker]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Soo Kim]]></dc:creator>
            <pubDate>Tue, 24 Jan 2023 07:20:11 GMT</pubDate>
            <atom:updated>2023-01-24T07:23:18.860Z</atom:updated>
            <content:encoded><![CDATA[<h3>Google Map Custom Icon — Part I.</h3><h4>Flutter: How to Use Your Own Image as Google Map Icon</h4><p>This is the first article in a two-part series on Google Map marker icon. In this article, I’ll be going over how to use your own image as a marker with a very simple app that shows listed houses. Part II will go over how to use nine patch image to create dynamic markers (or just image in general), which is a more advanced option.</p><p>Keep in mind that this is a <strong>very simplified version</strong> of what I have done professionally, and that you can do so much more than what is written here. For example, I’ve completely omitted making the selected marker smaller when you tap another house.</p><h4>Table of Contents</h4><ol><li>Class — Location Class, House Class, CustomMarker Class</li><li>Converting Image Asset to BitmapDescriptor</li><li>Provider &amp; View</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Utf3uhEre8N0v-9VRKrZ_w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hig2kVVpwvh2SAhgDI38TQ.png" /><figcaption>icon by HAJICON: <a href="https://www.flaticon.com/free-icons/maps-and-location">https://www.flaticon.com/free-icons/maps-and-location</a></figcaption></figure><h3>Custom Classes</h3><p>For this simple example, I created three classes: Location, House, and Custom Marker. The House class doesn’t require additional explanation.</p><pre>class House {<br>  final String houseUid;<br>  final String shortDescription;<br>  final LocationClass latLng;<br><br>  const House({required this.houseUid, required this.shortDescription, required this.latLng});<br>}</pre><h4>LocationClass</h4><p>The LocationClass <strong>extends Google Map’s LatLng</strong>, which I did so that it would be more convenient, as it could be used in other parts of the app.</p><pre>import &#39;package:google_maps_flutter/google_maps_flutter.dart&#39;;<br><br>class LocationClass extends LatLng {<br>  @override<br>  final double latitude;<br><br>  @override<br>  final double longitude;<br><br>  const LocationClass({required this.latitude, required this.longitude}) <br>    : super(latitude, longitude);<br><br>  factory LocationClass.fromJson({required double latitude, required double longitude}) =&gt;<br>      LocationClass(longitude: longitude, latitude: latitude);<br>  <br>  factory LocationClass.fromLatLng(LatLng ln)=&gt; LocationClass(<br>      latitude: ln.latitude,<br>      longitude: ln.longitude<br>  );<br>}</pre><h4>CustomMarker Class</h4><p>The CustomMarker class <strong>extends Google Map’s Marker</strong> class because I’d like to have my own onTap function and the info of the house stored in the marker. The anchor, which allows you to set the anchor point of the icon, doesn’t matter in this example.</p><pre>import &#39;package:google_maps_flutter/google_maps_flutter.dart&#39;;<br><br>class CustomMarker extends Marker {<br>  final House house;<br>  final FutureOr&lt;void&gt; Function(House house) onTapHouse;<br><br>  CustomMarker({required this.house, required super.icon, bool hasBubble = false, required this.onTapHouse})<br>    : super(<br>        markerId: MarkerId(house.houseUid),<br>        position: house.latLng,<br>        consumeTapEvents: true, /// do avoid camera moving <br>        anchor: !hasBubble ? const Offset(0.5, 0.5) : const Offset(0.1, 0.8),<br>        onTap: () async =&gt; await onTapHouse(house),<br>      );<br>}</pre><h3>Image Asset to BitmapDescriptor</h3><p>Google’s Marker takes a BitmapDescriptor as its icon, and you can create it using a <strong>array of bytes (Uint8List in Flutter) in png format</strong>. so you can take the image Uint8List and convert it to BitmapDescriptor. A Uint8List is a fixed-length list of 8-bit (8 binary digits) unsigned integers. You can create a Uint8List from the byte buffer.</p><pre>import &#39;dart:ui&#39; as ui;<br>import &#39;package:flutter/services.dart&#39;;<br><br>Future&lt;Uint8List&gt; getBytesFromAsset({required String path, required int width}) async {<br>  final ByteData _data = await rootBundle.load(path);<br>  final ui.Codec _codec = await ui.instantiateImageCodec(_data.buffer.asUint8List(), targetWidth: width);<br>  final ui.FrameInfo _fi = await _codec.getNextFrame();<br>  final Uint8List _bytes = (await _fi.image.toByteData(format: ui.ImageByteFormat.png))!.buffer.asUint8List();<br>  return _bytes;<br>}</pre><p>(1) Get the <strong>ByteData</strong> of the asset. This will get the byte data of the image as is. So if you convert this immediately to Uint8List, the size of the icon will be the size of the image itself. In order for us to tweak the size of the icon, we need to create a new ByteData with the appropriate size.</p><p>(2) Use <strong>instantiateImageCodec </strong>to get the image codec and set the target width/height.</p><p>(3) Use <strong>getNextFrame to </strong>get information about the image.</p><p>(4) Convert the FrameInfo to image → <strong>get Bytedata in png format</strong> → convert it to Uint8List.</p><p><strong>Note:</strong> You can choose to return BitmapDescriptor itself by creating it in getBytesFromAsset. I didn’t because I will be using that method in other places as well.</p><h3>Provider &amp; View</h3><p>Here is my map provider. When you tap on the marker, the onTapHouse() method removes the tapped one and adds a bigger marker (_selectedMarker). I chose to save the BitmapDescriptors so that I don’t have to create a new one every time the markers are tapped.</p><pre>class MapProvider with ChangeNotifier {<br>  final MapService _mapService = MapService();<br><br>  final List&lt;House&gt; houses = [...SampleData.houses];<br><br>  House? _selectedHouse;<br>  House? get selectedHouse =&gt; this._selectedHouse;<br>  set selectedHouse(House? h) =&gt; throw &quot;error&quot;;<br><br>  List&lt;Marker&gt; _markers = [];<br>  Set&lt;Marker&gt; get markers =&gt; {...this._markers};<br>  set markers(Set&lt;Marker&gt; s) =&gt; throw &quot;error&quot;;<br><br><br>  BitmapDescriptor? _unselectedIconMarker;<br>  BitmapDescriptor? _selectedIconMarker;<br><br>  Future&lt;void&gt; init() async {<br>    await this._setBitmapDescriptor();<br>    this._setIconMarkers();<br>  }<br><br>  Future&lt;void&gt; _setBitmapDescriptor() async {<br>    final Uint8List _unselected = await this._mapService.getBytesFromAsset(width: 100, path: &quot;assets/marker_icon.png&quot;);<br>    this._unselectedIconMarker = BitmapDescriptor.fromBytes(_unselected);<br>    final Uint8List _selected = await this._mapService.getBytesFromAsset(width: 140, path: &quot;assets/marker_icon.png&quot;);<br>    this._selectedIconMarker = BitmapDescriptor.fromBytes(_selected);<br>  }<br><br>   void _setIconMarkers() {<br>     if (this._unselectedIconMarker == null)return;<br>     this.houses.forEach((House house) =&gt; this._markers.add(CustomMarker(icon: this._unselectedIconMarker!, house: house, onTapHouse: this.onTapHouse)));<br>     this.notifyListeners();<br>  }<br><br><br>  void onTapHouse(House house) {<br>    this._selectedHouse = house;<br>    if (this._selectedIconMarker == null) return;<br>    this._markers.removeWhere((Marker marker) =&gt; marker.markerId.value == house.houseUid);<br>    this._markers.add(CustomMarker(icon: this._selectedIconMarker!, house: house, onTapHouse: this.onTapHouse));<br>    this.notifyListeners();<br>  }<br>}</pre><h4>Main.dart</h4><pre>import &#39;dart:async&#39;;<br><br>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:google_map_custom_icon/map_provider.dart&#39;;<br>import &#39;package:google_maps_flutter/google_maps_flutter.dart&#39;;<br>import &#39;package:provider/provider.dart&#39;;<br><br>import &#39;class/map_related.dart&#39; show House;<br><br>void main() =&gt; runApp(const GoogleMapCustomIcon());<br><br>class GoogleMapCustomIcon extends StatelessWidget {<br>  const GoogleMapCustomIcon({Key? key}) : super(key: key);<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return ChangeNotifierProvider(<br>      create: (_) =&gt; MapProvider()..init(),<br>      child: MaterialApp(home: MapScreen()),<br>    );<br>  }<br>}<br><br>class MapScreen extends StatelessWidget {<br>  MapScreen({Key? key}) : super(key: key);<br>  final Completer&lt;GoogleMapController&gt; _mapController = Completer();<br><br>  @override<br>  Widget build(BuildContext context) {<br>    final double _width = MediaQuery.of(context).size.width;<br><br>    return Scaffold(<br>        body: Stack(<br>          children: &lt;Widget&gt;[<br>            Builder(<br>              builder: (BuildContext ctx) {<br>                final MapProvider _mapProvider = Provider.of(ctx);<br>                return GoogleMap(<br>                  initialCameraPosition: const CameraPosition(target: LatLng(37.5258975, 126.9284261), zoom: 14.0),<br>                  markers: _mapProvider.markers,<br>                  onMapCreated: (GoogleMapController ct) async {<br>                    this._mapController.complete(ct);<br>                    final GoogleMapController _ct = await this._mapController.future;<br>                    _ct.setMapStyle(<br>                        &#39;[&#39;<br>                            &#39;{&quot;featureType&quot;: &quot;poi&quot;,&quot;elementType&quot;: &quot;labels&quot;, &quot;stylers&quot;: [{&quot;visibility&quot;: &quot;off&quot;}]},&#39; //<br>                            &#39;{&quot;featureType&quot;: &quot;poi.park&quot;,&quot;elementType&quot;: &quot;geometry&quot;, &quot;stylers&quot;: [{&quot;visibility&quot;: &quot;simplified&quot;}]},&#39;<br>                            &#39;{&quot;featureType&quot;: &quot;road&quot;,&quot;elementType&quot;: &quot;labels&quot;,&quot;stylers&quot;: [{&quot;visibility&quot;: &quot;off&quot;}]},&#39;<br>                            &#39;{&quot;featureType&quot;: &quot;road.highway&quot;,&quot;elementType&quot;: &quot;labels&quot;, &quot;stylers&quot;: [{&quot;visibility&quot;: &quot;on&quot;}]},&#39;<br>                            &#39;{&quot;featureType&quot;: &quot;road.arterial&quot;,&quot;elementType&quot;: &quot;labels&quot;, &quot;stylers&quot;: [{&quot;visibility&quot;: &quot;on&quot;}]},&#39;<br>                            &#39;{&quot;featureType&quot;: &quot;road.local&quot;,&quot;elementType&quot;: &quot;labels&quot;, &quot;stylers&quot;: [{&quot;visibility&quot;: &quot;on&quot;}]},&#39;<br>                            &#39;{&quot;featureType&quot;: &quot;road.highway.controlled_access&quot;,&quot;elementType&quot;: &quot;labels&quot;, &quot;stylers&quot;: [{&quot;visibility&quot;: &quot;on&quot;}]},&#39;<br>                          &#39;]&#39;<br>                    );<br>                  },<br>                );<br>              },<br>            ),<br>            Builder(<br>              builder: (BuildContext ctx) {<br>                final House? _selectedHouse = ctx.select&lt;MapProvider, House?&gt;((MapProvider p) =&gt; p.selectedHouse);<br>                if (_selectedHouse == null) return const SizedBox();<br>                return Positioned(<br>                  bottom: 50.0,<br>                  child: SizedBox(<br>                    width: _width,<br>                    height: _width * 0.4,<br>                    child: HouseInfo(house: _selectedHouse)<br>                  ),<br>                );<br>              },<br>            ),<br>          ],<br>        )<br>    );<br>  }<br>}<br><br>class HouseInfo extends StatelessWidget {<br>  const HouseInfo({Key? key, required this.house}) : super(key: key);<br>  final House house;<br><br>  @override<br>  Widget build(BuildContext context) {<br>    final double _width = MediaQuery.of(context).size.width;<br><br>    return Container(<br>      width: _width * 0.8,<br>      height: _width * 0.4,<br>      margin: EdgeInsets.only(left: _width * 0.02, right: _width * 0.03, ),<br>      padding: const EdgeInsets.symmetric(horizontal: 20.0, vertical: 15.0),<br>      decoration: BoxDecoration(<br>        color: Colors.white,<br>        borderRadius: BorderRadius.circular(20.0),<br>        border: Border.all(width: 1.5)<br>      ),<br>      child: Column(<br>        children: &lt;Widget&gt;[<br>          Text(this.house.shortDescription, style: const TextStyle(fontSize: 15.0, fontWeight: FontWeight.bold),),<br>          const Padding(<br>            padding: EdgeInsets.only(top: 20.0, left: 20.0),<br>            child: Text(&quot;whatever other details....&quot;),<br>          )<br>        ],<br>      ),<br>    );<br>  }<br>}</pre><p>Stay tuned for Part II! Happy Coding :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f8cd845cab98" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dart: Inheritance, Factory, Enums & Equality]]></title>
            <link>https://mookypoo.medium.com/dart-inheritance-factory-enums-equality-4e353d5a16d7?source=rss-a32d589adcc9------2</link>
            <guid isPermaLink="false">https://medium.com/p/4e353d5a16d7</guid>
            <category><![CDATA[inheritance]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[equality]]></category>
            <category><![CDATA[enum]]></category>
            <category><![CDATA[class]]></category>
            <dc:creator><![CDATA[Soo Kim]]></dc:creator>
            <pubDate>Sun, 22 Jan 2023 16:03:52 GMT</pubDate>
            <atom:updated>2023-01-22T16:03:52.629Z</atom:updated>
            <content:encoded><![CDATA[<h4>How I Use the Above using a Shopping App Example</h4><p>It took some time for me to become comfortable using classes and definitely struggled when I started studying programming a year and a half ago. So, I thought I’d share how I use classes, inheritance, enums and equality (in Dart). I’ll be using a shopping app as an example.</p><h3>Abstract Class &amp; Inheritance</h3><p>Abstract classes <strong>cannot be instantiated</strong> — used to create objects. Instead, you create sub-classes that inherit that class through the keyword “extends” or “implements”. In Java, abstract classes do not contain constructors, but in Dart, you can.</p><p>My example — Product — is an abstract class because I want it to be the parent class of more specific categories of products (shoes, pants, t-shirts etc).</p><pre>abstract class Product {<br>  final String productUid; <br>  final String productName;<br>  final Gender gender;<br>  final ProductType type;<br>  final bool isOnSale;<br>  final double originalPrice;<br>  final double salePercentage;<br><br>  const Product({<br>    required this.productUid,<br>    required this.productName,<br>    required this.gender,<br>    required this.type,<br>    required this.isOnSale,<br>    required this.originalPrice,<br>    required this.salePercentage<br>  });<br>}</pre><p>The advantage of having a top-level class is that you can <strong>use the parent class to refer to all its subclasses</strong>. Let’s say that you make an order. The product could be Shoes, Pants, Hoodie, Bag etc…so instead, you refer to the abstract class Product.</p><pre>class Order {<br>  final List&lt;Product&gt; products;<br>  /// and other fields<br><br>  const Order({required this.products});<br>}</pre><h4>Extend</h4><p>Think of this as your sub-class being an “extension” of the parent class. You can use <strong>super</strong> to refer to the parent class and use its objects. An easy example is that many Flutter widgets extend either StatelessWidget or StatefulWidget.</p><p>I would extend Product class for all my specific categories of products. If your parent-class has a constructor, you can use<strong> super.fieldName </strong>in the constructor, or invoke a <strong>super constructor.</strong></p><pre>class Shoes extends Product {<br>  final ShoeType shoeType;<br>  final int size;<br><br>  const Shoes({<br>    required super.productUid,<br>    required super.productName,<br>    required super.gender,<br>    required super.type,<br>    required super.originalPrice,<br>    required super.salePercentage,<br>    required this.size,<br>    required this.shoeType,<br>  }) : super (isOnSale: salePercentage &gt; 0.0 ? true : false); // super constructor<br>}<br><br>class Pants extends Product {<br>  final PantsType pantsType;<br>  final ApparelSize size;<br><br>  const Pants({required super.productUid,// ...etc});<br>}</pre><h4>Implement</h4><p>I rarely implement a class, but in to explain, in Dart, if you implement a class, <strong>all fields of the parent class must be present in the sub-class</strong>. The parent class’ fields do not have to be instantiated and methods can have empty bodies. But the sub-class must have concrete implementations. For example, ChangeNotifier (which I use as mixin for my providers) implements Listenable class.</p><p>I personally have not used implement yet, as I prefer to use mixins instead.</p><h4>Mixin</h4><p>I prefer to use mixin because I can <strong>reuse a class’s code in multiple classes</strong> without needing to implement every single one. For example, if the shopping app allows a user to change his/her profile picture AND upload a photo on his/her review, this is what I would do:</p><pre>import &#39;dart:typed_data&#39;;<br><br>class ImageService {<br>  Future&lt;Uint8List?&gt; pickPhoto() async {<br>    // some code that returns user&#39;s photo from gallery<br>  }<br><br>  Future&lt;Uint8List?&gt; takePicture() async {<br>    // some code that opens user camera and returns the photo taken <br>  }<br>}<br><br>class ReviewProvider with ImageService {<br>  List&lt;Uint8List&gt; photos = [];<br><br>  Future&lt;void&gt; pickPhotoFromGallery() async {<br>    final Uint8List? _photo = await super.pickPhoto();<br>    if (_photo == null) return;<br>    this.photos.add(_photo);<br>  }<br><br>  Future&lt;void&gt; openCamera() async {<br>    final Uint8List? _photo = await super.pickPhoto();<br>    if (_photo == null) return;<br>    this.photos.add(_photo);<br>  }<br>}<br><br>class UserProvider with ImageService {<br><br>  Future&lt;void&gt; pickPhotoFromGallery() async {<br>    final Uint8List? _photo = await super.pickPhoto();<br>    if (_photo == null) return;<br>    /// some code that changes user&#39;s photo<br>  }<br>}</pre><h3>Factory</h3><p>I use the factory constructor for two primary reasons: (1) <strong>create an instance of the class from JSON</strong>, and (2) <strong>create a new instance when a field of an existing instance has to be changed</strong>. As for the latter reason, I do so because I prefer all my classes to be <strong>immutable</strong>, which makes my code less prone to errors.</p><pre>typedef Json = Map&lt;String, dynamic&gt;;<br><br>class Shoes extends Product {<br>   // same code as above...<br>  factory Shoes.fromJson(Json json) =&gt; Shoes(<br>    productName: json[&quot;productName&quot;],<br>    productUid: json[&quot;productUid&quot;],<br>    gender: Gender.values.singleWhere((Gender gender) =&gt; gender.name == json[&quot;gender&quot;]),<br>    size: int.parse(json[&quot;size&quot;]),<br>    type: ProductType.values.singleWhere((ProductType type) =&gt; type.name == json[&quot;productType&quot;]),<br>    shoeType: ShoeType.values.singleWhere((ShoeType type) =&gt; type.name == json[&quot;shoeType&quot;]),<br>    originalPrice: double.parse(json[&quot;price&quot;]),<br>    salePercentage: double.parse(json[&quot;salePercentage&quot;]),<br>  );<br>}</pre><pre>class User {<br>  final String userUid;<br>  final String userName;<br>  final String email;<br><br>  const User({required this.userUid, required this.userName, required this.email});<br><br>  factory User.changeUserName({required User user, required String newName}) =&gt; User(<br>    userUid: user.userUid, email: user.email, userName: newName<br>  );<br>}</pre><p><strong>Sidenote: </strong>This is the code I use whenever I get a list as JSON that needs to be converted to a List of a class. There were too many places where I was re-writing basically the same code and decided to make a method to make my life easier. Instead of making the method static, you can also use it as a mixin.</p><pre>class JsonMethod {<br>  static List&lt;T&gt; convertJsonList&lt;T&gt;({required List&lt;dynamic&gt; jsonList, required T Function(Json) factory}) {<br>    final List&lt;Json&gt; _jsonList = List&lt;Json&gt;.from(jsonList);<br>    List&lt;T&gt; _list = [];<br>    _jsonList.forEach((Json json) =&gt; _list.add(factory(json)));<br>    return _list;<br>  }<br>}</pre><h3>Enums</h3><p>Enums are a great way to <strong>declare constant, customized types</strong>. In the abstract class Product, I had two enums — Gender and ProductType. Let’s look at ProductType. You can use <strong>enum.value</strong> to get the String representation of it (as I did in the factory constructor of Shoes). Also, the <strong>enum extension </strong>method was recently introduced, which allows you to define getters or methods to enumerations. Y</p><pre>enum ProductType {<br>  shoes, pants, shorts, shirt, hoodie<br>}<br><br>extension ProductTypeExt on ProductType {<br>  String get koreanName {<br>    switch (this) {<br>      case ProductType.hoodie: return &quot;후디&quot;;<br>      case ProductType.pants: return &quot;바지&quot;;<br>      case ProductType.shoes: return &quot;신발&quot;;<br>      case ProductType.shirt: return &quot;티셔츠&quot;;<br>      case ProductType.shorts: return &quot;반바지&quot;;<br>    }<br>  }<br>}<br><br>class Shoes extends Product {<br>  final ProductType type; ///....other code <br>}<br><br>final Shoes _nikeShoes = Shoes(ProductType.shoes);<br>final String _typeInKorean = _nikeShoes.type.koreanName;</pre><h4>Equality</h4><p>Even if all the variables in your classes have the same value, one does not “equal” the other. By <strong>overriding the == operator and hashCode</strong> (any two Objects that is deemed equal must have the same hashCode, although two Objects with the same hashCode isn’t necessarily equal), you can check whether one instance is the same as another.</p><pre>class Shoes extends Product {<br>  //...same code as above...<br>  <br>  @override<br>  bool operator == (other) {<br>    if (other is! Shoes) return false;<br>    if (this.productName != other.productName || this.type != other.type) return false; /// and so on...<br>    return this.productUid == other.productUid &amp;&amp; this.size == other.size;<br>  }<br><br>  @override<br>  int get hashCode =&gt; this.productUid.hashCode + this.size;<br>}</pre><p>Happy Coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4e353d5a16d7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter: Animated Progress/Count Bar]]></title>
            <link>https://mookypoo.medium.com/flutter-state-management-using-provider-animation-9eccee629195?source=rss-a32d589adcc9------2</link>
            <guid isPermaLink="false">https://medium.com/p/9eccee629195</guid>
            <category><![CDATA[provider]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[counter]]></category>
            <category><![CDATA[flutter-animation]]></category>
            <dc:creator><![CDATA[Soo Kim]]></dc:creator>
            <pubDate>Sat, 21 Jan 2023 03:09:44 GMT</pubDate>
            <atom:updated>2023-01-22T13:43:33.485Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oJyJxdBff9MSamZJ-N7XgA.jpeg" /></figure><p>I made a very simple progress/count bar app that I thought would be useful in sharing my programming stylistic choices, how I use Provider and animation in Flutter. Click <a href="https://github.com/mookypoo/animated_progress_bar.git">here</a> for the full code.</p><p><strong>Side-note</strong>: I’ve only used Provider for state management so I am limited in my knowledge of other state management packages, but one fact I know for certain is do not use GetX. I even quit my previous job because the new team manager wanted to re-do the whole app using GetX and I disagreed firmly trying it out due to various reasons that I won’t get into. This happened 2 months after my first job ever as a developer…</p><p>As you read through my code, you might notice some stylistic differences in my code with which some people might disagree. I do think, however, that although Dart is a statically typed language, <strong>do always declare your variable with a specific type</strong>. It reads better, prevents runtime errors, and actually allocates a (smaller and) proper amount of space for the variable.</p><p><a href="https://youtube.com/shorts/HyIYkPxrNNE?feature=share">Animated Progress Bar</a></p><h4>main.dart</h4><p>When I create instances of my provider, rarely do I actually listen to it (or use context.watch()). Usually, I will <strong>create an instance using listen: false</strong> in order to use its methods, and in each widget that requires a changing value from the provider, use the <strong>Builder widget + context.select()</strong>.</p><pre>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:progress_bar/progress_bar.dart&#39;;<br>import &#39;package:provider/provider.dart&#39;;<br><br>import &#39;animated_bar.dart&#39;;<br>import &#39;count_provider.dart&#39;;<br><br>void main() =&gt; runApp(const ProgressBarApp());<br><br>class ProgressBarApp extends StatelessWidget {<br>  const ProgressBarApp({Key? key}) : super(key: key);<br><br>  @override<br>  Widget build(BuildContext context) {<br>    /// in an actual app, you&#39;ll be using MultiProvider<br>    return ChangeNotifierProvider&lt;CountProvider&gt;(<br>      create: (_) =&gt; CountProvider(),<br>      child: const MaterialApp(home: Home()),<br>    );<br>  }<br>}<br><br>class Home extends StatelessWidget {<br>  const Home({Key? key}) : super(key: key);<br><br>  @override<br>  Widget build(BuildContext context) {<br>    /// listen: false if you do not want this widget to rebuild when the provider notifies its listeners<br>    /// since I&#39;m only creating the instance to use its methods, do not need to listen<br>    final CountProvider _countProvider = Provider.of(context, listen: false);<br>    return Scaffold(<br>      body: Center(<br>        child: Column(<br>          mainAxisAlignment: MainAxisAlignment.center,<br>          children: &lt;Widget&gt;[<br>            Builder(<br>              /// use Builder + select so that only this widget will rebuild when the selected value changes in a provider <br>              builder: (BuildContext ctx) {<br>                final int _count = ctx.select&lt;CountProvider, int&gt;((CountProvider p) =&gt; p.count1);<br>                return ProgressBar(count: _count);<br>              },<br>            ),<br>            Padding(<br>              padding: const EdgeInsets.symmetric(vertical: 30.0),<br>              child: Row(<br>                mainAxisAlignment: MainAxisAlignment.center,<br>                children: &lt;Widget&gt;[<br>                  IconButton(<br>                    icon: const Icon(Icons.remove),<br>                    onPressed: _countProvider.removeCount1,<br>                  ),<br>                  IconButton(<br>                    icon: const Icon(Icons.add),<br>                    onPressed: _countProvider.addCount1,<br>                  ),<br>                ],<br>              ),<br>            ),<br>            const AnimatedBar(),<br>          ],<br>        ),<br>      ),<br>    );<br>  }<br>}</pre><p>Some might ask, why not use context.select() in ProgressBar itself and not use Builder. I’d say that’s fine if you’re using a widget that will not be re-used anywhere else. I use the ProgressBar widget in two different places — and hence, use Builder to pass on the count value.</p><h4>ProgressBar</h4><p>Straight-forward UI so no explanation for the progress bar.</p><pre>import &#39;package:flutter/material.dart&#39;;<br><br>class ProgressBar extends StatelessWidget {<br>  const ProgressBar({Key? key, required this.count}) : super(key: key);<br>  final num count;<br><br>  @override<br>  Widget build(BuildContext context) {<br>    final double _barWidth = MediaQuery.of(context).size.width * 0.7;<br><br>    return Row(<br>      mainAxisAlignment: MainAxisAlignment.center,<br>      crossAxisAlignment: CrossAxisAlignment.end,<br>      children: &lt;Widget&gt;[<br>        Stack(<br>          children: &lt;Widget&gt;[<br>            Container(<br>              margin: const EdgeInsets.only(right: 20.0),<br>              height: 20.0,<br>              width: _barWidth,<br>              decoration: BoxDecoration(<br>                borderRadius: BorderRadius.circular(15.0),<br>                color: const Color.fromRGBO(234, 234, 234, 1.0)<br>              ),<br>            ),<br>            Container(<br>              height: 20.0,<br>              width: _barWidth * count/7,<br>              decoration: BoxDecoration(<br>                  borderRadius: BorderRadius.circular(15.0),<br>                  gradient: const LinearGradient(<br>                    colors: &lt;Color&gt;[<br>                      Color.fromRGBO(185, 235, 255, 1.0),<br>                      Color.fromRGBO(145, 224, 255, 1.0),<br>                      Color.fromRGBO(85, 206, 255, 1.0),<br>                      Colors.lightBlueAccent,<br>                    ],<br>                    stops: [0.25, 0.5, 0.75, 1.0],<br>                  )<br>              ),<br>            ),<br>          ],<br>        ),<br>        RichText(<br>          text: TextSpan(<br>            style: const TextStyle(color: Colors.black, fontSize: 15.0, fontWeight: FontWeight.w600),<br>            children: &lt;InlineSpan&gt;[<br>              TextSpan(<br>                text: count.roundToDouble().toString().substring(0, 1),<br>                style: const TextStyle(color: Colors.lightBlueAccent, fontSize: 24.0),<br>              ),<br>              const TextSpan(text: &quot;  /  7&quot;)<br>            ],<br>          ),<br>        ),<br>      ],<br>    );<br>  }<br>}</pre><h4>Count Provider</h4><p>The only thing to explain here is that for the bottom bar (animated), when the count reaches 7, a pop up dialog opens and when it is closed, the progress bar goes back to 0 and a coupon is “issued” (which starts as a small icon and becomes bigger). These steps are done using resetCount() and changeCount().</p><pre>import &#39;package:flutter/foundation.dart&#39;;<br><br>class CountProvider extends ChangeNotifier {<br>  /// for static progress bar<br>  int _count1 = 0;<br>  int get count1 =&gt; this._count1;<br>  set count1(int i) =&gt; throw &quot;error&quot;;<br><br>  /// for animated progress bar<br>  double _count2 = 6.0;<br>  double get count2 =&gt; this._count2;<br>  set count2(double i) =&gt; throw &quot;error&quot;;<br><br>  int _couponCount = 2;<br>  int get couponCount =&gt; this._couponCount;<br>  set couponCount(int i) =&gt; throw &quot;error&quot;;<br><br>  bool _needNewCoupon = false;<br>  bool get needNewCoupon =&gt; this._needNewCoupon;<br>  set needNewCoupon(bool b) =&gt; throw &quot;error&quot;;<br><br>  void addCount1(){<br>    if (this._count1 == 7) return;<br>    this._count1++;<br>    this.notifyListeners();<br>  }<br><br>  void removeCount1(){<br>    if (this._count1 == 0) return;<br>    this._count1--;<br>    this.notifyListeners();<br>  }<br><br>  /// called when progress bar is animating &amp; completed<br>  void changeCount(double count){<br>    if (count == 0 &amp;&amp; this._needNewCoupon) {<br>      this._couponCount ++;<br>      this._needNewCoupon = false;<br>      this.notifyListeners();<br>    }<br>    this._count2 = count;<br>    this.notifyListeners();<br>  }<br><br>  void resetCount(){<br>    this._needNewCoupon = true;<br>    this.notifyListeners();<br>  }<br>}</pre><h4>Animated Progress Bar — UI and Setting the Animation Up</h4><p>For the animated one, you need a <strong>stateful widget with TickerProviderStateMixin. </strong>I’ll go over the view first.</p><pre>@override<br>Widget build(BuildContext context) {<br>  return Column(<br>    children: &lt;Widget&gt;[<br>      Row(<br>        children: &lt;Widget&gt;[<br>          Builder(<br>            builder: (BuildContext ctx) {<br>              final int _stampCount = ctx.select&lt;CountProvider, int&gt;((CountProvider p) =&gt; p.couponCount);<br>              if (_stampCount == 0) return const SizedBox();<br>              return Container(<br>                margin: const EdgeInsets.only(left: 30.0),<br>                child: Row(<br>                  children: List.generate(_stampCount, (int i) =&gt; SizedBox(<br>                    width: 30.0,<br>                    child: Icon(Icons.local_attraction, size: 26.0),),<br>                  ),<br>                ),<br>              );<br>            },<br>          ),<br>          Builder(<br>            builder: (BuildContext ctx) {<br>              final bool _needNewStamp = ctx.select&lt;CountProvider, bool&gt;((CountProvider p) =&gt; p.needNewCoupon);<br>              if (!_needNewStamp) return const SizedBox();<br>              return Container(<br>                width: 30.0,<br>                child: Icon(Icons.local_attraction, size: this._stampAnimation?.value ?? 26.0),<br>              );<br>            },<br>          ),<br>        ],<br>      ),<br>      Builder(<br>        builder: (BuildContext ctx) {<br>          final double _count = ctx.select&lt;CountProvider, double&gt;((CountProvider p) =&gt; p.count2);<br>          return ClipRRect(<br>            borderRadius: BorderRadius.circular(15.0),<br>            child: ProgressBar(count: _count),<br>          );<br>        },<br>      ),<br>      Padding(<br>        padding: const EdgeInsets.symmetric(vertical: 30.0),<br>        child: Row(<br>          mainAxisAlignment: MainAxisAlignment.center,<br>          children: &lt;Widget&gt;[<br>            IconButton(<br>              icon: const Icon(Icons.remove),<br>              onPressed: () async {<br>                final int _count = this._countAnimation!.value.toInt();<br>                if (_count == 0) return;<br>                this._countAnimation = Tween&lt;double&gt;(begin: _count.toDouble(), end: _count - 1).animate(this._countAnimationController!);<br>                this._countAnimationController?.reset();<br>                await this._countAnimationController!.forward();<br>              },<br>            ),<br>            IconButton(<br>              icon: const Icon(Icons.add),<br>              onPressed: () async {<br>                final int _count = this._countAnimation!.value.toInt();<br>                this._countAnimation = Tween&lt;double&gt;(begin: _count.toDouble(), end: _count + 1).animate(this._countAnimationController!);<br>                this._countAnimationController?.reset();<br>                await this._countAnimationController!.forward();<br>              },<br>            ),<br>          ],<br>        ),<br>      ),<br>    ],<br>  );<br>}</pre><p>As you can see here, I’ve used Builder for 3 different components — count, coupons, and needNewCoupon, which is used for the newly issued coupon that animates from small → big. This way, only the necessary parts are rebuilt when the progress bar is animating. The _count variable is changed the whole duration of the animation, but the number of coupons and needNewCoupon will not change until the count reaches 7.</p><p>Now, for the <strong>animation</strong>. Let’s look just at the a snippet of initState and the + method to see how to begin the <strong>progress bar animation.</strong></p><pre>Animation&lt;double&gt;? _countAnimation;<br>AnimationController? _countAnimationController;<br><br>@override<br>void initState() {<br>  super.initState();<br>  this._countAnimationController = AnimationController(vsync: this, duration: const Duration(milliseconds: 600))<br>    ..addListener(() async {<br>      ...(bunch of code)...<br>    });<br>  final double _count = context.read&lt;CountProvider&gt;().count2;<br>  this._countAnimation = Tween&lt;double&gt;(begin: _count, end: _count+1).animate(this._countAnimationController!);<br>}<br><br>/// + button onPressed<br>() async {<br>    final int _count = this._countAnimation!.value.toInt();<br>    this._countAnimation = Tween&lt;double&gt;(begin: _count.toDouble(), end: _count + 1).animate(this._countAnimationController!);<br>    this._countAnimationController?.reset();<br>    await this._countAnimationController!.forward();<br>  },</pre><p>There are two classes you need for animation (my animation way anyways…there are other ways): <strong>Animation</strong> and <strong>Animation Controller. </strong>You have to instantiate the controller in initState because it needs the “Ticker Provider” (and therefore, “this” — the stateful widget — because the <strong>TickerProviderStateMixin </strong>is used). You also have to instantiate the animation in the initState because it needs the controller (in .animate( )).</p><p>So in initState, I instantiate the animation controller and then add a listener so that I can change my variables in count provider. Then, I assign it to the Tween animation. I need to assign the animation here first so that I can use its value when the + is pressed. <strong>Be careful with the null safety here</strong>…make sure that all variables are assigned before you use them!</p><p>When you first press the + button, it gets the animation value (which will be the count) and assign a new animation. If you<strong> .forward()</strong> the animation controller, the animation begins! (There’s reverse, reset, stop etc). I have <strong>.reset() </strong>because I need a new animation to begin (go forward) each time I press the button but “reverse” will just reverse the previous animation.</p><h4>Animated Progress Bar — the Animation Itself</h4><p>Let’s look at the my full code for initState that includes the count animation and coupon animation.</p><pre>@override<br>void initState() {<br>  super.initState();<br>  this._countAnimationController = AnimationController(vsync: this, duration: const Duration(milliseconds: 600))<br>    ..addListener(() async {<br>      <br>      if (this._countAnimationController!.isAnimating) {<br>        context.read&lt;CountProvider&gt;().changeCount(this._countAnimation!.value);<br>      }<br><br>      if (this._countAnimationController!.isCompleted) {<br>        context.read&lt;CountProvider&gt;().changeCount(this._countAnimation!.value);<br>        if (context.read&lt;CountProvider&gt;().count2 == 7) {<br>          await showDialog(<br>            context: context,<br>            builder: (BuildContext ctx) {<br>              return Dialog(<br>                child: Container(<br>                    alignment: Alignment.center,<br>                    height: 150.0,<br>                    width: 100.0,<br>                    child: Column(<br>                      mainAxisAlignment: MainAxisAlignment.center,<br>                      children: &lt;Widget&gt;[<br>                        Text(&quot;Congratulations!\nYou have received a coupon!&quot;, style: TextStyle(fontSize: 16.0),),<br>                        TextButton(onPressed: Navigator.of(ctx).pop, child: Text(&quot;Close&quot;, style: TextStyle(fontSize: 18.0, fontWeight: FontWeight.w600),))<br>                      ],<br>                    )<br>                ),<br>              );<br>            },<br>          );<br>         <br>          this._countAnimation = Tween&lt;double&gt;(begin: 7.0, end: 0.0).animate(this._countAnimationController!);<br>          this._countAnimationController?.reset();<br>          context.read&lt;CountProvider&gt;().resetCount();<br>          this._countAnimationController!.forward();<br>          this._couponAnimationController!.forward();<br>        }<br>      }<br>    });<br><br>  this._couponAnimationController = AnimationController(vsync: this, duration: Duration(milliseconds: 600))<br>    ..addListener(() {<br>      if (this._couponAnimationController!.isAnimating) this.setState(() {});<br>    });<br>  final double _count = context.read&lt;CountProvider&gt;().count2;<br>  this._couponAnimation = Tween&lt;double&gt;(begin: 15.0, end: 26.0).animate(this._couponAnimationController!);<br>  this._countAnimation = Tween&lt;double&gt;(begin: _count, end: _count+1).animate(this._countAnimationController!);<br>}</pre><p>When the animation is in progress, you want to <strong>notify the count variable so that it updates the progress bar</strong>. If you don’t use changeNotifier, you’d have to use setState to update the UI (as I did in the couponAnimationController). However, that means I’ll be updating the whole widget, which includes the coupons and the buttons. With the builder + this method, I can update only the progress bar.</p><p>You also need to notify the count when the animation is complete (when the animation reaches its end value). If not, the animation will stop short. For example, if the progress bar is going from 3 to 4, it’ll stop at 3.92. When the animation is complete and the count is 7, it shows a pop up dialog, after which the progress bar goes from 7 → 0, and the coupon animation begins.</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9eccee629195" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter Web: Problems, Solutions, and My Conclusion]]></title>
            <link>https://mookypoo.medium.com/flutter-web-problems-solutions-and-my-conclusion-294762701d80?source=rss-a32d589adcc9------2</link>
            <guid isPermaLink="false">https://medium.com/p/294762701d80</guid>
            <category><![CDATA[flutter-web]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Soo Kim]]></dc:creator>
            <pubDate>Thu, 27 Oct 2022 12:14:27 GMT</pubDate>
            <atom:updated>2022-11-12T10:15:01.322Z</atom:updated>
            <content:encoded><![CDATA[<h4>My thoughts building my first web page using Flutter</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/1*6Z1eNCLvof10rPqxLYrfgQ.png" /><figcaption><a href="https://flutter.dev/multi-platform/web">https://flutter.dev/multi-platform/web</a></figcaption></figure><p>I’ve been assigned a new project at work — to build our company website using Flutter. While doing so, I encountered some problems that I had not occurred while developing an app using Flutter, so I thought I’d share them. But before I do, here’s my conclusion as to building a web “app” using Flutter. Please take it with a grain of salt as I only built one web page with it and and may not be experienced enough.</p><p><strong>If you’re building a very simple website, I think it should be fine. But anything more complex in structure, you should stick to JavaScript.</strong> Although Flutter Web does provide you with convenience, it had more hurdles than I expected. Here are the hurdles/other information:</p><p>(1) Url — Query Parameters (and Leading Hash)<br>(2) How to Run Flutter Web on Mobile Browser?<br>(3) How to Know What the “Platform” is?<br>(3) How to Change Title &amp; Favicon Icon</p><h4>Url — Query Parameters (and Leading Hash)</h4><p>First of all, Flutter’s web apps start with hash (#) — I’m not sure why, but it seems unnecessary…but thankfully, it can be removed with the <a href="https://pub.dev/packages/url_strategy">url_strategy</a> package. Done!</p><p>Before going on to onGenerateRoute — page transitions. Without any configuration, Flutter will use the default transition for mobiles phones, which is usually not what we want for web. So, I use the below transition (which basically is “no transition” with no animation).</p><pre>import &#39;package:flutter/material.dart&#39;;<br><br>class CustomPageRoute&lt;T&gt; extends MaterialPageRoute&lt;T&gt; {<br>  CustomPageRoute({required Widget page, required String routeName})<br>    : super(builder: (BuildContext context) =&gt; page, settings: RouteSettings(name: routeName));<br><br>  @override<br>  Widget buildTransitions(BuildContext context, _, __, Widget child) {<br>    return child;<br>  }<br>}</pre><p>Now, what about the url? For web apps, we need to use <strong>onGenerateRoute</strong>.</p><pre>onGenerateRoute: (RouteSettings route) {<br>    /// for when page is pushed using Navigator<br>    if (route.name == &quot;/&quot;) {<br>      return CustomPageRoute(page: HomePage(contactUsType: _contactUsType), routeName: HomePage.routeName);<br>    }<br>    if (route.name == StoresPage.routeName) {<br>        final int _pageIndex = route.arguments as int;<br>        return CustomPageRoute(page: StoresPage(isPushed: true), routeName: &quot;/stores?page=${_pageIndex.toString()}&quot;);<br>      }<br>      if (route.name == StoreDetailPage.routeName) {<br>        final String _storeId = route.arguments as String;<br>        return CustomPageRoute(page: const StoreDetailPage(), routeName: &quot;/stores?store_id=$_storeId&quot;);<br>      }<br><br>    /// for when page is refreshed and there is a query variable (if no variable, this part is not needed)<br>    if (Uri.base.hasQuery) {<br>        final String? _pageIndex = Uri.base.queryParameters[&quot;page&quot;];<br>        final String? _storeId = Uri.base.queryParameters[&quot;store_id&quot;];<br>        if (_pageIndex != null) return CustomPageRoute(page: StoresPage(), routeName: &quot;/stores?page=$_pageIndex&quot;);<br>        if (_storeId != null) return CustomPageRoute(page: StoreDetailPage(), routeName: &quot;/stores?store_id=$_storeId&quot;);<br>      }<br>    return CustomPageRoute(page: const HomePage(), routeName: HomePage.routeName);<br>  },<br>),</pre><p>When you push using Navigator, you can put an argument in, which you can receive through <strong>route.arguments </strong>and use that to pass onto your page. You CANNOT use ModalRoute.of(context)?.settings.arguments in the page to receive the arguments in Flutter web. In the above code, I used it to set my <strong>query parameter</strong> so that I can display the url like a proper website. Notice that StoresPage and StoreDetailPage have different routeNames, but the actual url begins with the same path: /stores.</p><pre>await Navigator.of(context).pushNamed(StoreDetailPage.routeName, arguments: _stores[index].storeId);</pre><p>In the second part of onGenerate, I use<strong> Uri</strong>. to find information related to the url (like base, host, path, query, has query, query parameters etc). I added this portion because when I refresh the browser, all my state variables saved in my providers are lost, and any page with query variables will not be directed to the appropriate page (with just the top part of the above code). So I use the query value to direct it to the appropriate page, and if necessary, restore the appropriate state variables.</p><p><strong>Oddly, when pushing the same page that had a query value that was different from the page pushing it </strong>(for example, from stores?page=1 to stores?page=2),<strong> the page loaded twice. </strong>When debugging it, I found out that it was loading again because the query variable changed (to the previous value). This was weird and I still do not have an answer to this.</p><p>Final word, when pushing the same page but with a different query value, I found that it was better to pushReplacementNamed than just push because that means the same page is pushed repetitively, resulting in multiple reloads.</p><h4>How to Run Flutter Web on Mobile Browser?</h4><p>We definitely want to test how the webpage works on the mobile browser…but I struggled initially because it wouldn’t load my lotteflies nor detect any gestures. But I finally found the solution:</p><pre>flutter run -d web-server --web-port 1234 --web-hostname &lt;your_ip_address&gt; --web-renderer canvaskit</pre><p>Honestly, I don’t know enough about server/internet connections, so I explain the above code with 100% certainty, but I will share what I deduced. So, for you to open your web app on a mobile browser, you need to <strong>open it on a specific port</strong> (web-server — web-port 1234) (here, the port is 1234).</p><p>The — web-hostname specifies what will be the <strong>host of that port</strong>. You can put your ip address there (type ifconfig in terminal, and in en0, you should see your ip address after “inet”) or you can just put 0.0.0.0 (which tells the server to listen on all available network interface — which I presume…that if you connected from a different ip address with port 1234…your app might pop up?). Either way, you should be able to open your web app on your mobile browser if you put the following in the url:</p><pre>http://&lt;ip_address&gt;:1234</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/298/1*RsLTcu3Nzb6Qwf2WpMuH_g.png" /><figcaption>ifconfig</figcaption></figure><p>If you go to your ip site by putting in your ip address in the url, you could play with the the port forwarding configuration so that your coworkers can see your work (you’d have to run your application “server” first).</p><p>There are two different <a href="https://docs.flutter.dev/development/platform-integration/web/renderers"><strong>web renderers — HTML </strong>and <strong>CanvasKit</strong></a>. If you run your web app without specifying which renderer, it will automatically select HTML on a mobile browser and CanvasKit on a desktop browser. I found that the HTML renderer does not allow me to use gestures (scroll or tap a button) nor load my lottieflies animation. While the HTML renderer has a benefit of being much smaller in size, it is not fully consistent with Flutter mobile and desktop functions, because it uses only HTML elements, CSS, Canvas elements, and SVG elements.</p><p>However, when you use CanvasKit, there are other problems. For example, you cannot inspect your code through chrome, nor will some elements that appear fine when built with HTML not appear (ellipsis will appear with odd characters). The font size, font weight, and some other UI features seem to be different as well.</p><p>Also, I encountered <strong>XMLHttpRequest Error</strong> when trying to connect to our server (I wasn’t able to verify whether this is the same when the app is rendered using HTML), which my backend developer solved by changing some configurations on Nginx, and I was able to debug on chrome on my MacBook. However, the problem still persisted when debugging on the mobile browser.</p><p><strong>My thoughts</strong>: I think it’s better to render with HTML if possible, and only switch to CanvasKit if necessary.</p><h4>How to Know What the “Platform” is?</h4><p>I was so used to using Platform.isAndroid, Platform.isIOS etc. to determine the OS of the user’s device, but the dart:io library from which it is imported does not work with Flutter web apps. Thankfully, <a href="https://stackoverflow.com/questions/58459483/unsupported-operation-platform-operatingsystem">stack overflow</a> gave me a solution:</p><pre>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:flutter/foundation.dart&#39;;<br><br>class HomePage extends StatelessWidget {<br>  const HomePage({Key? key}) : super(key: key);<br>  static const routeName = &quot;/&quot;;<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return defaultTargetPlatform == TargetPlatform.iOS || defaultTargetPlatform == TargetPlatform.android<br>      ? const HomeMobile()<br>      : const HomeWeb();<br>  }<br>}</pre><p>I ended up adding a width boolean to the above code because I wanted the desktop version to be loaded to tablets and iPads.</p><h4>How to Change Title &amp; Favicon Icon</h4><p><strong>Icon:</strong> (1) add image to web/icons of your build folder and (2) in your html file in the web build folder, replace the favicon line with</p><pre>&lt;link rel=&quot;shortcut icon&quot; type=&quot;image/png&quot; href=&quot;icons/your-icon-name.jpg&quot; /&gt;</pre><p><strong>Title: </strong>add title value to MaterialApp.</p><p>I’m not sure whether I’m the only one that struggled with Flutter Web, but for now, I do think convenience comes at a cost. Maybe if you use html within your code, it could work better, like how sometimes, you want to use native code in your Flutter application.</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=294762701d80" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>