<?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 Jitesh Mohite on Medium]]></title>
        <description><![CDATA[Stories by Jitesh Mohite on Medium]]></description>
        <link>https://medium.com/@jitsm555?source=rss-80fd7c1ebd73------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*m-i4FdkRO4ORLuAjSAx67Q.png</url>
            <title>Stories by Jitesh Mohite on Medium</title>
            <link>https://medium.com/@jitsm555?source=rss-80fd7c1ebd73------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 04:48:50 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jitsm555/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Flutter/Dart: Design Pattern- Singleton]]></title>
            <link>https://medium.com/flutterworld/flutter-dart-design-pattern-singleton-c63be89c0b75?source=rss-80fd7c1ebd73------2</link>
            <guid isPermaLink="false">https://medium.com/p/c63be89c0b75</guid>
            <category><![CDATA[flutter-singleton-pattern]]></category>
            <category><![CDATA[design-patterns-flutter]]></category>
            <category><![CDATA[dart-design-patterns]]></category>
            <category><![CDATA[flutter-world]]></category>
            <category><![CDATA[dart-singleton-pattern]]></category>
            <dc:creator><![CDATA[Jitesh Mohite]]></dc:creator>
            <pubDate>Sat, 02 Oct 2021 13:19:15 GMT</pubDate>
            <atom:updated>2021-10-09T14:12:20.675Z</atom:updated>
            <content:encoded><![CDATA[<p>Design patterns are important when it comes to software development, and choosing the right one gives us a lot of headaches. Singleton pattern comes under Creational Design Patterns, which says</p><blockquote>In software engineering, <strong>creational design patterns</strong> are design patterns that deal with object creation mechanisms, trying to create objects in a manner suitable to the situation.</blockquote><p><strong>Singleton pattern</strong> is useful to restrict the instantiation of a class to one &quot;single&quot; instance. This is useful when exactly one object is needed to coordinate actions across the system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nqG-mT52WcOgGcEPiDg2ig.png" /></figure><p>It seems to be a simple design pattern but when it comes to implementation, it comes with a lot of implementation concerns. The implementation of the Singleton pattern has always been a controversial topic among developers. Here, We are going to discuss how to create a Singleton class that fulfills its purpose :</p><p>There are two ways to create a Singleton class:</p><ol><li>Eager Initialization</li><li>Lazy Initialization</li></ol><p>So, Let&#39;s dive inside now</p><h3>Eager Initialization:</h3><p>This is the simplest approach for creating a singleton class, In this instance of the class is created at the time of class loading which is done by DVM(Dart Virtual Machine). It can be used when the program will always use an instance of this class, or the cost of creating the instance is not too large in terms of resources and time.</p><pre>class Singleton {<br>  static Singleton _instance = Singleton._();<br><br>  Singleton._();<br><br>  static Singleton get instance =&gt; _instance;<br>  </pre><pre>  void someMethod() {<br>    print(&quot;someMethod Called&quot;);<br>  }  <br>}</pre><h3>Lazily Initialization:</h3><p>In this method, the object is created only if it is needed. This may prevent resource wastage. An implementation of the Singleton() the method is required which returns the instance. To make sure that class cannot be instantiated in any other way, the constructor is made private. As the object is created within a method, it ensures that the object will not be created until and unless it is required.</p><pre>class Singleton {<br>  static Singleton? _instance;<br><br>  Singleton._internal();<br><br>  factory Singleton() =&gt; _instance ??= Singleton._internal();<br>  <br>  void someMethod() {<br>    print(&quot;someMethod Called&quot;);<br>  }<br>}</pre><p><strong>Pros:</strong></p><ul><li>Restrict the number of instances, which ensures that a class can have only one instance, throughout the application.</li><li>Access a global variable, anywhere required.</li></ul><p><strong>Cons:</strong></p><ul><li>Unit test cases required loosely coupled classes, in order to test write better test cases, as they maintain a global state of variables it becomes difficult to test specific scenarios. The solution would be to create parameterized constructor/method to pass singleton objects.</li><li>It violates the Single Responsibility Principle, as it maintains the global state through the app.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c63be89c0b75" width="1" height="1" alt=""><hr><p><a href="https://medium.com/flutterworld/flutter-dart-design-pattern-singleton-c63be89c0b75">Flutter/Dart: Design Pattern- Singleton</a> was originally published in <a href="https://medium.com/flutterworld">FlutterWorld</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter: Equatable & It’s usage in Bloc]]></title>
            <link>https://medium.com/flutterworld/flutter-equatable-its-use-inside-bloc-7d14f3b5479b?source=rss-80fd7c1ebd73------2</link>
            <guid isPermaLink="false">https://medium.com/p/7d14f3b5479b</guid>
            <category><![CDATA[flutter-world]]></category>
            <category><![CDATA[equatableflutter]]></category>
            <category><![CDATA[whatisequatable]]></category>
            <category><![CDATA[blocequatable]]></category>
            <dc:creator><![CDATA[Jitesh Mohite]]></dc:creator>
            <pubDate>Thu, 10 Jun 2021 18:15:16 GMT</pubDate>
            <atom:updated>2021-06-10T18:20:51.284Z</atom:updated>
            <content:encoded><![CDATA[<p>In Dart or any language, We always find it difficult to compare objects and return results. If we do not implement it correctly then in the long term you will face a lot of problems, as this will provide the wrong output as data is not compared as expected, Let&#39;s see an example of <strong>how dart solve it?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*exxvKDLwKEyN2qdNnHhlGg.png" /></figure><p>First, we will see the problem which we will be trying to fix</p><pre>void main() {<br>  User user = User(&#39;jitsm555&#39;);<br>  print(user == User(&#39;jitsm555&#39;)); // Output: false<br>}<br><br>class User {<br>  final String name;<br><br>  User(this.name);<br>}</pre><p>As you can see above, both objects having the same values, but while comparing they returns <strong>false</strong>. This happens because both have different hashcode internally.</p><p><strong>Solution!!!</strong></p><pre>import &#39;package:equatable/equatable.dart&#39;;<br><br>void main() {<br>  User user = User(&#39;jitsm555&#39;);<br>  print(user == User(&#39;jitsm555&#39;)); // Output: true<br>}<br><br>class User extends Equatable {<br>  final String name;<br><br>  User(this.name);<br><br>  @override<br>  List&lt;Object?&gt; get props =&gt; [name];<br>}</pre><p>Object and data comparison is always hard to do, So here comes theEquatable as it overrides == and hashCode internally, which solves our purpose of data comparison and eventually will save a lot of boilerplate code.</p><p>If we are not using theEquatable then we have to write our own code for object comparison like</p><pre>class User {<br>  final String name;<br><br>  User(this.name);<br><br>  @override<br>  bool operator ==(Object other) =&gt; other is User &amp;&amp;<br>                                    name == other.name;<br><br>  @override<br>  int get hashCode =&gt; name.hashCode;<br>}</pre><p>So, coming to the usage of theEquatable in Bloc, becomes important as it updates the state as per the object changes, so before jumping on it, I recommend you to read the blog on the <a href="https://medium.com/flutterworld/flutter-bloc-mystery-part-1-34c2d20cd092"><strong>Bloc Mystery | Part 1</strong></a><strong> </strong>first, as the below topic required some knowledge around it.</p><p><strong>Dependency:</strong></p><p>To use theEquatable add the dependency in pubspec.yaml file</p><pre>dependencies:<br>  equatable: ^2.0.2</pre><blockquote>In Bloc, we have to extend Equatable to States and Events classes to use this functionality. This helps us when it comes to stream as we need to decide state updation based on it.</blockquote><p>Ex:</p><pre>abstract class LoginState extends Equatable {}</pre><p>LoginState will not make duplicate calls and will not going to rebuild the widget if the same state occurs. Now, think we haven&#39;t used Equatable it here, then how many times Widget will be rebuild.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Fl0HlRnAWXxn0MhKLK%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fbook-library-literacy-l0HlRnAWXxn0MhKLK&amp;image=https%3A%2F%2Fmedia2.giphy.com%2Fmedia%2Fl0HlRnAWXxn0MhKLK%2Fgiphy.gif%3Fcid%3D790b7611a14d660e042d10325895eb5a0d52c6677fac5690%26rid%3Dgiphy.gif%26ct%3Dg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="315" frameborder="0" scrolling="no"><a href="https://medium.com/media/851809cc972d0dd640be2a38b1176be5/href">https://medium.com/media/851809cc972d0dd640be2a38b1176be5/href</a></iframe><p>Equatable comes with props property which have its own purpose in object comparison, I have seen developers been neglecting this, and later face a lot of time in debugging.</p><p>Let’s see props usage in Equatable and what makes it special</p><p><strong>Define State without props:</strong></p><pre>class LoginLoadSuccess extends LoginState {<br>  final String name;<br>  final List&lt;User&gt; users;<br>  const LoginLoadSuccess([this.name, this.users = const []]);<br>}</pre><p><strong>Define State with props:</strong></p><p>props declared when we want State to be compared against the values declared inside props List</p><pre>class LoginLoadSuccess extends LoginState {<br>  final String name;<br>  final List&lt;User&gt; users;<br>  const LoginLoadSuccess([this.name, this.users = const []]);</pre><pre>   @override<br>   List&lt;Object&gt; get props =&gt; [name, users];</pre><pre> }</pre><p>props property decides which objects we should consider for object comparison, Suppose if we remove the name from the props then State will only consider the users field, avoiding the name field for object comparison. That is why it&#39;s important to use it carefully, as one mistake can cost a lot of time.</p><p><strong>Bloc Stream Usage:</strong></p><p>As we extending State with Equatable which makes a comparison of old state data with new state data.</p><p>For example, let&#39;s look at the below example here LoginState will build a widget only once, which will avoid the second call as it is duplicated.</p><pre>@override<br>Stream&lt;LoginState&gt; mapEventToState(MyEvent event) async* {<br>  final List&lt;User&gt; users = [User(), User()];<br>  yield LoginLoadSuccess(users);<br>  yield LoginLoadSuccess(users); <br>  /// Second call will be avoided, means widget will not rebuild<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7d14f3b5479b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/flutterworld/flutter-equatable-its-use-inside-bloc-7d14f3b5479b">Flutter: Equatable &amp; It’s usage in Bloc</a> was originally published in <a href="https://medium.com/flutterworld">FlutterWorld</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter: Bloc Mystery | Part 1]]></title>
            <link>https://medium.com/flutterworld/flutter-bloc-mystery-part-1-34c2d20cd092?source=rss-80fd7c1ebd73------2</link>
            <guid isPermaLink="false">https://medium.com/p/34c2d20cd092</guid>
            <category><![CDATA[what-is-bloc]]></category>
            <category><![CDATA[bloc-article]]></category>
            <category><![CDATA[flutter-world]]></category>
            <category><![CDATA[bloc-architecture]]></category>
            <category><![CDATA[flutter-bloc]]></category>
            <dc:creator><![CDATA[Jitesh Mohite]]></dc:creator>
            <pubDate>Sat, 29 May 2021 18:24:42 GMT</pubDate>
            <atom:updated>2021-06-10T13:11:15.474Z</atom:updated>
            <content:encoded><![CDATA[<p>As the title suggests we are going to learn some exciting stuff about Bloc and its usage. Also will cover some of the advanced concepts which can be integrated into code easily, so keep reading….</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d17Db0fcgO5ZUVsQxiYm3w.png" /></figure><blockquote>Flutter is designed in a reactive way with asynchronous data <strong>Streams</strong>. A Stream is basically a simple object which emits data whenever any change happens. To get notified about data changes we have to subscribe to the stream, which will notify the changes until it despose.</blockquote><blockquote>It is like an asynchronous Iterable — where, instead of getting the next event when you ask for it, the stream tells you that there is an event when it is ready.Note: Future emits the data only once, where as Stream emit the data continuoysly or iteratavely.</blockquote><p>This is important to have some knowledge about the stream before jumping to Bloc, as Bloc is built around the streams.</p><p>Stream uses [<strong>StreamSubscription</strong>] which listen events from this stream using the provided [onData], [onError] and [onDone] handlers.</p><pre>StreamSubscription&lt;T&gt; listen(void onData(T event)?,<br>    {Function? onError, void onDone()?, bool? cancelOnError});</pre><p>Let&#39;s look at Example: Below example will perform addition of 1 to 10 numbers</p><pre>import &#39;dart:async&#39;;<br><br>Stream&lt;int&gt; iterateSumUsingStream(int num) async* {<br>  int sum = 0;<br>  for (int i = 1; i &lt;= num; i++) {<br>    sum = sum + i;<br>    yield sum;<br>  }<br>}<br><br>void main() {<br>  var stream = iterateSumUsingStream(10);<br>  stream.listen(<br>    (data) {<br>      print(&#39;Data: $data&#39;);<br>    },<br>    onError: (err) {<br>      print(&#39;Error: ${err}&#39;);<br>    },<br>    cancelOnError: false,<br>    onDone: () {<br>      print(&#39;Done!&#39;);<br>    },<br>  );<br>}</pre><pre>Output:</pre><pre>Data: 1<br>Data: 3 <br>Data: 6 <br>Data: 10 <br>Data: 15 <br>Data: 21 <br>Data: 28 <br>Data: 36 <br>Data: 45 <br>Data: 55 <br>Done!</pre><p>As you can see, the first function <strong>onData</strong> is called 10 times, gives us the emitted value. once the for loop finished with its job then stream returns a callback in <strong>onDone</strong></p><p><strong>What is yield and *async? </strong>yield adds a value to the output stream of the surrounding async* function. It&#39;s like returning value but doesn&#39;t terminate the function.</p><p>So now, we have a fair idea about how the stream works, let&#39;s move towards <strong>Bloc usage.</strong></p><p>Bloc internally comes with good architecture which we can be used in small to large-scale projects.</p><p><strong>It has three layers in its architecture</strong></p><ol><li>Presentation Layer</li><li>Domain/Business Layer</li><li>Data Layer(It consist of Repository and Provider)</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/1*TElDAJnuT5sHtC369jyshw.png" /></figure><p>Now, we will look into one simple example which will demonstrate the above layers and their usage. Here we are going to fetch user details from API and will display them on UI.</p><h3>Data Layer:</h3><p>The data layer can be divided into two parts</p><ol><li>Data Provider</li><li>Repository</li></ol><p><strong>Data Provider:</strong></p><p>The main purpose of Provider classes is to perform <strong>CRUD</strong> operations on the network or Database. We can have methods like <strong>createUsers, readUsers, updateUsers, and deleteUsers</strong> method as part of our data layer.</p><pre>class UserDetailsProvider {<br>  final String URL =<br>      &quot;https://5f383e6541c94900169bfd42.mockapi.io/api/v1/user_details&quot;;<br><br>  <em>/// Fetch the user details from given public URL<br>  </em>Future&lt;UserDetails&gt; fetchUserDetails() async {<br>    final response = await http.get(<br>      Uri.<em>parse</em>(URL),<br>    );<br><br>    if (response.statusCode == 200) {<br>      print(&quot;Success&quot;);<br>      final resData = UserDetails.fromJson(jsonDecode(response.body));<br>      return resData;<br>    }<br>    throw Exception(&#39;Not able to fetch the data: &#39; + response.body);<br>  }<br>}</pre><p><strong>Repository:</strong></p><p>The repository contains one or more data providers, it basically communicates Between <strong>Bloc and Data Provider</strong>.</p><p>We can perform the following kind of operation</p><ol><li>Differentiate whether to call Database Provider or Network Provider.</li><li>Filtering data.</li><li>Joined results using different providers.</li></ol><pre>class UserDetailsRepository {<br>  final UserDetailsProvider _userDetailsProvider = UserDetailsProvider();<br><br>  <em>// Fetch the api response and pass it to bloc component<br>  </em>Future&lt;UserDetails&gt; fetchUserDetails() async =&gt;<br>      _userDetailsProvider.fetchUserDetails();<br>}</pre><h3><strong>Domain/Business Layer:</strong></h3><p>The Domain Layer has the responsibility to communicate between the presentation layer and data layer, It is used to respond to input from the presentation layer with new states. This layer can depend on one or more repositories to retrieve data needed to build up the application state.</p><blockquote>Bloc containes state and event where <strong>Event</strong> contains the information which passed by presentation layer to make queries to database/network operation, where as <strong>State</strong> tells us about current flow of bloc, an Event could be as Loading, Loaded, Error….</blockquote><p><strong>Event class:</strong></p><pre>@immutable<br>abstract class UserDetailsEvent {}<br><br>class UserDetailsInfo extends UserDetailsEvent {}</pre><p><strong>State class:</strong></p><pre>@immutable<br>abstract class UserDetailsState {}<br><br>class UserDetailsLoading extends UserDetailsState {<br>  @override<br>  String toString() {<br>    return &quot;UserDetailsLoading&quot;;<br>  }<br>}<br><br>class UserDetailsLoaded extends UserDetailsState {<br>  final UserDetails userDetails;<br><br>  UserDetailsLoaded(this.userDetails);<br><br>  @override<br>  String toString() {<br>    return &quot;UserDetailsLoaded&quot;;<br>  }<br>}<br><br>class UserDetailsError extends UserDetailsState {<br>  @override<br>  String toString() {<br>    return &quot;UserDetailsError&quot;;<br>  }<br>}</pre><p><strong>Bloc class:</strong></p><pre>class UserDetailsBloc extends Bloc&lt;UserDetailsEvent, UserDetailsState&gt; {<br>  final UserDetailsRepository userDetailsRepository;<br><br>  UserDetailsBloc({required this.userDetailsRepository})<br>      : super(UserDetailsLoading());<br><br>  @override<br>  Stream&lt;UserDetailsState&gt; mapEventToState(<br>    UserDetailsEvent event,<br>  ) async* {<br>    yield UserDetailsLoading();<br>    try {<br>      UserDetails userDetails = await userDetailsRepository.fetchUserDetails();<br>      yield UserDetailsLoaded(userDetails);<br>    } catch (e) {<br>      print(&quot;Exception while fetching user details: &quot; + e.toString());<br>      yield UserDetailsError();<br>    }<br>  }<br>}</pre><p>UserDetailsBloc contains the logic to trigger a different state of the bloc to the presentation layer so that it can act based on the coming state.</p><h3>Presentation Layer:</h3><p>The Presentation Layer will be responsible for showing different UI based on the coming state which will be reflected in <strong>BlocBuilder. </strong>One widget can contain multiple blocs which performed asynchronously.</p><p><strong>BlocBuilder: </strong>It must contain the required bloc and builder function, BlocBuilder handles building the widget in response to new states.</p><pre>class UserDetailsScreen extends StatefulWidget {<br>  @override<br>  _UserDetailsScreenState createState() =&gt; _UserDetailsScreenState();<br>}<br><br>class _UserDetailsScreenState extends State&lt;UserDetailsScreen&gt; {<br>  late final UserDetailsRepository _userDetailsRepository;<br>  late final UserDetailsBloc _userDetailsBloc;<br><br>  @override<br>  void initState() {<br>    _userDetailsRepository = UserDetailsRepository();<br>    _userDetailsBloc =<br>        UserDetailsBloc(userDetailsRepository: _userDetailsRepository);<br>    _userDetailsBloc.add(UserDetailsInfo());<br>    super.initState();<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(<br>        title: Text(&#39;My App&#39;),<br>      ),<br>      body: Center(<br>        child: BlocBuilder(<br>            bloc: _userDetailsBloc,<br>            builder: (BuildContext context, UserDetailsState state) {<br>              if (state is UserDetailsLoading) {<br>                return CircularProgressIndicator();<br>              }<br>              if (state is UserDetailsLoaded) {<br>                   return UserDetailsWidget(userDetails: state.userDetails);<br>              }<br>              return Text(&#39;Unable to fetch the user details!!!&#39;);<br>            }),<br>      ),<br>    );<br>  }<br>}</pre><p>As you can see UserDetailsLoading, UserDetailsLoaded and UserDetailsError are returning/rendering different widgets as per the state.</p><p><strong>UserDetailsWidget:</strong></p><pre>class UserDetailsWidget extends StatelessWidget {<br>  final UserDetails userDetails;<br><br>  const UserDetailsWidget({Key? key, required this.userDetails})<br>      : super(key: key);<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Column(<br>      mainAxisSize: MainAxisSize.min,<br>      children: [<br>        ClipRRect(<br>          borderRadius: BorderRadius.only(<br>            topLeft: Radius.circular(15),<br>            topRight: Radius.circular(15),<br>          ),<br>          child: Image.network(<br>            userDetails.image ?? &quot;&quot;,<br>            height: 250,<br>            width: double.<em>infinity</em>,<br>            fit: BoxFit.cover,<br>          ),<br>        ),<br>        SizedBox(height: 16.0,),<br>        Row(<br>          mainAxisAlignment: MainAxisAlignment.spaceAround,<br>          children: [<br>            Text(&quot;Name: ${userDetails.name ?? &quot;&quot;}&quot;),<br>            Text(&quot;Percentage: ${userDetails.winningPercentage ?? &quot;&quot;}&quot;),<br>            Text(&quot;Won: ${userDetails.won ?? &quot;&quot;}&quot;),<br>          ],<br>        )<br>      ],<br>    );<br>  }<br>}</pre><p><strong>Github Project: </strong><a href="https://github.com/jitsm555/flutter_bloc_sample">https://github.com/jitsm555/flutter_bloc_sample</a></p><p><strong>Output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*KQIKOL12ppDANCpkomlM4A.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=34c2d20cd092" width="1" height="1" alt=""><hr><p><a href="https://medium.com/flutterworld/flutter-bloc-mystery-part-1-34c2d20cd092">Flutter: Bloc Mystery | Part 1</a> was originally published in <a href="https://medium.com/flutterworld">FlutterWorld</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter: Null Safety]]></title>
            <link>https://medium.com/flutterworld/flutter-null-safety-5d20012c2441?source=rss-80fd7c1ebd73------2</link>
            <guid isPermaLink="false">https://medium.com/p/5d20012c2441</guid>
            <category><![CDATA[null-safety]]></category>
            <category><![CDATA[flutter-null-safety]]></category>
            <category><![CDATA[tech-madness]]></category>
            <category><![CDATA[dart-null-safety]]></category>
            <category><![CDATA[jitsm555]]></category>
            <dc:creator><![CDATA[Jitesh Mohite]]></dc:creator>
            <pubDate>Tue, 23 Mar 2021 17:28:35 GMT</pubDate>
            <atom:updated>2021-03-25T04:46:14.542Z</atom:updated>
            <content:encoded><![CDATA[<p>As a developer, we always struggle to handle <em>NullPointerException </em>which causes a lot of time and money while developing software. It has been referred to as a <em>billion-dollar mistake. </em>(<a href="https://en.wikipedia.org/wiki/Tony_Hoare#Apologies_and_retractions">Wiki</a>)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PNxHMRQTN34EtanR4HeHiw.png" /></figure><p>Flutter 2 supports null safety. You can now migrate your Flutter packages to use non-nullable types. Follow the below link to perform flutter migration for old projects.</p><p><a href="https://dart.dev/null-safety/migration-guide">https://dart.dev/null-safety/migration-guide</a></p><p><strong>Note:</strong> To use it it’s necessary to have your all libs updated with a null safety feature, otherwise you can’t migrate your project to Flutter 2.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F5huaMC0BfppFSe4Rad%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fbbcamerica-funny-omg-5huaMC0BfppFSe4Rad&amp;image=https%3A%2F%2Fmedia2.giphy.com%2Fmedia%2F5huaMC0BfppFSe4Rad%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/6d6bc662d2b6aa5c8f17fd5922c8b97a/href">https://medium.com/media/6d6bc662d2b6aa5c8f17fd5922c8b97a/href</a></iframe><p>Dart distinguishes between nullable and non-nullable references as a part of its type system which helps in eliminating the risk of <em>NullPointerException.</em></p><p>In Dart, all variables are non-nullable by default. We cannot assign a <em>null</em> value to a variable because it’ll throw a compilation error:</p><pre>  final String country = null; // Cannot be null.<br>  final String? country = null; // Can be null.</pre><p>Null safety is a major new productivity feature that helps you avoid null exceptions, a class of bugs that are often hard to spot. As an added bonus, this feature also enables a <strong>range of performance improvements.</strong></p><p><strong><em>— — — — — — — — — — — — — — — — — — — — — — — — — —</em></strong></p><h3>Compile Time Error For Nullable Type.</h3><p>Variables are non-nullable by default which means every variable should be assigned and cannot be null.</p><pre>void main() {<br>  String country;<br>  print(country);<br>}<br>Error: The non-nullable local variable &#39;country&#39; must be assigned before it can be used.</pre><p><strong>Values must be assigned at the time of declaration otherwise we have to mark it as nullable using ‘?’ </strong>Also, it is not possible to assign a value null to the variable, it will give an error <strong>“A country of type ‘Null’ can’t be assigned to a variable of type ‘String’.”</strong></p><pre>void main() {<br>  String country = null;<br>}</pre><p>The below code will work, as the <strong>variable country is not used</strong> before assigning a value.</p><pre>void main() {<br>  String country;<br>  country = &quot;Welcome To Flutter&quot;;<br>}</pre><p>Below code gives us an error as we are using a variable before it got assigned value, and the error which thrown <strong>“The non-nullable local variable ‘value’ must be assigned before it can be used.”</strong></p><pre>void main() {<br>  String country;<br>  print(country);<br>  country = &quot;USA&quot;;<br>}</pre><p><strong><em>— — — — — — — — — — — — — — — — — — — — — — — — — —</em></strong></p><h3>Nullable types (Use Question Mark ‘?’)</h3><p>To force variable nullable use <strong>‘?’ </strong>like below, which tells the system that it can be null, and assigned letter. This will through null exception which results in a red screen on mobile.</p><pre>void main() {<br>  String? country;<br>  print(country);<br>}<br>Output:<br>null</pre><p><strong><em>— — — — — — — — — — — — — — — — — — — — — — — — — —</em></strong></p><h3><strong>Non Nullable Type — Exclamation mark (</strong>!)</h3><p>Appending <strong>!</strong> to any variable tells the compiler that the variable is not null, and can be used safely.</p><pre>void main() {<br>  String? country = &quot;USA&quot;;<br>  String myCountry = country!; // myCountry is non-nullable; would throw an error if country is null</pre><p><strong><em>— — — — — — — — — — — — — — — — — — — — — — — — — —</em></strong></p><h3><strong>late</strong> variables</h3><p>The keyword late can be used to mark variables that will be <strong>initialized later</strong>, i.e. not when they are declared but when they are accessed. <strong>This also means that we can have non-nullable <em>instance fields</em> that are initialized later:</strong> Accessing value before it is initialized will throw a runtime error.</p><pre>void main() {<br>    late String country; // non-nullable<br>    // print(value) here would throw a runtime error<br>    country = &quot;USA&quot;;<br>}</pre><p><strong><em>— — — — — — — — — — — — — — — — — — — — — — — — — —</em></strong></p><h3>late final</h3><p>Wow!!, isn’t these amazing, Final variable can be assigned a letter.</p><p>You can declare a late final without an initializer, which is the same as having just a late variable, but it can only be assigned once.</p><pre>late final String country;<br>country = &quot;USA&quot;; <br>print(country); // Working<br>country = &quot;India&quot;;//Error: The late final local variable is already assigned.</pre><p>If the late final is declared as static, then it will be evaluated at runtime.</p><pre>class MyClass {<br>  static late final country;<br>}<br><br>void main() {<br>  MyClass.country<em> </em>= &quot;USA&quot;;<br>  MyClass.country<em> </em>= &quot;USA&quot;;<br>  print(MyClass.<em>values</em>.toString());<br>}</pre><pre>Output:<br>[VERBOSE-2:ui_dart_state.cc(186)] Unhandled Exception: LateInitializationError: Field &#39;<em>values</em>&#39; has already been initialized.</pre><p>This error will be thrown at runtime, not at the compile-time, so don&#39;t declare final late values again, this will cause a runtime error.</p><p><strong><em>— — — — — — — — — — — — — — — — — — — — — — — — — —</em></strong></p><h3><strong>Conditional operator(</strong><strong>?)</strong></h3><p>The cascade operator helps us to verify whether the given object/variable is null or not if it&#39;s null then we can use another value, it’s more like if, else</p><pre>class MyClass {<br>  String? country;<br>}<br><br>void main() {<br>   var myClass = MyClass();<br>   print(myClass.country?? &quot;Japan&quot;);<br>/// myClass.value is returning null, to avoid null exception we can /// pass placeholder value like above(&quot;Japan&quot;), this must be  <br>/// utilized whenever possible inside the code base. <br>}<br>Output: Japan</pre><p>I have tried to put everything below the class file, respectively wrote test cases for it.</p><p><strong>Example:</strong></p><pre>import &#39;package:flutter/material.dart&#39;;<br><br>class NullSafety {<br>  int? nullCheckForCountry() {<br>    String country = &quot;USA&quot;;<br>    <em>// country = null; //compilation error<br>    </em>return country != null ? country.length : null;<br>  }<br><br>  int? safeCallForCountry() {<br>    String? country;<br>    return country?.length;<br>  }<br><br>  int? nullCheckForCity() {<br>    String? city = &quot;Kolkata&quot;;<br>    city = null;<br>    return city != null ? city.length : null;<br>  }<br><br>  int? safeCallForCity() {<br>    String? city;<br>    return city?.length;<br>  }<br><br>  String? safeCallChainForValue() {<br>    Country? country = Country(City(&quot;Kolkata&quot;, &quot;003&quot;));<br>    return country.city?.code;<br>  }<br><br>  List&lt;String?&gt; safeCallUsingList() {<br>    List&lt;String?&gt; cities = [&quot;Kolkata&quot;, null, &quot;Mumbai&quot;];<br>    List&lt;String?&gt; name = [];<br>    for (int i = 0; i &lt; cities.length; i++) {<br>      String? city = cities[i];<br>      name.add(city);<br>    }<br>    return name;<br>  }<br><br>  String getDefaultValueIfObjectNull() {<br>    Country? country = Country(City(&quot;New Delhi&quot;, null));<br>    return country.city?.code ?? &quot;Not available&quot;;<br>  }<br><br>  int? notNullAssertionForException() {<br>    String? country;<br>    return country!.length;<br>  }<br>}<br><br>class Country {<br>  City? city;<br><br>  Country(City? city) {<br>    this.city = city;<br>  }<br>}<br><br>class City {<br>  String? name;<br>  String? code;<br><br>  City(String? name, String? code) {<br>    this.name = name;<br>    this.code = code;<br>  }<br>}</pre><p><strong>Class File:</strong> <a href="https://github.com/jitsm555/Null-Safety-Flutter/blob/master/lib/main.dart">https://github.com/jitsm555/Null-Safety-Flutter/blob/master/lib/main.dart</a></p><p><strong>Test File:</strong> <a href="https://github.com/jitsm555/Null-Safety-Flutter/blob/master/test/null_safety_test.dart">https://github.com/jitsm555/Null-Safety-Flutter/blob/master/test/null_safety_test.dart</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5d20012c2441" width="1" height="1" alt=""><hr><p><a href="https://medium.com/flutterworld/flutter-null-safety-5d20012c2441">Flutter: Null Safety</a> was originally published in <a href="https://medium.com/flutterworld">FlutterWorld</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter: Perform Background Job]]></title>
            <link>https://medium.com/flutterworld/flutter-perform-background-job-9bce92f0a21e?source=rss-80fd7c1ebd73------2</link>
            <guid isPermaLink="false">https://medium.com/p/9bce92f0a21e</guid>
            <category><![CDATA[backgroundworkflutter]]></category>
            <category><![CDATA[flutterbackgroundjob]]></category>
            <category><![CDATA[tech-madness]]></category>
            <category><![CDATA[flutter-background]]></category>
            <category><![CDATA[jitsm555]]></category>
            <dc:creator><![CDATA[Jitesh Mohite]]></dc:creator>
            <pubDate>Sat, 13 Feb 2021 15:25:03 GMT</pubDate>
            <atom:updated>2021-02-14T03:28:37.084Z</atom:updated>
            <content:encoded><![CDATA[<p>Every application does some kind of background work which required to be performed for data storage, API usage, hardware events many more. In this article, we will learn about scheduling background tasks in our flutter apps using one of the simplest methods.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yzRl4pnzz1CBv_wOf5iq0A.png" /></figure><p>Please find below steps to use <a href="https://pub.dev/packages/workmanager"><strong>workmanager</strong></a><strong> </strong>plugin</p><h3>1. Depend on it</h3><p>Add this to your package’s pubspec.yaml file:</p><pre>dependencies:<br>  workmanager: ^0.2.3</pre><h3>2. Install it</h3><p>You can install packages from the command line:</p><p>with Flutter:</p><pre><strong>$</strong> flutter pub get</pre><p>Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.</p><h3>3. Import it</h3><p>Now in your Dart code, you can use:</p><pre><strong>import</strong> &#39;package:workmanager/workmanager.dart&#39;;</pre><p>WorkManager comes under two parts, which run the task in the background.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FzmUy85cgghBRqxsdND%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FzmUy85cgghBRqxsdND%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FzmUy85cgghBRqxsdND%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="229" frameborder="0" scrolling="no"><a href="https://medium.com/media/092e938519fed34db1634baffb7bfcb1/href">https://medium.com/media/092e938519fed34db1634baffb7bfcb1/href</a></iframe><h3><strong>1. Delayed background work</strong></h3><p>registerOneOffTask runs the task only once with an initial delay of 10 seconds. This is useful when we need to perform any background work only once.</p><p><strong>Example:</strong></p><pre>Workmanager.<em>registerOneOffTask</em>(<br>  &quot;1&quot;,<br>  &quot;<em>registerOneOffTask</em>&quot;,<br>  initialDelay: Duration(seconds: 10),<br>);</pre><h3><strong>2. Periodic background work</strong></h3><p>This task runs periodically, Since we have not provided a frequency it will be the default 15 minutes.</p><p><strong>Example:</strong></p><pre>Workmanager.<em>registerPeriodicTask</em>(<br>  &quot;2&quot;,<br>  &quot;<em>registerPeriodicTask</em>&quot;,<br>  initialDelay: Duration(seconds: 10),<br>);</pre><p>If we provide the frequency of 1 hour then it will run background job after every one hour. Likewise, we can mention different frequencies but it should be more than 15 minutes.</p><pre>frequency: Duration(hours: 1),</pre><p>The next thing we have to do initialize is <strong>callbackDispatcher, </strong>so what is this?</p><p><strong>CallbackDispactcher</strong> is invoked inside flutter code, so to perform anything inside Flutter, we do require Flutter Engine to be available. <strong>callbackDispatcher </strong>is a dart callback function that gets called only when native code(iOS/Android) invokes any background work. Just one thing we have to remember before using it is that <strong>callbackDispatcher </strong>method must be a top-level function or a static block of code.</p><pre>Workmanager.<em>initialize</em>(<br>      callbackDispatcher, <em>// The top level function, aka callbackDispatcher<br>      </em>isInDebugMode: false <em>// This should be false<br>      </em>);</pre><p>The above code should be implemented inside<strong> main()</strong> method, for better understanding goes through the below code.</p><h3>Full Code:</h3><p>The below code runs the background job after every 15 minutes and saved the incremented value in shared preference.</p><pre>import &#39;dart:async&#39;;<br><br>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:shared_preferences/shared_preferences.dart&#39;;<br>import &#39;package:workmanager/workmanager.dart&#39;;<br><br>const String TAG = &quot;BackGround_Work&quot;;<br><br>void main() {<br>  WidgetsFlutterBinding.<em>ensureInitialized</em>();<br>  Workmanager.<em>initialize</em>(<br>      callbackDispatcher, <em>// The top level function, aka callbackDispatcher<br>      </em>isInDebugMode: false <em>// This should be false<br>      </em>);<br>  runApp(MyApp());<br>}<br><br>class MyApp extends StatelessWidget {<br>  <em>// This widget is the root of your application.<br>  </em>@override<br>  Widget build(BuildContext context) {<br>    return MaterialApp(<br>      title: &#39;BackGround Work Sample&#39;,<br>      theme: ThemeData(<br>        primarySwatch: Colors.<em>blue</em>,<br>      ),<br>      home: BackGroundWorkSample(),<br>    );<br>  }<br>}<br><br>class BackGroundWorkSample extends StatefulWidget {<br>  @override<br>  _BackGroundWorkSampleState createState() =&gt; _BackGroundWorkSampleState();<br>}<br><br>class _BackGroundWorkSampleState extends State&lt;BackGroundWorkSample&gt; {<br>  int _counterValue = 0;<br><br>  @override<br>  void initState() {<br>    <em>// TODO: implement initState<br>    </em>super.initState();<br>    <em>//This task runs periodically<br>    //It will wait at least 10 seconds before its first launch<br>    //Since we have not provided a frequency it will be the default 15 minutes<br>    </em>Workmanager.<em>registerPeriodicTask</em>(<br>      TAG,<br>      &quot;simplePeriodicTask&quot;,<br>      initialDelay: Duration(seconds: 10),<br>    );<br>    loalData();<br>  }<br><br>  void loalData() async {<br>    _counterValue =<br>        await BackGroundWork.<em>instance</em>._getBackGroundCounterValue();<br>    setState(() {});<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>        appBar: AppBar(<br>          title: Text(&#39;BackGround Work Sample&#39;),<br>        ),<br>        body: Center(<br>          child: Column(<br>            mainAxisSize: MainAxisSize.min,<br>            children: [<br>              Text(&quot;Counter Value: ${_counterValue}&quot;),<br>              RaisedButton(onPressed: () {<br>                loalData();<br>              }, child: Text(&quot;Fetch Current Counter Value&quot;),)<br>            ],<br>          ),<br>        ));<br>  }<br>}<br><br>void callbackDispatcher() {<br>  Workmanager.<em>executeTask</em>((task, inputData) async {<br>    print(TAG + &quot;callbackDispatcher&quot;);<br>    int value =<br>        await BackGroundWork.<em>instance</em>._getBackGroundCounterValue();<br>    BackGroundWork.<em>instance</em>._loadCounterValue(value + 1);<br>    return Future.value(true);<br>  });<br>}<br><br>class BackGroundWork {<br>  BackGroundWork._privateConstructor();<br><br>  static final BackGroundWork <em>_instance </em>=<br>  BackGroundWork._privateConstructor();<br><br>  static BackGroundWork get <em>instance </em>=&gt; <em>_instance</em>;<br><br>  _loadCounterValue(int value) async {<br>    SharedPreferences prefs = await SharedPreferences.<em>getInstance</em>();<br>    await prefs.setInt(&#39;BackGroundCounterValue&#39;, value);<br>  }<br><br>  Future&lt;int&gt; _getBackGroundCounterValue() async {<br>    SharedPreferences prefs = await SharedPreferences.<em>getInstance</em>();<br>    <em>//Return bool<br>    </em>int counterValue = prefs.getInt(&#39;BackGroundCounterValue&#39;) ?? 0;<br>    return counterValue;<br>  }<br>}</pre><p><strong>Output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/308/1*WAMG4KHh3e2Xu5WS3TDo2g.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9bce92f0a21e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/flutterworld/flutter-perform-background-job-9bce92f0a21e">Flutter: Perform Background Job</a> was originally published in <a href="https://medium.com/flutterworld">FlutterWorld</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter: AVATAR VIEW]]></title>
            <link>https://medium.com/flutterworld/flutter-avatar-view-75c567e47bdc?source=rss-80fd7c1ebd73------2</link>
            <guid isPermaLink="false">https://medium.com/p/75c567e47bdc</guid>
            <category><![CDATA[rectangularviewflutter]]></category>
            <category><![CDATA[tech-madness]]></category>
            <category><![CDATA[flutteravatarview]]></category>
            <category><![CDATA[avatarviewflutter]]></category>
            <category><![CDATA[circularviewflutter]]></category>
            <dc:creator><![CDATA[Jitesh Mohite]]></dc:creator>
            <pubDate>Sun, 17 Jan 2021 19:44:42 GMT</pubDate>
            <atom:updated>2021-03-13T16:31:47.375Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gWTwN2blfOS9uDWqb6yTiw.png" /></figure><p>Flutter has a <a href="https://api.flutter.dev/flutter/material/CircleAvatar-class.html">CircleAvatar</a> widget that comes with very limited functionality, to solve this I have created my own flutter lib called <a href="https://pub.dev/packages/avatar_view">avatar_view</a>. This will solve some of the common problems which we faced while development.</p><h3>AvatarView Features</h3><p>All below features will be supported for network and assets images.</p><ul><li>Circular AvatarView Without Border</li><li>Circular AvatarView With Border</li><li>Rectangular AvatarView Without Border</li><li>Rectangular AvatarView With Border</li><li>Circular/Rectangular Text Widget</li><li>Error Support Widgets.</li></ul><p>Some of the examples which describe how we can use this.</p><h4>Circular AvatarView Without Border</h4><pre>       AvatarView(<br>                  radius: 60,<br>                  borderColor: Colors.yellow,<br>                  avatarType: AvatarType.CIRCLE,<br>                  backgroundColor: Colors.red,<br>                  imagePath:<br>                  &quot;https://images.pexels.com/photos/415829/pexels-photo-415829.jpeg?cs=srgb&amp;dl=pexels-pixabay-415829.jpg&quot;,<br>                  placeHolder: Container(<br>                    child: Icon(Icons.person, size: 50,),<br>                  ),<br>                  errorWidget: Container(<br>                    child: Icon(Icons.error, size: 50,),<br>                  ),<br>                ),</pre><h4>Circular AvatarView With Border</h4><pre>       AvatarView(<br>                  radius: 60,<br>                  borderWidth: 8,<br>                  borderColor: Colors.yellow,<br>                  avatarType: AvatarType.CIRCLE,<br>                  backgroundColor: Colors.red,<br>                  imagePath:<br>                      &quot;https://images.pexels.com/photos/415829/pexels-photo-415829.jpeg?cs=srgb&amp;dl=pexels-pixabay-415829.jpg&quot;,<br>                  placeHolder: Container(<br>                    child: Icon(Icons.person, size: 50,),<br>                  ),<br>                  errorWidget: Container(<br>                    child: Icon(Icons.error, size: 50,),<br>                  ),<br>                ),</pre><h4>Rectangular AvatarView Without Border</h4><pre>      AvatarView(<br>                  radius: 60,<br>                  borderColor: Colors.grey,<br>                  avatarType: AvatarType.RECTANGLE,<br>                  backgroundColor: Colors.red,<br>                  imagePath:<br>                  &quot;https://images.pexels.com/photos/220453/pexels-photo-220453.jpeg?cs=srgb&amp;dl=pexels-pixabay-220453.jpg&quot;,<br>                  placeHolder: Container(<br>                    child: Icon(Icons.person, size: 50,),<br>                  ),<br>                  errorWidget: Container(<br>                    child: Icon(Icons.error, size: 50,),<br>                  ),<br>                ),</pre><h4>Rectangular AvatarView With Border</h4><pre>      AvatarView(<br>                  radius: 60,<br>                  borderWidth: 8,<br>                  borderColor: Colors.grey,<br>                  avatarType: AvatarType.RECTANGLE,<br>                  backgroundColor: Colors.red,<br>                  imagePath:<br>                  &quot;https://images.pexels.com/photos/220453/pexels-photo-220453.jpeg?cs=srgb&amp;dl=pexels-pixabay-220453.jpg&quot;,<br>                  placeHolder: Container(<br>                    child: Icon(Icons.person, size: 50,),<br>                  ),<br>                  errorWidget: Container(<br>                    child: Icon(Icons.error, size: 50,),<br>                  ),<br>                ),</pre><h3>Output:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*MgS4MwcWj35NzqnRs4PfIw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*BnvErPhoAVQr7_aAcl78yQ.png" /></figure><p>Please find examples repository inside below given GitHub URL, Please do star if you like the repository.</p><p>Github: <a href="https://github.com/jitsm555/flutter_avatar_view">https://github.com/jitsm555/flutter_avatar_view</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=75c567e47bdc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/flutterworld/flutter-avatar-view-75c567e47bdc">Flutter: AVATAR VIEW</a> was originally published in <a href="https://medium.com/flutterworld">FlutterWorld</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter: MVVM Architecture]]></title>
            <link>https://medium.com/flutterworld/flutter-mvvm-architecture-f8bed2521958?source=rss-80fd7c1ebd73------2</link>
            <guid isPermaLink="false">https://medium.com/p/f8bed2521958</guid>
            <category><![CDATA[jitsm555]]></category>
            <category><![CDATA[mvvm-architecture]]></category>
            <category><![CDATA[flutter-mvvm]]></category>
            <category><![CDATA[tech-madness]]></category>
            <dc:creator><![CDATA[Jitesh Mohite]]></dc:creator>
            <pubDate>Sun, 13 Dec 2020 15:11:57 GMT</pubDate>
            <atom:updated>2021-03-29T04:04:59.560Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vXhzgjHv6mrbZQzKnOCIDA.png" /></figure><p><strong>Last Updated: 28th march 2021</strong></p><p><strong>Model–View–ViewModel</strong> (<strong>MVVM</strong>) is a very established architectural pattern when it’s come to software development. <strong>What is so special about MVVM?</strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F26gR0YFZxWbnUPtMA%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Ftipsyelves-math-26gR0YFZxWbnUPtMA&amp;image=https%3A%2F%2Fmedia3.giphy.com%2Fmedia%2F26gR0YFZxWbnUPtMA%2Fgiphy.gif%3Fcid%3D790b76111582df287a9bc185917e2c204ee1c131b0301c98%26rid%3Dgiphy.gif%26ct%3Dg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/7bd966499a076557831f44b8e7235df9/href">https://medium.com/media/7bd966499a076557831f44b8e7235df9/href</a></iframe><p>We need one architecture to be placed in the application which communicates between UI and business logic. MVVM is one of them which is able to segregate business logic from UI, this looks easy job to do, but my friend believe me if you missed something in architecture or doing anything inaccurate then be ready for big trouble at a later stage of application development, and eventually you will end up having some code hack in application to do your job.</p><p>Here I am going to explain MVVM with a simple example that will give you enough knowledge to implement in your application.</p><p><strong>MVVM</strong> is useful to move business logic from view to ViewModel and Model. ViewModel is the mediator between View and Model which carry all user events and return back the result.</p><p><em>The key benefit is allowing true separation between the View and Model and the efficiency that you gain from having that. What it means in real terms is that when your model needs to change, it can be changed easily without the view needing to and vice-versa.</em></p><p>There are three key things that flow out of applying MVVM −</p><ul><li>Maintainability:- The presentation layer and the logic are loosely coupled, due to this code is easily maintainable and reusable. As the code base will increase over the course of time, this will help you to distinguish between them.</li><li>Testability:- The ViewModel is easier to unit test than code-behind or event-driven code. Thanks to separation logic MVVM have 😀</li><li>Extensibility:- This architecture gives you assurance which enables code to get extensible over the period of time. but keep in mind it’s also over job to keep component reusable.</li></ul><p>So, let&#39;s go through each component individually and try to understand the purpose. Please see the diagram while referring to the below points, you will have a clear understanding of flow.</p><h3><strong>Model</strong></h3><p>The model represents a single source of truth that carries the real-time fetch data or database-related queries.</p><p>This layer can contain business logic, code validation, etc. This layer interacts with ViewModel for local data or for real-time. Data are given in response to ViewModel.</p><h3>ViewModel</h3><p>ViewModel is the mediator between View and Model, which accept all the user events and request that to Model for data. Once the Model has data then it returns to ViewModel and then ViewModel notify that data to View.</p><p>ViewModel can be used by multiple views, which means a single ViewModel can provide data to more than one View.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/331/1*kj8QMNAvUbNdgr6o3e-C_Q.png" /></figure><h3>View</h3><p>The view is where the user is interacting with Widgets that are shown on the screen. These user events request some actions which navigate to ViewModel, and the rest of ViewModel does the job. Once ViewModel has the required data then it updates View.</p><p>Now, we will go through the example which will demonstrate MVVM architecture, for notifying data we will use the Provider state mechanism.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*RU3VqpCOEtUhRdoP1U0lrg.png" /></figure><p><strong>MediaService.dart</strong></p><pre>import &#39;dart:convert&#39;;<br>import &#39;dart:io&#39;;<br>import &#39;package:meta/meta.dart&#39;;<br><br>import &#39;package:http/http.dart&#39; as http;<br>import &#39;package:mvvm_flutter_app/model/apis/app_exception.dart&#39;;<br><br>class MediaService {<br>  final String _baseUrl = &quot;https://itunes.apple.com/search?term=&quot;;<br><br>  Future&lt;dynamic&gt; get(String url) async {<br>    dynamic responseJson;<br>    try {<br>      final response = await http.get(_baseUrl + url);<br>      responseJson = returnResponse(response);<br>    } on SocketException {<br>      throw FetchDataException(&#39;No Internet Connection&#39;);<br>    }<br>    return responseJson;<br>  }<br><br>  @visibleForTesting<br>  dynamic returnResponse(http.Response response) {<br>    switch (response.statusCode) {<br>      case 200:<br>        dynamic responseJson = jsonDecode(response.body);<br>        return responseJson;<br>      case 400:<br>        throw BadRequestException(response.body.toString());<br>      case 401:<br>      case 403:<br>        throw UnauthorisedException(response.body.toString());<br>      case 500:<br>      default:<br>        throw FetchDataException(<br>            &#39;Error occured while communication with server&#39; +<br>                &#39; with status code : ${response.statusCode}&#39;);<br>    }<br>  }<br>}</pre><p>MediaRepository.dart</p><pre>import &#39;package:mvvm_flutter_app/model/media.dart&#39;;<br>import &#39;package:mvvm_flutter_app/model/services/media_service.dart&#39;;<br><br>class MediaRepository {<br>  MediaService _mediaService = MediaService();<br><br>  Future&lt;List&lt;Media&gt;&gt; fetchMediaList(String value) async {<br>    dynamic response = await _mediaService.get(value);<br>    final jsonData = response[&#39;results&#39;] as List;<br>    List&lt;Media&gt; mediaList =<br>        jsonData.map((tagJson) =&gt; Media.fromJson(tagJson)).toList();<br>    return mediaList;<br>  }<br>}</pre><p><strong>MediaViewModel.dart</strong></p><pre>import &#39;package:flutter/cupertino.dart&#39;;<br>import &#39;package:mvvm_flutter_app/model/apis/api_response.dart&#39;;<br>import &#39;package:mvvm_flutter_app/model/media.dart&#39;;<br>import &#39;package:mvvm_flutter_app/model/media_repository.dart&#39;;<br><br>class MediaViewModel with ChangeNotifier {<br>  ApiResponse _apiResponse = ApiResponse.loading(&#39;Fetching artist data&#39;);<br><br>  Media _media;<br><br>  ApiResponse get response {<br>    return _apiResponse;<br>  }<br><br>  Media get media {<br>    return _media;<br>  }<br><br>  <em>/// Call the media service and gets the data of requested media data of<br>  /// an artist.<br>  </em>Future&lt;void&gt; fetchMediaData(String value) async {<br>    try {<br>      List&lt;Media&gt; mediaList = await MediaRepository().fetchMediaList(value);<br>      _apiResponse = ApiResponse.completed(mediaList);<br>    } catch (e) {<br>      _apiResponse = ApiResponse.error(e.toString());<br>      print(e);<br>    }<br>    notifyListeners();<br>  }<br><br>  void setSelectedMedia(Media media) {<br>    _media = media;<br>    notifyListeners();<br>  }<br>}</pre><p><strong>HomScreen.dart</strong></p><pre>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:mvvm_flutter_app/model/apis/api_response.dart&#39;;<br>import &#39;package:mvvm_flutter_app/model/media.dart&#39;;<br>import &#39;package:mvvm_flutter_app/view/widgets/player_list_widget.dart&#39;;<br>import &#39;package:mvvm_flutter_app/view/widgets/player_widget.dart&#39;;<br>import &#39;package:mvvm_flutter_app/view_model/media_view_model.dart&#39;;<br><br>import &#39;package:provider/provider.dart&#39;;<br><br>class HomeScreen extends StatefulWidget {<br>  @override<br>  _HomeScreenState createState() =&gt; _HomeScreenState();<br>}<br><br>class _HomeScreenState extends State&lt;HomeScreen&gt; {<br>  @override<br>  void initState() {<br>    <em>// TODO: implement initState<br>    </em>super.initState();<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    final _inputController = TextEditingController();<br>    ApiResponse apiResponse = Provider.<em>of</em>&lt;MediaViewModel&gt;(context).response;<br>    List&lt;Media&gt; mediaList = apiResponse.data as List&lt;Media&gt;;<br>    return Scaffold(<br>        appBar: AppBar(<br>          title: Text(&#39;Media Player&#39;),<br>        ),<br>        body: Column(<br>          children: &lt;Widget&gt;[<br>            Padding(<br>              padding: const EdgeInsets.symmetric(vertical: 10.0),<br>              child: Row(<br>                children: &lt;Widget&gt;[<br>                  Expanded(<br>                    child: Container(<br>                      margin: EdgeInsets.symmetric(horizontal: 20.0),<br>                      decoration: BoxDecoration(<br>                        color: Theme.<em>of</em>(context).accentColor.withAlpha(50),<br>                        borderRadius: BorderRadius.circular(30.0),<br>                      ),<br>                      child: TextField(<br>                          style: TextStyle(<br>                            fontSize: 15.0,<br>                            color: Colors.<em>grey</em>,<br>                          ),<br>                          controller: _inputController,<br>                          onChanged: (value) {},<br>                          onSubmitted: (value) {<br>                            if (value.isNotEmpty) {<br>                              Provider.<em>of</em>&lt;MediaViewModel&gt;(context)<br>                                  .setSelectedMedia(null);<br>                              Provider.<em>of</em>&lt;MediaViewModel&gt;(context,<br>                                      listen: false)<br>                                  .fetchMediaData(value);<br>                            }<br>                          },<br>                          decoration: InputDecoration(<br>                            border: InputBorder.<em>none</em>,<br>                            enabledBorder: InputBorder.<em>none</em>,<br>                            focusedBorder: InputBorder.<em>none</em>,<br>                            prefixIcon: Icon(<br>                              Icons.<em>search</em>,<br>                              color: Colors.<em>grey</em>,<br>                            ),<br>                            hintText: &#39;Enter Artist Name&#39;,<br>                          )),<br>                    ),<br>                  ),<br>                ],<br>              ),<br>            ),<br>            mediaList != null &amp;&amp; mediaList.length &gt; 0<br>                ? Expanded(<br>                    child: PlayerListWidget(mediaList, (Media media) {<br>                    Provider.<em>of</em>&lt;MediaViewModel&gt;(context)<br>                        .setSelectedMedia(media);<br>                  }))<br>                : Expanded(<br>                    child: Center(<br>                      child: Text(&#39;Search the song by Artist&#39;),<br>                    ),<br>                  ),<br>            if (Provider.<em>of</em>&lt;MediaViewModel&gt;(context).media != null)<br>              Align(<br>                  alignment: Alignment.<em>bottomCenter</em>,<br>                  child: PlayerWidget(<br>                    function: () {<br>                      setState(() {});<br>                    },<br>                  )),<br>          ],<br>        ));<br>  }<br>}</pre><p>Full Repository code available here</p><p>MVVM is heavily used nowadays as it supports an event-driven approach, which goes hand in hand as a lot of flutter components are performed based on events.</p><p>Full Repository code available here</p><p><a href="https://github.com/jitsm555/Flutter-MVVM">https://github.com/jitsm555/Flutter-MVVM</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f8bed2521958" width="1" height="1" alt=""><hr><p><a href="https://medium.com/flutterworld/flutter-mvvm-architecture-f8bed2521958">Flutter: MVVM Architecture</a> was originally published in <a href="https://medium.com/flutterworld">FlutterWorld</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter Obfuscation And Build Optimization]]></title>
            <link>https://medium.com/flutterworld/flutter-obfuscation-and-build-optimization-69ff5a338fdb?source=rss-80fd7c1ebd73------2</link>
            <guid isPermaLink="false">https://medium.com/p/69ff5a338fdb</guid>
            <category><![CDATA[flutter-app-size]]></category>
            <category><![CDATA[jitsm555]]></category>
            <category><![CDATA[flutter-obfuscation]]></category>
            <category><![CDATA[flutter-apk]]></category>
            <category><![CDATA[tech-madness]]></category>
            <dc:creator><![CDATA[Jitesh Mohite]]></dc:creator>
            <pubDate>Wed, 09 Dec 2020 18:28:23 GMT</pubDate>
            <atom:updated>2020-12-09T18:28:23.508Z</atom:updated>
            <content:encoded><![CDATA[<p>Once we are done with the development of the app somethings are really important like code security, app size, and obfuscation. This blog will explain how you can obfuscate the application in flutter? and how the app size can be reduced in simple steps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mcI2gdEl6ZKoF7HvEPbZ8g.png" /></figure><p>In software development, obfuscation is the deliberate act of creating source or machine code that is difficult for humans to understand. This is done to deter reverse engineering which provides code in place and getting leak anywhere.</p><p>There are two ways to create a build and upload it to store</p><ol><li>App Bundle</li><li>Apk</li></ol><p>You need to run the below commands as per your need, everyone has their own purpose.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FAWv3UAFkgz39u%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fhoppip-how-i-met-your-mother-barney-stinson-AWv3UAFkgz39u&amp;image=https%3A%2F%2Fmedia1.giphy.com%2Fmedia%2FAWv3UAFkgz39u%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="317" frameborder="0" scrolling="no"><a href="https://medium.com/media/bef4eaf1b84826f1521fb74c46ea4171/href">https://medium.com/media/bef4eaf1b84826f1521fb74c46ea4171/href</a></iframe><p><strong>For AppBundle:</strong></p><p>Without splitting:</p><pre>flutter build appbundle --obfuscate --split-debug-info=/&lt;directory&gt;</pre><p>Splitting:</p><pre>flutter build appbundle --target-platform android-arm,android-arm64,android-x64 --obfuscate --split-debug-info=/&lt;directory&gt;</pre><p><strong>For APK:</strong></p><p>Without splitting:</p><pre>flutter build apk --obfuscate --split-debug-info=/&lt;directory&gt;</pre><p>Splitting:</p><pre>flutter build apk --target-platform android-arm,android-arm64,android-x64 --split-per-abi --obfuscate --split-debug-info=/&lt;directory&gt;</pre><p>The /&lt;directory&gt; can be replaced with the relative path of the project or exact location.</p><p>Ex:</p><ol><li>./ProjectFolderName/debug(It will create <strong>ProjectFolderName</strong> folder inside your project directory)</li><li>/Users/apple/Desktop/items/debug (It will be specific path of folder )</li></ol><p><strong><em>Note:</em></strong><em> Works only for Flutter version v1.16.2 or higher.</em></p><blockquote>By default, fat apk contains arm v7, arm v8 and x64 which increases apk size, which you don’t want to. So, when you split it, you have separate binaries that you can upload to the store and thus reducing the size of the apk that a user would need to download.</blockquote><p>Few questions which you might have after reading the above things are explained via the below questions which are taken from flutter <a href="https://flutter.dev/docs/deployment/android#what-is-a-fat-apk">docs</a></p><h3>When should I build app bundles versus APKs?</h3><p>The Google Play Store recommends that you deploy app bundles over APKs because they allow more efficient delivery of the application to your users. However, if you’re distributing your application by means other than the Play Store, an APK may be your only option.</p><h3>What is fat APK?</h3><p>A <a href="https://en.wikipedia.org/wiki/Fat_binary">fat APK</a> is a single APK that contains binaries for multiple ABIs embedded within it. This has the benefit that the single APK runs on multiple architectures and thus has wider compatibility, but it has the drawback that its file size is much larger, causing users to download and store more bytes when installing your application. When building APKs instead of app bundles, it is strongly recommended to build split APKs, as described in <a href="https://flutter.dev/docs/deployment/android#build-an-apk">build an APK</a> using the --split-per-abi flag.</p><h3>What are the supported target architectures?</h3><p>When building your application in release mode, Flutter apps can be compiled for <a href="https://developer.android.com/ndk/guides/abis#v7a">armeabi-v7a</a> (ARM 32-bit), <a href="https://developer.android.com/ndk/guides/abis#arm64-v8a">arm64-v8a</a> (ARM 64-bit), and <a href="https://developer.android.com/ndk/guides/abis#86-64">x86–64</a> (x86 64-bit). Flutter does not currently support building for x86 Android (See <a href="https://github.com/flutter/flutter/issues/9253">Issue 9253</a>).</p><h3>Reducing app size</h3><p>Developers are concerned with the size of their compiled app. As the APK, app bundle, or IPA version of a Flutter app is self-contained and holds all the code and assets needed to run the app, its size can be a concern. The larger an app, the more space it requires on a device, the longer it takes to download, and it may break the limit of useful features like Android instant apps.</p><p>When building a release version of your app, consider using the --split-debug-info tag. This tag can dramatically reduce code size.</p><p>Some of the other things you can do to make your app smaller are:</p><ul><li>Remove unused resources</li><li>Minimize resource imported from libraries</li><li>Compress PNG and JPEG files</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=69ff5a338fdb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/flutterworld/flutter-obfuscation-and-build-optimization-69ff5a338fdb">Flutter Obfuscation And Build Optimization</a> was originally published in <a href="https://medium.com/flutterworld">FlutterWorld</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter: Run function repeatedly using CRON]]></title>
            <link>https://medium.com/flutterworld/flutter-run-function-repeatedly-using-cron-4aa030eda332?source=rss-80fd7c1ebd73------2</link>
            <guid isPermaLink="false">https://medium.com/p/4aa030eda332</guid>
            <category><![CDATA[timervscron]]></category>
            <category><![CDATA[cron]]></category>
            <category><![CDATA[cronjob]]></category>
            <category><![CDATA[functionusingcron]]></category>
            <category><![CDATA[tech-madness]]></category>
            <dc:creator><![CDATA[Jitesh Mohite]]></dc:creator>
            <pubDate>Sat, 31 Oct 2020 12:12:02 GMT</pubDate>
            <atom:updated>2020-10-31T12:12:02.091Z</atom:updated>
            <content:encoded><![CDATA[<p>There are times when you want to run some tasks periodically, and to do that we have two things in a flutter.</p><ol><li><strong>Timer</strong></li><li><strong>Cron</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IDKnbj6DbyaPUZbXL7UVhg.png" /></figure><p><strong>Timer:</strong> It’s running a task on given specific time intervals whether it is seconds, minutes, hours, etc…</p><pre>import &#39;dart:async&#39;;<br><br>void main() {<br>    const oneSec = const Duration(seconds: 1);<br><br>    Timer.periodic(oneSec, (Timer timer) {<br>        print(&quot;Repeat task every one second&quot;);  // This statement will be printed after every one second<br>    }); <br>} </pre><p><a href="https://pub.dev/packages/cron"><strong>Cron</strong></a><strong> </strong>lib which will be running periodically, but there is a difference between Timer and Cron. Cron used for more complex time intervals.</p><p><strong>Example:</strong> If a task needs to be run at a specific time of an hour or a day or month then this is very useful. It is also called a time-based job scheduler.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F110MZt5qYxdrH2%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fdrake-and-josh-bell-parker-110MZt5qYxdrH2&amp;image=https%3A%2F%2Fmedia2.giphy.com%2Fmedia%2F110MZt5qYxdrH2%2Fgiphy.gif%3Fcid%3D790b7611c8c7babb9c1737f689e01bbed2710a64ddb82d64%26rid%3Dgiphy.gif%26ct%3Dg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="206" frameborder="0" scrolling="no"><a href="https://medium.com/media/d3189b92d554a2aad592588bb71a091f/href">https://medium.com/media/d3189b92d554a2aad592588bb71a091f/href</a></iframe><p>Let’s see the diagram for a better understanding. The below diagram has an asterisk(*) that represents a number that appears in a specific position.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Ug1MglUj_r0o_aYe.png" /></figure><p>Cron has a daemon thread that runs in the background all the time and this thread is responsible for scheduling background work.</p><pre>import &#39;package:cron/cron.dart&#39;;</pre><pre>main() {<br>  var cron = new Cron();<br>  cron.schedule(new Schedule.parse(&#39;*/3 * * * *&#39;), () async {<br>    print(&#39;every three minutes&#39;);<br>  });<br>  cron.schedule(new Schedule.parse(&#39;8-11 * * * *&#39;), () async {<br>    print(&#39;between every 8 and 11 minutes&#39;);<br>  });<br>}</pre><p>The above examples are taken from the repository which pretty well explains that the first <strong>‘*’ represents minutes,</strong> similar for the hour and so on as shown in the diagram.</p><p>Another example of the <strong>hour</strong> would be Schedule.parse(* 1,2,3,4 * * *), This schedule will run every minute every day during the hours of 1 AM, 2 AM, 3 AM, and 4 AM.</p><p>“*” This represents all possible numbers for that position.</p><h4>Examples:</h4><p>Schedule.parse(* * * * *): This will run the job each minute till it gets to stop.</p><p>Schedule.parse(0 * * * *) : This Cron job will run at minute zero, every hour (i.e. an hourly Cron job):</p><p>15 * * * * : This is also an minutes Cron job but runs at minute 15 (i.e. 00:15, 01:15, 02:15 etc.):</p><p>30 2 * * * [command]This will run once a day, at 2:30 am.</p><p>0 0 2 * * [command]This will run once a month, on the second day of the month at midnight (i.e. November 5th, 12:00am, December 5th, 12:00am, etc.):</p><p>0 * * * 1 [command]This will run on Mondays, every hour (i.e. 24 times in one day, but only on Mondays):</p><p>0,10,20 * * * * [command]You can use multiple intervals separated by commas. This will run three times every hour, <strong>at minutes 0, 10, and 20:</strong></p><p>*/5 * * * * [command]A division operator is also used. This will run 12 times per hour, i.e. every 5 minutes:</p><p>0 5-10 * * * [command]Dash can be used to specify a range. This will run once every hour between 5:00 am and 10:00 am:</p><p><strong>Few Examples where CRON job can be used</strong></p><ul><li>You can used it for auto log out which will logout user after user after specific intervals.</li><li>Erase cache data after specific intervals.</li><li>You can even perform something as simple as fetching your most recent data, after specific interval or given time.</li></ul><p>for more reference <a href="https://code.tutsplus.com/tutorials/scheduling-tasks-with-cron-jobs--net-8800">https://code.tutsplus.com/tutorials/scheduling-tasks-with-cron-jobs--net-8800</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4aa030eda332" width="1" height="1" alt=""><hr><p><a href="https://medium.com/flutterworld/flutter-run-function-repeatedly-using-cron-4aa030eda332">Flutter: Run function repeatedly using CRON</a> was originally published in <a href="https://medium.com/flutterworld">FlutterWorld</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter: How to scroll to a specific position in ListView?]]></title>
            <link>https://medium.com/flutterworld/flutter-how-to-scroll-to-a-specific-position-in-listview-9ff9333ed4e?source=rss-80fd7c1ebd73------2</link>
            <guid isPermaLink="false">https://medium.com/p/9ff9333ed4e</guid>
            <category><![CDATA[listviewscrollflutter]]></category>
            <category><![CDATA[listviewscrolling]]></category>
            <category><![CDATA[flutter-world]]></category>
            <category><![CDATA[scrolltopositioninflutter]]></category>
            <category><![CDATA[tech-madness]]></category>
            <dc:creator><![CDATA[Jitesh Mohite]]></dc:creator>
            <pubDate>Sun, 04 Oct 2020 06:43:52 GMT</pubDate>
            <atom:updated>2020-10-04T06:43:52.378Z</atom:updated>
            <content:encoded><![CDATA[<p>There is always a problem with scrolling in ListView inside Flutter, so here I am coming with an example where we can scroll to a specific index of ListView.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5D73f5rhYG-IcbHqsWuYnw.png" /></figure><p>Here we are using scroll_to_index dependency which solves our equation of scrolling easily. but first, we need to understand <strong>What </strong><strong>ScrollController do?</strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Fl41YhzppzFo06iuly%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fwayward-pines-fox-wayward-pines-l41YhzppzFo06iuly&amp;image=https%3A%2F%2Fmedia1.giphy.com%2Fmedia%2Fl41YhzppzFo06iuly%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/75221eb04586f51304c3887d4290bcde/href">https://medium.com/media/75221eb04586f51304c3887d4290bcde/href</a></iframe><p>Looks Amazing Right :) As it is not easy in a flutter.</p><p>ScrollController <em>Controls a scrollable widget. </em>Scroll controllers are typically stored as member variables in [State]objects and are reused in each [State.build]. A single scroll controller can be used to control multiple scrollable widgets, but some operations, such as reading the scroll [offset], require the controller to be used with a single scrollable widget. A scroll controller creates a [ScrollPosition] to manage the state-specific to an individual [Scrollable] widget. To use a custom [ScrollPosition], subclass [ScrollController] and override [createScrollPosition]. A [ScrollController] is a [Listenable]. It notifies its listeners whenever any of the attached [ScrollPosition]s notify _their_ listeners (i.e. whenever any of the scroll). It does not notify its listeners when the list of attached [ScrollPosition]s changes. Typically used with [ListView], [GridView], [CustomScrollView].</p><p>AutoScrollController extends ScrollController which used in the below sample which contains the additional logic of scrolling. It’s internally calculated offset value and performs scrolling till the given index.</p><p><strong>Use Dependency:</strong></p><pre>dependencies:<br>    scroll_to_index: ^1.0.6</pre><p><strong>Example: </strong>Generate the list of 20 items and scroll to the sixth position of Listview on click of Fab Button</p><p><strong>Code Snippet:</strong></p><pre><strong>import &#39;package:flutter/material.dart&#39;</strong>;<br><strong>import &#39;package:scroll_to_index/scroll_to_index.dart&#39;</strong>;<br><br><strong>void </strong>main() =&gt; runApp(MyApp());<br><br><strong>class </strong>MyApp <strong>extends </strong>StatelessWidget {<br>  <em>// This widget is the root of your application.<br>  </em>@override<br>  Widget build(BuildContext context) {<br>    <strong>return </strong>MaterialApp(<br>      title: <strong>&#39;Scroll To Index Demo&#39;</strong>,<br>      theme: ThemeData(<br>        primarySwatch: Colors.<em>blue</em>,<br>      ),<br>      home: MyHomePage(title: <strong>&#39;Scroll To Index Demo&#39;</strong>),<br>    );<br>  }<br>}<br><br><strong>class </strong>MyHomePage <strong>extends </strong>StatefulWidget {<br>  MyHomePage({Key key, <strong>this</strong>.<strong>title</strong>}) : <strong>super</strong>(key: key);<br><br>  <strong>final </strong>String <strong>title</strong>;<br><br>  @override<br>  _MyHomePageState createState() =&gt; _MyHomePageState();<br>}<br><br><strong>class </strong>_MyHomePageState <strong>extends </strong>State&lt;MyHomePage&gt; {<br>  <strong>final scrollDirection </strong>= Axis.<strong>vertical</strong>;<br><br>  AutoScrollController <strong>controller</strong>;<br>  List&lt;List&lt;int&gt;&gt; <strong>randomList</strong>;<br><br>  @override<br>  <strong>void </strong>initState() {<br>    <strong>super</strong>.initState();<br>    <strong>controller </strong>= AutoScrollController(<br>        viewportBoundaryGetter: () =&gt;<br>            Rect.fromLTRB(0, 0, 0, MediaQuery.<em>of</em>(<strong>context</strong>).<strong>padding</strong>.<strong>bottom</strong>),<br>        axis: <strong>scrollDirection</strong>);<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    <strong>return </strong>Scaffold(<br>      appBar: AppBar(<br>        title: Text(<strong>widget</strong>.<strong>title</strong>),<br>      ),<br>      body: ListView(<br>        scrollDirection: <strong>scrollDirection</strong>,<br>        controller: <strong>controller</strong>,<br>        children: &lt;Widget&gt;[<br>          ...List.generate(20, (index) {<br>            <strong>return </strong>AutoScrollTag(<br>              key: ValueKey(index),<br>              controller: <strong>controller</strong>,<br>              index: index,<br>              child: Container(<br>                height: 100,<br>                color: Colors.<em>red</em>,<br>                margin: EdgeInsets.all(10),<br>                child: Center(child: Text(<strong>&#39;index: </strong>$index<strong>&#39;</strong>)),<br>              ),<br>              highlightColor: Colors.<em>black</em>.withOpacity(0.1),<br>            );<br>          }),<br>        ],<br>      ),<br>      floatingActionButton: FloatingActionButton(<br>        onPressed: _scrollToIndex,<br>        tooltip: <strong>&#39;Increment&#39;</strong>,<br>        child: Icon(Icons.<em>add</em>),<br>      ),<br>    );<br>  }<br><br>  Future _scrollToIndex() <strong>async </strong>{<br>    <strong>await controller</strong>.scrollToIndex(6, preferPosition: AutoScrollPosition.<strong>begin</strong>);<br>  }<br>}</pre><p><strong>Output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*moyGrovMLbPksxv7tF-LYQ.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9ff9333ed4e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/flutterworld/flutter-how-to-scroll-to-a-specific-position-in-listview-9ff9333ed4e">Flutter: How to scroll to a specific position in ListView?</a> was originally published in <a href="https://medium.com/flutterworld">FlutterWorld</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>