<?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 Muhammad Mashood Siddiquie on Medium]]></title>
        <description><![CDATA[Stories by Muhammad Mashood Siddiquie on Medium]]></description>
        <link>https://medium.com/@mashoodsidd97?source=rss-5b67e4c2ebd6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*N0t6Co1bkQhlRe5hTC5e9Q.jpeg</url>
            <title>Stories by Muhammad Mashood Siddiquie on Medium</title>
            <link>https://medium.com/@mashoodsidd97?source=rss-5b67e4c2ebd6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 07:26:23 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mashoodsidd97/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 + ServerPod = Fullstack Flutter Developer‍]]></title>
            <link>https://medium.com/@mashoodsidd97/flutter-serverpod-fullstack-flutter-developer-1fc519f6d5c4?source=rss-5b67e4c2ebd6------2</link>
            <guid isPermaLink="false">https://medium.com/p/1fc519f6d5c4</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[serverpod]]></category>
            <category><![CDATA[flutter-backend]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Muhammad Mashood Siddiquie]]></dc:creator>
            <pubDate>Wed, 08 May 2024 17:30:37 GMT</pubDate>
            <atom:updated>2024-05-08T17:30:37.274Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi Guys, Today I am back with another hot topic going on in the market,<br>Serverpod i.e. backend with flutter. How it’s supposed to be so cool writing the code in the dart for your backend and frontend, Damn Writing a single model class for the server-side can be used the same in your Flutter frontend app. TBH It’s an amazing journey using Dart with Flutter for creating cross-platform apps but now we can proudly say we are a “<strong>FULL STACK DEVELOPER</strong>” Thanks to the ServerPod.</p><p>So without wasting time, Let’s see how to become a Flutter developer to a Full stack Flutter developer. I will be covering just the basic understanding and simple Crud operations using ServerPod with Flutter apps.</p><h3>Project Setup:</h3><p>Some Pre-requisite we need to have:</p><ol><li>Docker Desktop application</li><li>If you’re on Mac install <a href="https://eggerapps.at/postico2/"><strong>Postico 2</strong></a> for PostgreSQL if you’re on Windows then Install <a href="https://www.beekeeperstudio.io/"><strong>Beekeeper Studio</strong></a><strong>.</strong></li></ol><p>Now First we need to globally activate the server pod CLI to do that open Terminal on Mac or cmd on Windows and run the below command:</p><pre>dart pub global activate serverpod_cli</pre><p>Once this is done, Check the version of Serverpod using the below command:</p><pre>serverpod version</pre><blockquote><strong>NOTE: At the time I’m writing this article I am using ServerPod version 1.2.6, So you might be getting a different version at the time you might be reading this article.</strong></blockquote><p>Since we are done with the initial setup of server pod CLI and all other stuff that is required. So let’s begin with the project setup and how things work there.</p><p>To Create a server pod project just use the below command on the terminal:</p><pre>serverpod create article_app</pre><p>Once we press enter we might see three different folders below:<br>1. article_app_server<br>2. article_app_client<br>3. article_app_flutter</p><p>As the name suggests, article_app_server will be the one we will be using for backend purposes, article_app_flutter will be serving as a frontend and article_app_client will serve the communication with the server.</p><p>Congratulations you’ve created the first server pod project successfully.</p><h3><strong>DEVELOPMENT</strong></h3><p>Now let’s open the article_app_server on VS code or Android Studio or whatever IDE you prefer to use for Flutter. I’ll be using VS Code 👨‍💻 .</p><p>Let’s understand the important files and folders we will be using for our article app:</p><ol><li>lib/src/endpoints: This is where we will be creating our endpoints for API purposes e.g we are creating an article app, and We need an endpoint for the article so we will create a new class inside the folder with the name: article_endpoint.dart.</li><li>lib/src/models: In this directory, we will be creating our custom models, Remember to follow the same pattern file name as described for the example app i.e. example.spy.yaml so for us we will be using article.spy.yaml as our file name.</li><li>Config: This is the main folder where we have each deployment target for our backend i.e. development, staging, production, and passwords for DB as well.</li><li>The other folders don’t necessary to be changed or do anything as some of them are auto-generated files which we will be generating in a while.</li></ol><p>Now Let’s begin with our endpoint first go to the lib/src/endpoints folder and create a new file inside it with the name: <strong>article_endpoint.dart</strong></p><p>Now Let&#39;s create a class inside it with below code:</p><pre>class ArticleEndPoint extends Endpoint {}</pre><p>Since we are creating an endpoint for our app we extend it with an endpoint so the server pod may know about the new endpoint for our API.</p><p>Now before writing code inside this class, First let’s create how our article might look like by creating a model class, In previous releases of server pod there used to be a protocol folder where we define our model class like abc_class.yaml since it’s a yaml file so we need to have a proper indent in it. Since I am using server pod version 1.2.6, so there have been some changes to it, now the protocols are auto-generated inside the lib/generated folder and a new model folder has been added to create our custom class with yaml format. Too much theory let’s get back to a practical example:</p><p>Let’s create a file inside lib/models and name it as <strong>article_model.spy.yaml<br></strong>and copy/paste the code below in this file:</p><pre>class: ArticleModel<br>table: article_tbl<br><br><br>fields:<br>  title: String<br>  content: String<br>  publishedOn: DateTime<br>  isPrime: bool</pre><p>Now let’s understand the above properties:<br>1. class: Its a name same as we provide when creating a class in dart.</p><p>2. table: This will be used as the table name in our database.<br>3. fields: This is where define our properties of model class and their types we can also pass the custom objects here as well.</p><p>Once we are done with this, we need to run the below commands so Serverpod can generate the files related to protocols and models to be used and other operations like insert, delete, update, get, and other database features like where clause in methods, etc. So let’s generate it with below command:</p><pre>serverpod generate </pre><p>Let me share a hint with you If you are in a development phase and you don’t want to run this command again and again on the terminal instead you want to list to changes and auto-run the command to generate files just use the below command:</p><pre>serverpod generate --watch</pre><p>Cool Now you won’t be triggering the terminal again to write this command, Pretty interesting.</p><p>Now let’s move forward to the endpoints folder and <strong>article_endpoint.dart </strong>file:</p><p>We already have created a class that extends the endpoint so now let’s write a crud operation for our article app:</p><p>To fetch articles, copy and paste the below code inside the class:</p><pre>class ArkiToolEndPoint extends Endpoint {<br>  //Fetch articles from DB<br><br>//DB is the repository auto created by the serverpod<br>  Future&lt;List&lt;Article&gt;&gt; fetchArticles(Session session,<br>      {String? searchQuery}) async {<br>    return await Article.db.find(<br>      session,<br>      where: (t) =&gt;<br>          searchQuery != null ? t.title.like(searchQuery) : Constant.bool(true),<br>    );<br>  }<br><br>}</pre><p>Let’s understand the important part here:<br>Always use Session which is provided by the server pod as our first positioned parameter and after that, we can define named parameters like if we want to get some params from our flutter app.</p><p>Simply, we define a method fetchArticles which returns us a future of a list of articles and it has one positioned parameter session which is always required in each method we create in our endpoint class. The other one I’ve passed is the named nullable parameter for a search query to filter the list. In our function body, we are awaiting the response for the response from our Articles -&gt; db -&gt; which will trigger our “<strong>article_tbl</strong>” we created above in <strong>models/article_model.spy.yaml</strong> folder. Now As per our code, we simply call go to the DB, and find all the articles from there, If the search query != null then we apply like operator which is the same as the SQL query so we can get filtered records as per our search, otherwise we passed true which means return all the articles from “article_tbl”.</p><p>Now let’s define all the other methods for adding, updating, and deleting an article inside our <strong>article_endpoint.dart </strong>class:</p><pre><br><br>  // Add Article to DB<br>  Future&lt;bool&gt; addArticle(Session session, Article article) async {<br>    await Article.db.insertRow(session, article);<br>    return true;<br>  }<br><br>  // Update Article<br><br>  Future&lt;bool&gt; updateArticle(Session session, Article article) async {<br>    await Article.db.updateRow(session, article);<br>    return true;<br>  }<br>// Delete Article<br>  Future&lt;bool&gt; deleteArticle(Session session, int id) async {<br>    await Article.db.deleteWhere(session, where: (t) =&gt; t.id.equals(id));<br>    return true;<br>  }</pre><p>Now in each method, we can see:</p><ol><li>In the add article: we simply insert a row that takes our current session object as the first parameter and the other object that we will be passing in it for adding a new record and we directly return a true as a bool there.</li><li>In the updated article: we simply update a row that takes our current session object as the first parameter and the other object that we will be passing in it for updating a record and we directly return a true as a bool there.</li><li>In the delete article: we simply delete a row that takes our current session object as the first parameter and the int id that we will be passing in it and we directly return a true as a bool there.</li></ol><p>Now Since we are done with our backend code for the articles app. <br>Let’s open the terminal on vs code/android studio and run the following commands in order:</p><pre>1. docker-compose up --build --detach<br>2. serverpod create-migration<br>3. dart run bin/main.dart --apply-migrations</pre><p>This will create migrations so we can check them in postico or beekeeper studio.<br>Once done let’s begin with our frontend flutter app integration with backend.</p><h3><strong>FRONTEND APP</strong></h3><p>Let’s begin with how we will be implementing these backend endpoints to our Flutter application.</p><p>So without wasting time let’s open a new VS code/Android studio instance and then go to our project director and open the “<strong>article_app_flutter</strong>” project.<br>By default, you will see some code like the below inside main.dart file:</p><pre>import &#39;package:demopod_client/demopod_client.dart&#39;;<br>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:serverpod_flutter/serverpod_flutter.dart&#39;;<br><br>// Sets up a singleton client object that can be used to talk to the server from<br>// anywhere in our app. The client is generated from your server code.<br>// The client is set up to connect to a Serverpod running on a local server on<br>// the default port. You will need to modify this to connect to staging or<br>// production servers.<br>var client = Client(&#39;http://$localhost:8080/&#39;)<br>  ..connectivityMonitor = FlutterConnectivityMonitor();<br><br>void main() {<br>  runApp(const MyApp());<br>}<br><br>class MyApp extends StatelessWidget {<br>  const MyApp({super.key});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return MaterialApp(<br>      title: &#39;Serverpod Demo&#39;,<br>      theme: ThemeData(<br>        primarySwatch: Colors.blue,<br>      ),<br>      home: const MyHomePage(title: &#39;Serverpod Example&#39;),<br>    );<br>  }<br>}<br><br>class MyHomePage extends StatefulWidget {<br>  const MyHomePage({super.key, required this.title});<br><br>  final String title;<br><br>  @override<br>  MyHomePageState createState() =&gt; MyHomePageState();<br>}<br><br>class MyHomePageState extends State&lt;MyHomePage&gt; {<br>  // These fields hold the last result or error message that we&#39;ve received from<br>  // the server or null if no result exists yet.<br>  String? _resultMessage;<br>  String? _errorMessage;<br><br>  final _textEditingController = TextEditingController();<br><br>  // Calls the `hello` method of the `example` endpoint. Will set either the<br>  // `_resultMessage` or `_errorMessage` field, depending on if the call<br>  // is successful.<br>  void _callHello() async {<br>    try {<br>      <br>      final result = await client.example.hello(_textEditingController.text);<br>      setState(() {<br>        _errorMessage = null;<br>        _resultMessage = result;<br>      });<br>    } catch (e) {<br>      setState(() {<br>        _errorMessage = &#39;$e&#39;;<br>      });<br>    }<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(<br>        title: Text(widget.title),<br>      ),<br>      body: Padding(<br>        padding: const EdgeInsets.all(16),<br>        child: Column(<br>          children: [<br>            Padding(<br>              padding: const EdgeInsets.only(bottom: 16.0),<br>              child: TextField(<br>                controller: _textEditingController,<br>                decoration: const InputDecoration(<br>                  hintText: &#39;Enter your name&#39;,<br>                ),<br>              ),<br>            ),<br>            Padding(<br>              padding: const EdgeInsets.only(bottom: 16.0),<br>              child: ElevatedButton(<br>                onPressed: _callHello,<br>                child: const Text(&#39;Send to Server&#39;),<br>              ),<br>            ),<br>            _ResultDisplay(<br>              resultMessage: _resultMessage,<br>              errorMessage: _errorMessage,<br>            ),<br>          ],<br>        ),<br>      ),<br>    );<br>  }<br>}<br><br>// _ResultDisplays shows the result of the call. Either the returned result from<br>// the `example.hello` endpoint method or an error message.<br>class _ResultDisplay extends StatelessWidget {<br>  final String? resultMessage;<br>  final String? errorMessage;<br><br>  const _ResultDisplay({<br>    this.resultMessage,<br>    this.errorMessage,<br>  });<br><br>  @override<br>  Widget build(BuildContext context) {<br>    String text;<br>    Color backgroundColor;<br>    if (errorMessage != null) {<br>      backgroundColor = Colors.red[300]!;<br>      text = errorMessage!;<br>    } else if (resultMessage != null) {<br>      backgroundColor = Colors.green[300]!;<br>      text = resultMessage!;<br>    } else {<br>      backgroundColor = Colors.grey[300]!;<br>      text = &#39;No server response yet.&#39;;<br>    }<br><br>    return Container(<br>      height: 50,<br>      color: backgroundColor,<br>      child: Center(<br>        child: Text(text),<br>      ),<br>    );<br>  }<br>}</pre><p>It’s a default template and code that’s provided by the Serverpod team for our Flutter app. It creates a client connection at the top so we can communicate with our backend API. So without wasting time let’s replace this whole class with below code:</p><pre>import &#39;package:arkitool_app_client/arkitool_app_client.dart&#39;;<br>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:serverpod_flutter/serverpod_flutter.dart&#39;;<br><br>// Sets up a singleton client object that can be used to talk to the server from<br>// anywhere in our app. The client is generated from your server code.<br>// The client is set up to connect to a Serverpod running on a local server on<br>// the default port. You will need to modify this to connect to staging or<br>// production servers.<br>var client = Client(&#39;http://$localhost:8080/&#39;)<br>  ..connectivityMonitor = FlutterConnectivityMonitor();<br><br>void main() {<br>  runApp(const MyApp());<br>}<br><br>class MyApp extends StatelessWidget {<br>  const MyApp({super.key});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return MaterialApp(<br>      title: &#39;Serverpod Demo&#39;,<br>      theme: ThemeData(<br>        primarySwatch: Colors.blue,<br>      ),<br>      home: const MyHomePage(title: &#39;Serverpod Example&#39;),<br>    );<br>  }<br>}<br><br>class MyHomePage extends StatefulWidget {<br>  const MyHomePage({super.key, required this.title});<br><br>  final String title;<br><br>  @override<br>  MyHomePageState createState() =&gt; MyHomePageState();<br>}<br><br>class MyHomePageState extends State&lt;MyHomePage&gt; {<br>  // These fields hold the last result or error message that we&#39;ve received from<br>  // the server or null if no result exists yet.<br>  String? _resultMessage;<br>  String? _errorMessage;<br><br>  final _textEditingController = TextEditingController();<br><br>  // Calls the `hello` method of the `example` endpoint. Will set either the<br>  // `_resultMessage` or `_errorMessage` field, depending on if the call<br>  // is successful.<br>  void _callHello() async {<br>    try {<br>      final result = await client.example.hello(_textEditingController.text);<br>      setState(() {<br>        _errorMessage = null;<br>        _resultMessage = result;<br>      });<br>    } catch (e) {<br>      setState(() {<br>        _errorMessage = &#39;$e&#39;;<br>      });<br>    }<br>  }<br><br>  addArticle() async {<br>    var article = Article(<br>        title: &quot;ServerPod + Flutter&quot;,<br>        content: &quot;Backend integration with Flutter using ServerPod&quot;,<br>        publishedOn: DateTime.now(),<br>        isPrime: true);<br><br>    try {<br>      bool isAdded = await client.arkiToolEndPoint.addArticle(article);<br>      print(isAdded);<br>      if (isAdded) {<br>        setState(() {<br>          _resultMessage = &quot;Article Inserted&quot;;<br>        });<br>      }<br>    } catch (e) {<br>      print(e.toString());<br>    }<br>  }<br><br>  Future&lt;List&lt;Article&gt;&gt; fetchArticles() async {<br>    try {<br>      final response = await client.arkiToolEndPoint<br>          .fetchArticles(keyWord: &quot;ServerPod + Flutter&quot;);<br><br>      return response;<br>    } catch (e) {<br>      print(e.toString());<br>      return [];<br>    }<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(<br>        title: Text(widget.title),<br>      ),<br>      body: Padding(<br>        padding: const EdgeInsets.all(16),<br>        child: Column(<br>          children: [<br>            Padding(<br>              padding: const EdgeInsets.only(bottom: 16.0),<br>              child: TextField(<br>                controller: _textEditingController,<br>                decoration: const InputDecoration(<br>                  hintText: &#39;Enter your name&#39;,<br>                ),<br>              ),<br>            ),<br>            Padding(<br>              padding: const EdgeInsets.only(bottom: 16.0),<br>              child: ElevatedButton(<br>                onPressed: addArticle,<br>                child: const Text(&#39;Send to Server&#39;),<br>              ),<br>            ),<br>            _ResultDisplay(<br>              resultMessage: _resultMessage,<br>              errorMessage: _errorMessage,<br>            ),<br>            Flexible(<br>              child: FutureBuilder&lt;List&lt;Article&gt;&gt;(<br>                future: fetchArticles(),<br>                builder: (ctx, snapshot) {<br>                  if (snapshot.connectionState == ConnectionState.done) {<br>                    return ListView.builder(<br>                      itemBuilder: (ctx, index) =&gt; ListTile(<br>                        title: Text(snapshot.data?[index].title ?? &quot;N/A&quot;),<br>                      ),<br>                      itemCount: snapshot.data?.length,<br>                    );<br>                  }<br>                  return const Center(<br>                    child: CircularProgressIndicator.adaptive(),<br>                  );<br>                },<br>              ),<br>            ),<br>          ],<br>        ),<br>      ),<br>    );<br>  }<br>}<br><br>// _ResultDisplays shows the result of the call. Either the returned result from<br>// the `example.hello` endpoint method or an error message.<br>class _ResultDisplay extends StatelessWidget {<br>  final String? resultMessage;<br>  final String? errorMessage;<br><br>  const _ResultDisplay({<br>    this.resultMessage,<br>    this.errorMessage,<br>  });<br><br>  @override<br>  Widget build(BuildContext context) {<br>    String text;<br>    Color backgroundColor;<br>    if (errorMessage != null) {<br>      backgroundColor = Colors.red[300]!;<br>      text = errorMessage!;<br>    } else if (resultMessage != null) {<br>      backgroundColor = Colors.green[300]!;<br>      text = resultMessage!;<br>    } else {<br>      backgroundColor = Colors.grey[300]!;<br>      text = &#39;No server response yet.&#39;;<br>    }<br><br>    return Container(<br>      height: 50,<br>      color: backgroundColor,<br>      child: Center(<br>        child: Text(text),<br>      ),<br>    );<br>  }<br>}</pre><p>In the above code, I have implemented only fetch and create a new article. For updating and deleting a record It’s an assignment for you guys to do and then comment “<strong>Done</strong>” in the comment section of this article.</p><p>Now Last thing How can we verify if our data is stored perfectly in the DB? Since I am using Mac, I’ll be using Postico and on Windows, you can use Beekeeper Studio.</p><p>Now let’s open the Postico, you will see this form same as the below image:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*quDv_WfLlW-kfLSrk_0kOA.png" /></figure><p>Now let’s define the properties and you will see this output in the image below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/1*3gUwusMYZqJJJhL90O6esA.png" /></figure><p>Our host will remain the same, Nickname can be any name we need to set. We need to replace the following properties for connecting to our DB.</p><ol><li>User: Goto <strong>article_app_server </strong>project and open it, then go to the config folder on root, and there you will find multiple configuration files since we are in development mode we will go to development.yaml file and inside it we will go to database property:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dJJjdcu-hylu0t14hmG9rQ.png" /></figure><p>Now you will replace the <strong>port</strong> with the <strong>database port</strong>, <strong>user</strong> with <strong>database user</strong>, and <strong>database</strong> with <strong>name</strong> property inside Postico form.</p><p>Since we need to set the password of the database access it’s not available inside development.yaml file. So to get the password we will again go to the config folder on root and inside passwords.yaml you’ll get all the passwords for each environment i.e. Development, Staging, Productions, etc. So now let’s go to the development property and copy the value of the <strong>database</strong> key without Inverted commas which is the password of our database and then paste it into our Postico form and enable the checkbox for save in keychain.</p><p>Open the docker desktop app and now you need to open the terminal on the <strong>aricle_app_server </strong>project and run this command in order:</p><pre>1. docker-compose up --build --detach<br>2. serverpod create-migration<br>3. dart run bin/main.dart --apply-migrations</pre><p>After running “docker-compose up — build — detach” you will see this on your terminal:</p><pre> ✔ Container article_app_server-postgres-1  Started                                                                    0.0s <br> ✔ Container article_app_server-redis-1     Started  </pre><p>This will make a container inside the docker so that we can access our db within this container and connect to it. (<strong>Next, it will create a migration Moreover if you have already created migrations in our above discussion then leave this command and also don&#39;t pass.--apply-migrations to the 3rd command). </strong>Since I am considering you have created migrations before so just run this command after docker-compose:</p><pre>dart run bin/main.dart</pre><p>Since our docker container is up and running, we need to go back to Postico on Mac or Beekeeper Studio on Windows and try to connect again with the connection.</p><p>After connecting you will see this output on Postico:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EM4R-Kt13Z_o_-JGz51vHQ.png" /></figure><p>We can see all the available tables i.e. Serverpod generates some of them and we are interested only in the “article_tbl” Table. So now we are connected to the database as well.</p><p>Now the final step:</p><h3><strong>TESTING:</strong></h3><p>Go to the “article_app_flutter” project and run the application on an Android emulator or IOS simulator.</p><p>Once the app has been run, Try to press the “<strong>Send to server</strong>” button, You will see a message “<strong>Article Inserted</strong>”. Now, Let’s check our Postico on Mac or Beekeeper Studio on Windows database. Select/double-click on article_tbl then you’ll see a new record has been added to our database and article_tbl. Now Hot Restart the app, you’ll see the row we inserted is showing on our app too by fetching the articles.</p><p>So that’s all for today. Server Pod has been one of the flutter favorites for creating backend + frontend apps and the most precious part is the code reusability i.e. the custom objects/model class we create on the server side are accessible on the front-end app to that&#39;s what a developer needs.</p><p>To learn more about the Server pod, you can follow this series on YouTube of Observable Flutter:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F8sCxWBWhm2Y%3Fstart%3D9%26feature%3Doembed%26start%3D9&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D8sCxWBWhm2Y&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F8sCxWBWhm2Y%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/038623f42d0ccce765619954fa8835e0/href">https://medium.com/media/038623f42d0ccce765619954fa8835e0/href</a></iframe><p>I hope this clears all the doubts about how to make the most out of the server pod and flutter. Consolidating myriad findings into a comprehensive guide, empowering the Flutter community to streamline operations with a single, powerful package enhancing efficiency and unifying workflows for all Flutter developers!</p><p>So guys Stay tuned and follow/subscribe to me on Medium to get the latest articles/stories. Meanwhile, If you want to hire me for your projects? Let’s connect below:</p><ol><li>Linkedin: <a href="https://www.linkedin.com/in/mashood-siddiquie-5940a9168/">https://www.linkedin.com/in/mashood-siddiquie-5940a9168/</a></li><li>Github: <a href="https://github.com/Mashood97">https://github.com/Mashood97</a></li><li>Upwork: <a href="https://www.upwork.com/freelancers/~013e211d8172e9bd49">https://www.upwork.com/freelancers/~013e211d8172e9bd49</a></li><li>Fiverr: <a href="https://www.fiverr.com/mashood9712">https://www.fiverr.com/mashood9712</a></li><li>Email: mashoodsidd97@gmail.com</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1fc519f6d5c4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Isolates in Flutter]]></title>
            <link>https://medium.com/@mashoodsidd97/isolates-in-flutter-aaaf98ff87f5?source=rss-5b67e4c2ebd6------2</link>
            <guid isPermaLink="false">https://medium.com/p/aaaf98ff87f5</guid>
            <category><![CDATA[threads]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[dart-isolates]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Muhammad Mashood Siddiquie]]></dc:creator>
            <pubDate>Sat, 04 May 2024 16:15:42 GMT</pubDate>
            <atom:updated>2024-05-04T16:15:42.641Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Hi Guys, It’s been a long since I’ve written a blog article on Flutter. So today I have arrived to discuss a very interesting topic i.e: <br><strong>ISOLATES IN FLUTTER</strong></blockquote><figure><img alt="Flutter and Isolates" src="https://cdn-images-1.medium.com/max/1024/1*wZI4tYuaoZuobT_BiPAfLw.jpeg" /></figure><p>As it has been one of the topics that Flutter developers usually want to learn about. Think of a scenario where you are parsing a JSON file with tons of data or around 800 MB file that gives you JSON as a result. You might feel that your app starts janking while parsing that file. or if you have animation too in that page and your animation is stuck for some seconds while performing this operation? Surely you will be worried about how to fix this? The savior is “<strong>Isolates</strong>”.</p><p>I will be sharing about isolates in more upcoming articles, For the sake of simplicity let’s just use one of the powerful and simple isolates i.e. Isolate.run().</p><blockquote>Let’s understand it with an example:</blockquote><pre>import &quot;dart:io&quot;;<br><br>import &#39;package:flutter/material.dart&#39;;<br>import &quot;dart:convert&quot;;<br>import &quot;dart:isolate&quot;;<br><br>import &quot;package:flutter/services.dart&quot;;<br><br>void main() {<br>  WidgetsFlutterBinding.ensureInitialized();<br>  runApp(<br>    const MaterialApp(<br>      debugShowCheckedModeBanner: false,<br>      home: MyApp(),<br>    ),<br>  );<br>}<br><br>class MyApp extends StatefulWidget {<br>  const MyApp({super.key});<br><br>  @override<br>  State&lt;MyApp&gt; createState() =&gt; _MyAppState();<br>}<br><br>class _MyAppState extends State&lt;MyApp&gt; {<br>  @override<br>  Widget build(BuildContext context) {<br>    return Home();<br>  }<br>}<br><br>class Home extends StatefulWidget {<br>  const Home({super.key});<br><br>  @override<br>  State&lt;Home&gt; createState() =&gt; _HomeState();<br>}<br><br>class _HomeState extends State&lt;Home&gt; {<br>  Future&lt;String&gt; getDataWithDelay() async {<br>    try {<br><br>      final fileData = await rootBundle.loadString(&quot;assets/my_json.json&quot;);<br>      var _decoded = jsonDecode(fileData) as List&lt;dynamic&gt;;<br>      print(_decoded);<br>      return _decoded.first.toString();<br>    } catch (e) {<br>      print(e.toString());<br>      return &quot;&quot;;<br>    }<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      body: FutureBuilder&lt;String&gt;(<br>          future: getDataWithDelay(),<br>          builder: (context, snapshot) {<br>            if (snapshot.connectionState == ConnectionState.done) {<br>              return Center(<br>                child: Text(snapshot.data ?? &quot;N/A&quot;),<br>              );<br>            }<br>            return const Center(child: CircularProgressIndicator.adaptive());<br>          }),<br>    );<br>  }<br>}</pre><p>You can grab this code and paste it into the main.dart, When you run the application you can see a little jank on the loading indicator which means the user might think the app has stopped responding to user-tapped events. In such cases we use Isolates so let’s convert our code to use isolates below:</p><pre>import &quot;dart:io&quot;;<br><br>import &#39;package:flutter/material.dart&#39;;<br>import &quot;dart:convert&quot;;<br>import &quot;dart:isolate&quot;;<br><br>import &quot;package:flutter/services.dart&quot;;<br><br>void main() {<br>  WidgetsFlutterBinding.ensureInitialized();<br>  runApp(<br>    const MaterialApp(<br>      debugShowCheckedModeBanner: false,<br>      home: MyApp(),<br>    ),<br>  );<br>}<br><br>class MyApp extends StatefulWidget {<br>  const MyApp({super.key});<br><br>  @override<br>  State&lt;MyApp&gt; createState() =&gt; _MyAppState();<br>}<br><br>class _MyAppState extends State&lt;MyApp&gt; {<br>  @override<br>  Widget build(BuildContext context) {<br>    return Home();<br>  }<br>}<br><br>class Home extends StatefulWidget {<br>  const Home({super.key});<br><br>  @override<br>  State&lt;Home&gt; createState() =&gt; _HomeState();<br>}<br><br>class _HomeState extends State&lt;Home&gt; {<br>  Future&lt;String&gt; getDataWithDelay() async {<br>    try {<br>      final fileData = await rootBundle.loadString(&quot;assets/myJson.json&quot;);<br>      final _decoded = await Isolate.run(() {<br>        return jsonDecode(fileData) as List&lt;dynamic&gt;;<br>      });<br>      print(_decoded);<br>      return _decoded.first.toString();<br>    } catch (e) {<br>      print(e.toString());<br>      return &quot;&quot;;<br>    }<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      body: FutureBuilder&lt;String&gt;(<br>          future: getDataWithDelay(),<br>          builder: (context, snapshot) {<br>            if (snapshot.connectionState == ConnectionState.done) {<br>              return Center(<br>                child: Text(snapshot.data ?? &quot;N/A&quot;),<br>              );<br>            }<br>            return const Center(child: CircularProgressIndicator.adaptive());<br>          }),<br>    );<br>  }<br>}</pre><blockquote>Now you run/restart your app again, You will see our loader doesn’t jank, What is so special about isolates in such a case? Let’s understand in few points:<br>1. Our app starts on <strong>Main UI Isolate<br></strong>2. We call our <strong>getDataWithDelay() </strong>method which uses Isolate.run.<br>3. Isolate.run creates a new Isolate which doesn’t stop our Main UI Isolate so the jank that appears on the loader vanishes and our app runs smoothly. The decode of JSON is now isolated in its world.This Isolate has its memory and gets destroyed once it’s completed <strong>That’s the main difference between the Isolates in Dart and threads in other programming languages like Java etc.</strong></blockquote><p>I hope this clears all the doubts about how to use Isolate.run in your app and at what use case you might think to use it.</p><p>So guys Stay tuned and follow/subscribe to me on Medium to get the latest articles/stories. Meanwhile, If you want to hire me for your projects? Let’s connect below:</p><ol><li>Linkedin: <a href="https://www.linkedin.com/in/mashood-siddiquie-5940a9168/">https://www.linkedin.com/in/mashood-siddiquie-5940a9168/</a></li><li>Github: <a href="https://github.com/Mashood97">https://github.com/Mashood97</a></li><li>Upwork: <a href="https://www.upwork.com/freelancers/~013e211d8172e9bd49">https://www.upwork.com/freelancers/~013e211d8172e9bd49</a></li><li>Fiverr: <a href="https://www.fiverr.com/mashood9712">https://www.fiverr.com/mashood9712</a></li><li>Email: mashoodsidd97@gmail.com</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aaaf98ff87f5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Chopper: Flutter’s Multipart Requests  ]]></title>
            <link>https://medium.com/@mashoodsidd97/mastering-chopper-flutters-multipart-requests-e6b7cea6a5f1?source=rss-5b67e4c2ebd6------2</link>
            <guid isPermaLink="false">https://medium.com/p/e6b7cea6a5f1</guid>
            <category><![CDATA[multipart-form-data]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <dc:creator><![CDATA[Muhammad Mashood Siddiquie]]></dc:creator>
            <pubDate>Fri, 24 Nov 2023 23:57:11 GMT</pubDate>
            <atom:updated>2023-11-24T23:57:11.529Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi Guys, It’s been a long since I’ve written a blog article on Flutter. So today I have arrived to discuss a very interesting topic i.e:<br>Revolutionizing Flutter’s Chopper: Unveiling the Hidden Power of Multipart Requests! 🚀 Developers, it’s time to break free from alternate packages like dio or HTTP client for handling multipart requests. Dive into a game-changing approach with Chopper, optimizing API calls for seamless app integration.</p><p>As I was building an application that uses Chopper client and guess what when it comes to multipart and sending files I didn’t find much support in the documentation for sending files to a server using Chopper then I googled about it and guess what most of the developers are using dio or HTTP client to manage multipart and other crud operations are simply done with a chopper 🧐. Ouch, that doesn’t look quite good Huh? GitHub issues links are attached, these are closed because people are using HTTP or Dio to manage multipart requests 🥶, so without wasting much time let’s dive into how we can manage API calls using chopper for multipart requests ❤.</p><p><a href="https://github.com/lejard-h/chopper/issues/160">https://github.com/lejard-h/chopper/issues/160</a></p><p><a href="https://github.com/lejard-h/chopper/issues/55">https://github.com/lejard-h/chopper/issues/55</a></p><p>You can see in these reported issues people are using HTTP or dio to send multipart requests might be chopper documentation needs to get updated so people can easily integrate these things seamlessly</p><p>There are three scenarios that we will be discussing in this article:<br>1. Sending Data without file.<br>2. Sending File only.<br>3. Sending Data and files together.</p><p>Let’s assume this as URL as our base URL:<br>“www.testingurl.com/api/ ”<br>This is a dummy url so don’t think it will work by copy-pasting the code as we will only discuss how we can achieve it.😂</p><p>So let’s set the dependencies and project startup:</p><p>First, add a chopper inside pubspec.yaml file inside the dependencies section:</p><pre>dependencies:<br>  chopper: ^7.0.9</pre><p>Also, add chopper_generator and build_runner to our dev_dependencies section inside the pubspec.yaml file:</p><pre>dev_dependencies:<br>  chopper_generator: ^7.0.6<br>  build_runner: ^2.4.6</pre><p>Now run flutter pub get to retrieve all the dependencies for our project.</p><p>Now let’s create a folder inside the lib directory with the name “networking” and create a dart file inside it with the name chopper_client.dart:</p><pre>class ChopperClientInstance {<br>  static final ChopperClientInstance _singleton =<br>      ChopperClientInstance._internal();<br><br>  factory ChopperClientInstance() {<br>    return _singleton;<br>  }<br><br>  ChopperClientInstance._internal();<br><br><br>  static ChopperClient? client;<br><br>  static void initializeChopperClient() {<br>    client ??= ChopperClient(<br>        baseUrl: Uri.parse(&quot;www.testingurl.com/api/&quot;),<br>        services: [<br>         <br>        ],<br>      <br>        converter: const JsonConverter(),<br>        <br>        );<br>  }<br>}</pre><p>We have set a simple chopper client as a singleton class, you might have watched services containing an empty list so don’t worry we will fill this in a few minutes.</p><p>So now go inside the main.dart file and then go to the void main entry point before the runApp(), initialize the chopper client instance like below.</p><pre>void main() {<br>ChopperClientInstance.initializeChopperClient();<br>// Other functionalities and methods<br>}</pre><p>Now we have set our chopper client 😍. It’s time to dive into the main topic i.e managing multipart requests, so let’s begin with the points we discussed, Oh I don’t want you guys to scroll up again so for simplicity you can find it here:</p><pre>There are three scenarios that we will be discussing in this article:<br>1. Sending Data without file.<br>2. Sending File only.<br>3. Sending Data and files together.</pre><p><strong>So Let’s start with point# 1:</strong></p><p>Let’s create another directory inside the networking folder with the name “Services” and then create a file inside it with the name “multipart_chopper_service.dart”:<br>I’ve defined all 3 methods that we may require later as well</p><pre>import &#39;package:chopper/chopper.dart&#39;;<br>part &#39;multipart_chopper_service.chopper.dart&#39;;<br><br>@ChopperApi()<br>abstract class MultipartChopperService extends ChopperService {<br>  static MultipartChopperService create([ChopperClient? client]) =&gt;<br>      _$MultipartChopperService(client);<br><br>@Post(path: &quot;user/send-multipart-data&quot;, headers: {<br>    &#39;Accept&#39;: &#39;application/json&#39;,<br>    &#39;Content-Type&#39;: &#39;multipart/form-data&#39;<br>  })<br>  @Multipart()<br>  Future&lt;Response&lt;Map&gt;&gt; sendDataWithMultipart({<br>    @PartMap() required List&lt;PartValue&gt; requestParams,<br>  });<br><br>@Post(path: &quot;user/send-multipart-file&quot;, headers: {<br>    &#39;Accept&#39;: &#39;application/json&#39;,<br>    &#39;Content-Type&#39;: &#39;multipart/form-data&#39;<br>  })<br>  @Multipart()<br>  Future&lt;Response&lt;Map&gt;&gt; sendFileWithMultipart({<br>    @PartMap() required List&lt;PartValue&gt; requestParams,<br>  });<br><br>@Post(path: &quot;user/send-multipart-data-with-file&quot;, headers: {<br>    &#39;Accept&#39;: &#39;application/json&#39;,<br>    &#39;Content-Type&#39;: &#39;multipart/form-data&#39;<br>  })<br>  @Multipart()<br>  Future&lt;Response&lt;Map&gt;&gt; sendFileAndDataWithMultipart({<br>    @PartMap() required List&lt;PartValue&gt; requestParams,<br>  });<br><br>}</pre><p>Now It looks a little bit confusing at first 😳 but don’t worry I am your savior here right now so just understand the key points in this class:<br>1. Never forget to add part imports i.e. part ‘your_file_name.chopper.dart’.<br>2. Never forget to create a class as an abstract and always annotate with “@ChopperApi()” so the code generator can easily understand that this class belongs to the chopper client.</p><p>3. Now the main point as you can see I’ve used “@PartMap” but why? So let’s understand this deeply:</p><p>In Chopper we have three things to understand when to use PartMap, Part, and PartFile.<br>When we want to send single data in a multipart request we can simply use Part, similarly a single file we use PartFile but when we want to send multiple data or multiple files or a combination of both data and files we use PartMap, I’ve used PartMap as I really like it because if backend team added any request param for the request so I don’t want to define manually every time here so it’s better to add PartMap.</p><p>4. Now why do we use List&lt;PartValue&gt; because we want to send more than one param then we use this but when we use Part or PartFile we can define the data types like String, int, or whatever it is.</p><p>So now let’s generate our chopper client class, Thanks to chopper_generator and build_runner which makes it easier to generate classes.<br>Open the terminal inside your IDE and run this command:</p><pre>dart run build_runner build --delete-conflicting-outputs</pre><p>OR</p><pre>flutter pub run build_runner build --delete-conflicting-outputs</pre><p>This will generate a class with the name ‘multipart_chopper_service.chopper.dart’ that we added as a part import inside our service.</p><p>Now let’s consume our chopper client to make a multipart request</p><p>First, we need to go to our chopper_client.dart class and inside services list let’s add our multipart_service class inside it:</p><pre>class ChopperClientInstance {<br>  static final ChopperClientInstance _singleton =<br>      ChopperClientInstance._internal();<br><br>  factory ChopperClientInstance() {<br>    return _singleton;<br>  }<br><br>  ChopperClientInstance._internal();<br><br>  static ChopperClient? client;<br><br>  static void initializeChopperClient() {<br>    client ??= ChopperClient(<br>        baseUrl: Uri.parse(&quot;www.testingurl.com/api/&quot;),<br>        services: [<br>         MultipartChopperService.create(),<br>        ],<br>      <br>        converter: const JsonConverter(),<br>        <br>        );<br>  }<br>}</pre><p>Let’s begin with sending data with a multipart request</p><p>Assume we need to send this data to the server:</p><ol><li>Email</li><li>Password</li></ol><p>Let’s create a directory inside the lib folder with the name “models” and create a file with the name “send_data_request_params.dart”:</p><pre>class SendDataRequestParam {<br>  String? email;<br>  String? password;<br><br>  SendDataRequestParam({this.email, this.password});<br><br>  SendDataRequestParam.fromJson(Map&lt;String, dynamic&gt; json) {<br>    email = json[&#39;email&#39;];<br>    password = json[&#39;password&#39;];<br>  }<br><br>  Map&lt;String, dynamic&gt; toJson() {<br>    final Map&lt;String, dynamic&gt; data = new Map&lt;String, dynamic&gt;();<br>    data[&#39;email&#39;] = this.email;<br>    data[&#39;password&#39;] = this.password;<br>    return data;<br>  }<br>}</pre><p>Now Goto main.dart or wherever you want to use your chopper client, I will be using a default flutter project template of the counter app, so inside the HomePage stateful widget:</p><p>I will add this line of code:</p><pre>final MultipartChopperService multipartService =<br>      MultipartChopperService.create(ChopperClientInstance.client);</pre><p>Now I will create a function with the name sendDataWithMultipartRequest:</p><pre>Future&lt;void&gt; sendDataWithMultipartRequest({<br>    required SendDataRequestParam params,<br>  }) async {<br>    try {<br>      List&lt;PartValue&gt; requestParams = [];<br>params.toJson().forEach((key,value){<br>requestParams.add(PartValue(key,value));<br>});<br>      final response = await multipartService.sendDataWithMultipart(<br>        requestParams: requestParams,<br>      );<br>      if (response.isSuccessful) {<br>        final body = response.bodyString;<br>        final decodedBody = jsonDecode(body);<br>// Add your logic whatever you want to do if api request succeed.<br>        print(&quot;Data is $decodedBody&quot;);<br>      } <br>    } catch (e) {<br>      throw e.toString();<br>    }<br>  }</pre><p>This will send data with the multipart request, you can tweak this more as per your need like return type instead of void, etc.</p><p>Now Let’s send the file with the chopper:</p><p>Now I will create a function with the name sendFileWithMultipartRequest:</p><p>For example, you may have used image_picker to pick an image or capture an image by using the camera, you get a file from there, so let’s assume the file you get is saved inside the variable named “capturedImage”.</p><pre>Future&lt;void&gt; sendFileWithMultipartRequest() async {<br>    try {<br>// This image path is coming from image picker.<br>String imagePath = capturedImage.path;<br>      List&lt;PartValue&gt; requestParams = [];<br>requestParams.add(PartValueFile(&quot;image&quot;,imagePath),);<br><br>      final response = await multipartService.sendFileWithMultipart(<br>        requestParams: requestParams,<br>      );<br>      if (response.isSuccessful) {<br>        final body = response.bodyString;<br>        final decodedBody = jsonDecode(body);<br>// Add your logic whatever you want to do if api request succeed.<br>        print(&quot;Data is $decodedBody&quot;);<br>      } <br>    } catch (e) {<br>      throw e.toString();<br>    }<br>  }</pre><p>In this way, you will see your file will be uploaded successfully to the server using chopper.</p><p>Now Let’s move to the last part of this article sending data and files together with chopper:</p><p>Let’s create a model class again inside the lib/models folder with the name “send_data_files_request”:</p><pre>class SendDataFilesRequest {<br>  String? username;<br>  String? phoneNumber;<br>  String? profilePhotoPath;<br><br>  SendDataFilesRequest({this.username, this.phoneNumber, this.profilePhotoPath});<br><br>  SendDataFilesRequest.fromJson(Map&lt;String, dynamic&gt; json) {<br>    username = json[&#39;username&#39;];<br>    phoneNumber = json[&#39;phone_number&#39;];<br>    profilePhotoPath = json[&#39;profile_photo&#39;];<br>  }<br><br>  Map&lt;String, dynamic&gt; toJson() {<br>    final Map&lt;String, dynamic&gt; data = new Map&lt;String, dynamic&gt;();<br>    data[&#39;username&#39;] = this.username;<br>    data[&#39;phone_number&#39;] = this.phoneNumber;<br>    data[&#39;profile_photo&#39;] = this.profilePhotoPath;<br>    return data;<br>  }<br>}</pre><p>Now I will create a function with the name sendDataAndFilesBothWithMultipartRequest:</p><pre>Future&lt;void&gt; sendDataAndFilesBothWithMultipartRequest({<br>    required SendDataFilesRequest params,<br>  }) async {<br>    try {<br>      List&lt;PartValue&gt; requestParams = [];<br>      params.toJson().forEach((key,value){<br>      if(key ==&quot;profile_photo&quot; &amp;&amp; (value != null &amp;&amp; value?.isNotEmpty == true)){<br>          requestParams.add(PartValueFile(key,value));<br>        }<br>      else{<br>          requestParams.add(PartValue(key,value));<br>        }<br>  });<br>      final response = await multipartService.sendFileAndDataWithMultipart(<br>        requestParams: requestParams,<br>      );<br>      if (response.isSuccessful) {<br>        final body = response.bodyString;<br>        final decodedBody = jsonDecode(body);<br>// Add your logic whatever you want to do if api request succeed.<br>        print(&quot;Data is $decodedBody&quot;);<br>      } <br>    } catch (e) {<br>      throw e.toString();<br>    }<br>  }</pre><p>Now in this way, you can send both files and data as multipart requests with the help of a chopper.</p><p><strong>Finally! The culmination of Exhaustive Research: Simplifying Flutter API Calls with Chopper. Consolidating myriad findings into a comprehensive guide, empowering the Flutter community to streamline operations with a single, powerful package. Here’s to enhancing efficiency and unifying workflows for all Flutter developers! 🥳✌🏻❤️</strong></p><p>So guys Stay tuned and follow/subscribe to me on Medium to get the latest articles/stories. Meanwhile, you can find me on these social platforms as well:</p><ol><li>Linkedin: <a href="https://www.linkedin.com/in/mashood-siddiquie-5940a9168/">https://www.linkedin.com/in/mashood-siddiquie-5940a9168/</a></li><li>Github: <a href="https://github.com/Mashood97">https://github.com/Mashood97</a></li><li>Email: mashoodsidd97@gmail.com</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e6b7cea6a5f1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PostParsing JSON In Background In Flutter]]></title>
            <link>https://medium.com/@mashoodsidd97/postparsing-json-in-background-in-flutter-95f6d196b28c?source=rss-5b67e4c2ebd6------2</link>
            <guid isPermaLink="false">https://medium.com/p/95f6d196b28c</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[google]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Muhammad Mashood Siddiquie]]></dc:creator>
            <pubDate>Fri, 22 Apr 2022 21:20:53 GMT</pubDate>
            <atom:updated>2022-04-22T21:20:53.961Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*ItJ2vttimEyNhII6O_IePA.jpeg" /><figcaption>Flutter Isolates</figcaption></figure><p>Hello Flutter Devs, I hope you guys are doing great 😊 , Today We will talk about how to parse JSON in the background in a flutter, so let’s don’t waste time and jump into the basic understanding of it.</p><p>As we know Flutter applications run on a single thread/Isolate. We will discuss later what are isolates in the upcoming article. Assume you create an application that supports some backend services let’s assume API, your application runs smoothly on higher-end devices but when you run your app on a lower-end device it starts lagging at some stage maybe because we have thousands of data or maybe hundreds of data coming from backend services which can take time to parse the response due to which a user can’t perform any action on other features of the app, which can frustrate your user as per UX i.e user experience :( or might be possible a user may delete your application. To solve these problems what we can do to make our app run smoothly? yes, you have thought right, we will be going to parse the backend service response into the background thread/isolate so that your application may not lag on a lower-end device, but it may work smoothly on a lower-end device, I hope you have got a vast knowledge about the problem i described, so let’s jump towards the solution by coding.</p><p>— — — — — — — — — EXCITEMENT BEGINS HERE — — — — — — — — — <br>We will be using Get-x and Dio with Repository Pattern, also we will be using a free mock API of JSON placeholder.<br>API URL: “<a href="https://jsonplaceholder.typicode.com/posts">https://jsonplaceholder.typicode.com/posts</a>”</p><p>First, create an empty project with any name you want, it’s totally up to you what name you want to give to your app, I hope it might be meaningful 😭.</p><p>Now go to pubspec.yaml file and add these packages under the dependencies section:<br>get: 4.6.1<br>dio: 4.0.6</p><p>Then open a terminal and run this command “flutter pub get”.</p><p>Now go Inside the lib folder and create a new directory inside it with the name networking. create a subfolder inside networking with the name dio_client. <br>Now create a file inside the dio_client folder with the name dio_client.dart and copy-paste the following code:</p><pre>import &#39;package:dio/dio.dart&#39;;</pre><pre>import &#39;package:flutter/foundation.dart&#39;;</pre><pre>import &#39;../exception/http_exception.dart&#39;;</pre><pre>const _defaultConnectTimeout = Duration.millisecondsPerMinute;<br>const _defaultReceiveTimeout = Duration.millisecondsPerMinute;<br>const kServerError =&#39;The server encountered an internal error and unable to process your request.&#39;;<br>const kRedirectionError = &#39;The resource requested has been temporarily moved.&#39;;</pre><pre>const kBadRequestError =&#39;Your client has issued a malformed or illegal request.&#39;;</pre><pre>const kInternetError =&#39;There is poor or no internet connection, please try again later.&#39;;</pre><pre>class DioClient {</pre><pre>static final DioClient _singleton = DioClient._internal();</pre><pre>static Dio? _dio;</pre><pre>factory DioClient({required Dio dio}) {</pre><pre>_dio = dio;</pre><pre>List&lt;Interceptor&gt;? interceptors;</pre><pre>_dio!</pre><pre>..options.baseUrl = &quot;https://jsonplaceholder.typicode.com/&quot;</pre><pre>..options.connectTimeout = _defaultConnectTimeout</pre><pre>..options.receiveTimeout = _defaultReceiveTimeout</pre><pre>..options.headers = {&#39;Content-Type&#39;: &#39;application/json; charset=UTF-8&#39;}</pre><pre>..httpClientAdapter;</pre><pre>if (interceptors?.isNotEmpty ?? false) {</pre><pre>_dio!.interceptors.addAll(interceptors!);</pre><pre>}</pre><pre>if (kDebugMode) {</pre><pre>_dio!.interceptors.add(LogInterceptor(</pre><pre>responseBody: true,</pre><pre>error: true,</pre><pre>requestHeader: true,</pre><pre>responseHeader: true,</pre><pre>request: true,</pre><pre>requestBody: true));</pre><pre>}</pre><pre>return _singleton;</pre><pre>}</pre><pre>DioClient._internal();</pre><pre>Future&lt;dynamic&gt; get(</pre><pre>String? uri, {</pre><pre>Map&lt;String, dynamic&gt;? queryParameters,</pre><pre>Options? options,</pre><pre>CancelToken? cancelToken,</pre><pre>ProgressCallback? onReceiveProgress,</pre><pre>}) async {</pre><pre>try {</pre><pre>var response = await _dio!.get(</pre><pre>uri!,</pre><pre>queryParameters: queryParameters,</pre><pre>options: options,</pre><pre>cancelToken: cancelToken,</pre><pre>onReceiveProgress: onReceiveProgress,</pre><pre>);</pre><pre>return response.data;</pre><pre>} on DioError catch (e) {</pre><pre>if (DioErrorType.receiveTimeout == e.type ||</pre><pre>DioErrorType.connectTimeout == e.type ||</pre><pre>DioErrorType.sendTimeout == e.type) {</pre><pre>throw HttpException(kInternetError);</pre><pre>} else if (DioErrorType.response == e.type) {</pre><pre>throw HttpException(</pre><pre>e.response!.data[&#39;message&#39;]</pre><pre>.toString()</pre><pre>.replaceAll(&quot;[&quot;, &quot;&quot;)</pre><pre>.replaceAll(&quot;]&quot;, &quot;&quot;),</pre><pre>);</pre><pre>} else {</pre><pre>throw HttpException(kServerError);</pre><pre>}</pre><pre>}</pre><pre>}</pre><pre>Future&lt;dynamic&gt; delete(</pre><pre>String? uri, {</pre><pre>Map&lt;String, dynamic&gt;? queryParameters,</pre><pre>Options? options,</pre><pre>CancelToken? cancelToken,</pre><pre>}) async {</pre><pre>try {</pre><pre>var response = await _dio!.delete(</pre><pre>uri!,</pre><pre>queryParameters: queryParameters,</pre><pre>options: options,</pre><pre>cancelToken: cancelToken,</pre><pre>);</pre><pre>return response.data;</pre><pre>} on DioError catch (e) {</pre><pre>if (DioErrorType.receiveTimeout == e.type ||</pre><pre>DioErrorType.connectTimeout == e.type ||</pre><pre>DioErrorType.sendTimeout == e.type) {</pre><pre>throw HttpException(kInternetError);</pre><pre>} else if (DioErrorType.response == e.type) {</pre><pre>throw HttpException(</pre><pre>e.response!.data[&#39;message&#39;]</pre><pre>.toString()</pre><pre>.replaceAll(&quot;[&quot;, &quot;&quot;)</pre><pre>.replaceAll(&quot;]&quot;, &quot;&quot;),</pre><pre>);</pre><pre>} else {</pre><pre>throw HttpException(kServerError);</pre><pre>}</pre><pre>}</pre><pre>}</pre><pre>Future&lt;dynamic&gt; post(</pre><pre>String? uri, {</pre><pre>data,</pre><pre>Map&lt;String, dynamic&gt;? queryParameters,</pre><pre>Options? options,</pre><pre>CancelToken? cancelToken,</pre><pre>ProgressCallback? onSendProgress,</pre><pre>ProgressCallback? onReceiveProgress,</pre><pre>}) async {</pre><pre>try {</pre><pre>var response = await _dio!.post(</pre><pre>uri!,</pre><pre>data: data,</pre><pre>queryParameters: queryParameters,</pre><pre>options: options,</pre><pre>cancelToken: cancelToken,</pre><pre>onSendProgress: onSendProgress,</pre><pre>onReceiveProgress: onReceiveProgress,</pre><pre>);</pre><pre>return response.data;</pre><pre>} on DioError catch (e) {</pre><pre>if (DioErrorType.receiveTimeout == e.type ||</pre><pre>DioErrorType.connectTimeout == e.type ||</pre><pre>DioErrorType.sendTimeout == e.type) {</pre><pre>throw HttpException(kInternetError);</pre><pre>} else if (DioErrorType.response == e.type) {</pre><pre>throw HttpException(</pre><pre>e.response!.data[&#39;message&#39;]</pre><pre>.toString()</pre><pre>.replaceAll(&quot;[&quot;, &quot;&quot;)</pre><pre>.replaceAll(&quot;]&quot;, &quot;&quot;),</pre><pre>);</pre><pre>} else {</pre><pre>throw HttpException(kServerError);</pre><pre>}</pre><pre>}</pre><pre>}</pre><pre>}</pre><p>Now you may get some red lines like WTH is HttpException class? It’s a very simple class so don’t worry just create another folder inside the networking folder with the name exception, then create a file inside the exception folder with http_exception.dart then copy-pastes the following code:</p><pre>class HttpException implements Exception {</pre><pre>final String message;</pre><pre>HttpException(this.message);</pre><pre>@override<br>String toString() {<br>return message;<br>}<br>}</pre><p>Great, the error must have been gone now, Congratulations 🎉 🥳 .</p><p>Now move towards the lib folder again…..</p><p>Create another folder namely post inside the lib directory. follow the sub folder hierarchy in the image below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/506/1*BPPsUrLvKecjD-VaJL5sVA.png" /><figcaption>Post Directory Hierarchy.</figcaption></figure><p>Now first look at the API response and what it looks like. We have a list of posts, so we will grab only a single object from the list of posts so that we can create a model class from it. A single object looks something like this:</p><pre><strong>{<br> </strong>&quot;userId&quot;: <strong>1</strong>,<br> &quot;id&quot;: <strong>1</strong>,<br> &quot;title&quot;: &quot;sunt aut facere repellat provident occaecati excepturi   optio reprehenderit&quot;,<br> &quot;body&quot;: &quot;quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto&quot;<br><strong>}</strong></pre><p>Hm, So we can create a model class directly, but there’s a super-easy and fast way to create a model class, Just go to the below link:</p><p><a href="https://javiercbk.github.io/json_to_dart/">https://javiercbk.github.io/json_to_dart/</a></p><p>It may look strange to you, but it will help you a lot and save your development time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QUdSvJ7vlaTULp_3zDdqng.png" /></figure><p>Now below the JSON header, paste the JSON object you copied earlier, then give a name to your model class inside the input field provided, final output will be the same as the below image:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DOOoTmMuZ8BVkD6QB_0Hgw.png" /></figure><p>Wow, super easy to create model class, ❤️ heartily thank the developer who made this tool for us.</p><p>Now copy this code and then go inside lib/post/model and create a new class with the name post_model.dart and paste the copied code over there.</p><p>Now go to the repo folder inside the post folder, create a class inside the repo folder with the name post_repository.dart.</p><p>Here we will have two classes inside post_repository, one will be a concrete class, and the other which will extend this concrete class to perform it’s implementation.</p><p>First create an abstract class with the name PostRepository, see the below image for help:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2IEOqxlqUffMSAEBRqF7qw.png" /></figure><p>Now create another class below the PostRepository with name PostRepositoryImplementation which will extend PostRepository class, see the below image for help:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/964/1*VmXyvz2WA1-KC4g67SoNCw.png" /></figure><p>You may see a red line below PostRepositoryImpl, that’s because you have to override the parent class method, so just override the parent class method of getting posts. See the below image for help</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LgHC5julViPjANOyurCA5w.png" /></figure><p>Now we have to call our backend service here by using the dio client we created earlier. so how could we do that? create an instance of dio client inside PostRepositoryImpl class and pass it to the constructor of it, please see the below image for the help:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dpTJyC3BMqFJqqX1D9DL5A.png" /></figure><p>Now let’s create a functional body of the getPosts method, first, we will create a method without parsing JSON in the background, then we will add JSON parsing in the background. See the below image for help:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oZx01snAayGxN5Po3eCfrA.png" /></figure><p>Here we wait for the response using the get the request of our dio client where we pass the endpoint of the URL, as we already set the baseUrl on our dio_client.dart class. Here we simply return the list of posts, as there are only 100 data inside this API response, but let’s assume this API may return 1000’s data which can lag the application on the lower-end devices. To convert this JSON parsing into the background thread, we will use compute function which is related to isolate, a compute function will create another thread/isolate which will run in the background, this compute function will run and destroy on its own when the job is done which will not create any memory leakage. compute functions take two params inside it, one a function, second data we will be passing. The function we pass inside the compute should be outside the class or should be static inside the class.<br>So let’s create a method that will parse our JSON in the background, please see the below image for help:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eeSkZQysYVshMx1dAhOGWg.png" /></figure><p>Here you can see we create a method out of the class called parsed Post Response, which takes a string as a param and returns us a List&lt;PostModel&gt;.</p><p>Now, this is all done let’s move towards our controller and view, create a file inside the controller folder with the name: post_controller.dart, and then copy-paste the following code:</p><pre>import &#39;package:get/get.dart&#39;;</pre><pre>import &#39;package:networking_background/post/model/post_model.dart&#39;;</pre><pre>import &#39;package:networking_background/post/repo/post_repository.dart&#39;;</pre><pre>class PostController extends GetxController {</pre><pre>final PostRepository postRepository;</pre><pre>PostController({</pre><pre>required this.postRepository,</pre><pre>});</pre><pre>final RxList&lt;PostModel&gt; _posts = RxList();</pre><pre>List&lt;PostModel&gt; get posts =&gt; [..._posts];</pre><pre>final RxBool _isLoadingState = false.obs;</pre><pre>bool get isLoadingState =&gt; _isLoadingState.value;</pre><pre>Future&lt;void&gt; getPostsFromServer() async {</pre><pre>_isLoadingState.value = true;</pre><pre>try {</pre><pre>final response = await postRepository.getPosts();</pre><pre>_posts.addAll(response);</pre><pre>} catch (e) {</pre><pre>Get.snackbar(&quot;Error&quot;, e.toString());</pre><pre>}</pre><pre>_isLoadingState.value = false;</pre><pre>}</pre><pre>@override</pre><pre>void onInit() async {</pre><pre>await getPostsFromServer();</pre><pre>super.onInit();</pre><pre>}</pre><pre>}</pre><p>Here we want to get access to our PostRepository so we can call the method of getting posts, so simply we create an instance of our post repository and pass it to the constructor of our controller. onInit function we call our API so whenever our controller is initialized this API will be called.</p><p>Now let’s create a view for our application:<br>create a file inside the view folder with the name post_view.dart and copy-paste the following code:</p><pre>import &#39;package:flutter/material.dart&#39;;</pre><pre>import &#39;package:get/get.dart&#39;;</pre><pre>import &#39;package:networking_background/post/controller/post_controller.dart&#39;;</pre><pre>class PostView extends StatelessWidget {</pre><pre>PostView({Key? key}) : super(key: key);</pre><pre>final _postController = Get.find&lt;PostController&gt;();</pre><pre>@override</pre><pre>Widget build(BuildContext context) {</pre><pre>return Scaffold(</pre><pre>appBar: AppBar(</pre><pre>title: const Text(&quot;Networking In Background&quot;),</pre><pre>),</pre><pre>body: SafeArea(</pre><pre>child: Obx(() =&gt; _postController.isLoadingState</pre><pre>? const Center(child: CircularProgressIndicator.adaptive())</pre><pre>: ListView.separated(</pre><pre>itemBuilder: (ctx, index) =&gt; ListTile(</pre><pre>title: Text(_postController.posts[index].title ?? &quot;&quot;),</pre><pre>subtitle: Text(_postController.posts[index].body ?? &quot;&quot;),</pre><pre>),</pre><pre>separatorBuilder: (_, __) =&gt; const Divider(),</pre><pre>itemCount: _postController.posts.length,</pre><pre>)),</pre><pre>),</pre><pre>);</pre><pre>}</pre><pre>}</pre><p>Here we use Obx which is provided by getting library, it’s used to re-build the specific part of the UI rather than the whole screen.</p><p>Now The main point is, how we will be going to pass the parameters to our controller and our repository? We will be going to implement a simple dependency injection using get library. so go to the main. dart and copy-paste the following code inside main. dart:</p><pre>import &#39;package:dio/dio.dart&#39;;</pre><pre>import &#39;package:flutter/material.dart&#39;;</pre><pre>import &#39;package:get/get.dart&#39;;</pre><pre>import &#39;package:networking_background/post/controller/post_controller.dart&#39;;</pre><pre>import &#39;package:networking_background/post/repo/post_repository.dart&#39;;</pre><pre>import &#39;package:networking_background/post/view/post_view.dart&#39;;</pre><pre>import &#39;networking/dio_client/dio_client.dart&#39;;</pre><pre>void main() {</pre><pre>Get.lazyPut&lt;PostController&gt;(</pre><pre>() =&gt; PostController(postRepository: Get.find&lt;PostRepository&gt;()),</pre><pre>fenix: true);</pre><pre>Get.lazyPut&lt;PostRepository&gt;(</pre><pre>() =&gt; PostRepositoryImpl(dioClient: Get.find&lt;DioClient&gt;()),</pre><pre>fenix: true);</pre><pre>Get.lazyPut&lt;DioClient&gt;(</pre><pre>() =&gt; DioClient(</pre><pre>dio: Dio(),</pre><pre>),</pre><pre>fenix: true);</pre><pre>runApp(const MyApp());</pre><pre>}</pre><pre>class MyApp extends StatelessWidget {</pre><pre>const MyApp({Key? key}) : super(key: key);</pre><pre>@override</pre><pre>Widget build(BuildContext context) {</pre><pre>return GetMaterialApp(</pre><pre>title: &#39;Flutter Demo&#39;,</pre><pre>theme: ThemeData(</pre><pre>primarySwatch: Colors.blue,</pre><pre>),</pre><pre>home: PostView(),</pre><pre>);</pre><pre>}</pre><pre>}</pre><p>Now as you can see, inside the void main function we used get. lazyput as it will create the instance of the specified class but will not initialize until we find/use it in some class, Fenix means it will remain in memory.</p><p>Now let’s run our application, it will look like this, first, we will have a loader then we will see a list of posts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*v6kbX5L8v_RL2L3njMC5tQ.png" /></figure><p>Congratulations 🥳 👏 🥂 🎉 , You have learned a simple but useful knowledge about how to parse the JSON in the background using compute function.</p><p>If you like the article, then don’t forget to Clap and share it with your other Flutter Devs community.</p><p>P.S: I tried my best to make this useful approach as simple and as detailed as possible so you may create smooth-running apps on lower-end devices as well.</p><p>Thank you for reaching here.❤️😁🎃👀</p><p>Github repository:<br><a href="https://github.com/Mashood97/flutter_networking_background">https://github.com/Mashood97/flutter_networking_background</a></p><p>My LinkedIn Profile:<br><a href="https://pk.linkedin.com/in/mashood-siddiquie-5940a9168">https://pk.linkedin.com/in/mashood-siddiquie-5940a9168</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=95f6d196b28c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Clean Architecture & TDD With Flutter Part-2]]></title>
            <link>https://medium.com/@mashoodsidd97/clean-architecture-tdd-with-flutter-part-2-968c7fc52c5b?source=rss-5b67e4c2ebd6------2</link>
            <guid isPermaLink="false">https://medium.com/p/968c7fc52c5b</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Muhammad Mashood Siddiquie]]></dc:creator>
            <pubDate>Sat, 12 Mar 2022 12:24:23 GMT</pubDate>
            <atom:updated>2022-03-12T12:24:23.813Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*vWzD68bN2YAJGu4hKMw1xQ.png" /></figure><blockquote><strong>THE DOMAIN LAYER AND PROJECT SETUP ❤</strong></blockquote><p>Hello Everyone, I know it’s too late to post a second story on clean architecture with Flutter part-2, if you haven’t read about part-1 you can check it out here:</p><p><a href="https://medium.com/@mashoodsidd97/understanding-of-clean-architecture-in-your-flutter-apps-with-tdd-test-driven-development-e674429fa0d">Understanding of clean architecture in your flutter apps WITH TDD(TEST DRIVEN DEVELOPMENT)</a></p><p>So now as we have already learned about the basics of clean architecture, so today we will discuss one of the three pillars of clean architecture which is the “DOMAIN LAYER” if we talk generally about what’s a domain?</p><blockquote><strong>If we define a domain in simple English it’s an area of territory owned or controlled by a particular ruler or government.</strong></blockquote><p>So it means as government rules over specific territory so same while coding using clean architecture a domain represents the role of a government that manages the whole territory between the data and presentation layer. I hope you have a clear idea about what a domain layer does? Now Let’s Talk about what other parts does domain layer contains?</p><ol><li>Entity.</li><li>UseCases</li><li>Repository (Interface (Mixins) -OR- Abstract class)</li></ol><p>So let’s talk about the entity part:</p><blockquote><strong>ENTITY:</strong></blockquote><p>If we understand an entity in a very simple way, an Entity is a thing with distinct and independent existence which means it’s not dependent on any of our other layers i.e Data and presentation layer, but the other two layers depend upon an entity layer.</p><p>How does an entity declare in our code, let’s start doing some basic coding, first let me share the dependencies we needed to implement the clean architecture in our flutter app, copy and paste the below code into your pubspec.yaml file:</p><p><strong>dependencies:</strong></p><p>get:</p><p>equatable:</p><p>dartz:</p><p>internet_connection_checker:</p><p>dio:</p><p><strong>dev_dependencies:</strong></p><p>build_runner:</p><p>mocktail: ^0.1.4</p><p>Now run this command on terminal, “flutter pub get” to get all the packages.</p><p>Here we will use an opensource API for fetching posts using JSON placeholder API.</p><p><a href="https://jsonplaceholder.typicode.com/posts">https://jsonplaceholder.typicode.com/posts</a></p><p>Now let’s create a directory of “Domain” inside our lib directory and then create a subdirectory of “Entity” inside our domain directory and then create a file of “post_entity.dart” inside our entity directory.</p><h4>post_entity.dart:</h4><blockquote>import ‘package:equatable/equatable.dart’;</blockquote><blockquote>class PostEntity extends Equatable {</blockquote><blockquote>final int userId;</blockquote><blockquote>final int postId;</blockquote><blockquote>final String postTitle;</blockquote><blockquote>final String postBody;</blockquote><blockquote>const PostEntity({</blockquote><blockquote>required this.postBody,</blockquote><blockquote>required this.postId,</blockquote><blockquote>required this.postTitle,</blockquote><blockquote>required this.userId,</blockquote><blockquote>});</blockquote><blockquote>@override</blockquote><blockquote>List&lt;Object?&gt; get props =&gt; [</blockquote><blockquote>userId,</blockquote><blockquote>postBody,</blockquote><blockquote>postId,</blockquote><blockquote>postTitle,</blockquote><blockquote>];</blockquote><blockquote>}</blockquote><p>Now let’s understand why we are extending our entity with equatable as we know if we create two instances of the same object and compare them it’ll always return false, to solve this issue we used an equatable package to overcome this issue so we always get true whenever we compare the two instances of the same object.</p><p>Now as we understand let’s move towards a use-case. how to define a use-case in our code, first let’s try to understand a use-case in basic terms, let’s assume we are creating a simple <strong>TODO</strong> app, before creating a Todo app we may understand what are the core functionalities a todo app contains, we can add a task, get a task or tasks, delete a task or tasks and update a task. so these are the use cases of a TODO app, always remember we will define different classes of each use case, i.e get_tasks_usecase.dart, post_tasks_usecase.dart, delete_tasks_usecase.dart, edit_tasks_usecase.dart etc.</p><p>Now let’s create a folder inside lib/domain/usecase and then add a file inside use-case folder with the name “get_post_usecase.dart” and copy-paste the below code:</p><blockquote>import ‘package:dartz/dartz.dart’;</blockquote><blockquote>import ‘../../../../core/error/failures.dart’;</blockquote><blockquote>import ‘../../../../core/usecases/usecase_post.dart’;</blockquote><blockquote>import ‘../entities/post_entity.dart’;</blockquote><blockquote>import ‘../repositories/post_repository.dart’;</blockquote><blockquote>class GetPostsUseCase extends UseCase&lt;List&lt;PostEntity&gt;, NoParams&gt; {</blockquote><blockquote>final PostRepository postRepository;</blockquote><blockquote>GetPostsUseCase({required this.postRepository});</blockquote><blockquote>@override</blockquote><blockquote>Future&lt;Either&lt;Failure, List&lt;PostEntity&gt;&gt;&gt; call(NoParams params) async =&gt;</blockquote><blockquote>await postRepository.getPostsFromApi();</blockquote><blockquote>}</blockquote><p>Now when you paste the above, you may find errors and think what the hell is happening around in this class, what is either, what is a failure ? what is a call function, what is no params? from where do we get access to the repository.</p><p>So to talk about “either”, let’s welcome the functional programming here, an either is a type which takes a failure or a success result in its angular brackets, don’t worry we will define these classes below let’s just try to understand this either keyword, the left side of either angular bracket takes the failed case and the right side of angular brackets takes the success case, in a success case we will get our list of posts and in failure, we will return an error.</p><p>Now from where do, we get a Usecase class with angular brackets. We made a single abstract class of a use-case that takes a type and parameters if available for any API. Now let’s first create our first abstract class of a use case.</p><p>Create a new folder inside our lib folder with the name “Core”, this folder will contain all the core functionalities of our app. Now let’s create another folder inside core with the name use case and create a file with the name use_case.dart and copy-paste the below code:</p><blockquote>import ‘package:dartz/dartz.dart’;</blockquote><blockquote>import ‘package:equatable/equatable.dart’;</blockquote><blockquote>import ‘../error/failures.dart’;</blockquote><blockquote>// Parameters have to be put into a container object so that they can be</blockquote><blockquote>// included in this abstract base class method definition.</blockquote><blockquote>abstract class UseCase&lt;Type, Params&gt; {</blockquote><blockquote>Future&lt;Either&lt;Failure, Type&gt;&gt; call(Params params);</blockquote><blockquote>}</blockquote><blockquote>// This will be used by the code calling the use case whenever the use case</blockquote><blockquote>// doesn’t accept any parameters.</blockquote><blockquote>class NoParams extends Equatable {</blockquote><blockquote>@override</blockquote><blockquote>List&lt;Object?&gt; get props =&gt; [];</blockquote><blockquote>}</blockquote><p>Each use case inside the domain/use case folder will extend this use case class Here type is what we will get in return i.e for simplicity we will get a list of posts so that’s why we have passed List&lt;PostEntity&gt;, as we don’t have any params to be pass into our API so we have to define noParams class here so we don’t need to create this class, again and again, params doesn’t that only API parameters can be passed but a body can’t be, it’s just a generic name that we are passing params either in the type of body or API params.</p><p>Now we may see the error as we haven’t defined any failure class so let’s implement our failure class to catch exceptions.</p><p>let’s create another folder inside core with a name error and then create a file failure.dart inside it and copy-paste the below code:</p><blockquote>import ‘package:equatable/equatable.dart’;</blockquote><blockquote>import ‘http_exception.dart’;</blockquote><blockquote>abstract class Failure extends Equatable {</blockquote><blockquote>final List? properties = const &lt;dynamic&gt;[];</blockquote><blockquote>// If the subclasses have some properties, they’ll get passed to this constructor</blockquote><blockquote>// so that Equatable can perform value comparison.</blockquote><blockquote>@override</blockquote><blockquote>List&lt;Object?&gt; get props =&gt; [properties];</blockquote><blockquote>}</blockquote><blockquote>class HttpFailure extends Failure implements HttpException {</blockquote><blockquote>final String messages;</blockquote><blockquote>HttpFailure(this.messages);</blockquote><blockquote>@override</blockquote><blockquote>// TODO: implement message</blockquote><blockquote>String get message =&gt; messages;</blockquote><blockquote>}</blockquote><p>Now let’s create http_excpetion.dart inside the error folder and copy-paste the below code:</p><blockquote>class HttpException implements Exception {</blockquote><blockquote>final String message;</blockquote><blockquote>HttpException(this.message);</blockquote><blockquote>@override</blockquote><blockquote>String toString() {</blockquote><blockquote>return message;</blockquote><blockquote>}}</blockquote><p>As we have successfully implemented our failure class and let’s import it inside our use case.dart and get_post_usecase.dart class.</p><p>Now let’s back to our get_post_usecase.dart, as we may say many errors have gone but what about PostRepository, it’s still showing an error, so let’s create our post repository, concrete class.</p><blockquote>POST REPOSITORY:</blockquote><p>Create a folder inside the domain with the name “repository” and create a file inside with the name “post_repository” and then copy-paste the below code:</p><blockquote>import ‘package:dartz/dartz.dart’;</blockquote><blockquote>import ‘package:flutter_api_clean_architecture/core/error/failures.dart’;</blockquote><blockquote>import ‘package:flutter_api_clean_architecture/features/post/domain/entities/post_entity.dart’;</blockquote><blockquote>import ‘package:flutter_api_clean_architecture/utils/networking/http_exception.dart’;</blockquote><blockquote>abstract class PostRepository {</blockquote><blockquote>Future&lt;Either&lt;HttpFailure, List&lt;PostEntity&gt;&gt;&gt; getPostsFromApi();</blockquote><blockquote>}</blockquote><p>This is just a simple abstract class that contains all the methods related to our posts, in our app we are working on gettings posts, but we can similarly create other methods.</p><p>Now import this repository inside our domain/usecase/get_posts_usecase.dart.</p><p>This repository will be implemented in our data layer we will discuss it in the upcoming article.</p><blockquote><strong>HERE WE ARE DONE WITH THE DOMAIN LAYER.</strong></blockquote><p>WHAT’S NEXT ?</p><p>Now let’s move towards the most amazing part of this series the TDD (TEST DRIVEN DEVELOPMENT) using mocktail package.<br>Test cases are written by creating mock classes, in test-driven development approach we write test cases before we write our production code so may know that whatever code we are writing will work or not?</p><p>So now let’s move towards the test folder inside our project and create a folder with the name post and then create a folder inside the post with the name “Domain” and then create a folder with the name use cases and then create a file inside usecases with name get_post_usecase_test.dart and then copy-paste the below code:</p><blockquote>import ‘package:dartz/dartz.dart’;</blockquote><blockquote>import ‘package:flutter_api_clean_architecture/core/usecases/usecase_post.dart’;</blockquote><blockquote>import ‘package:flutter_api_clean_architecture/features/post/domain/entities/post_entity.dart’;</blockquote><blockquote>import ‘package:flutter_api_clean_architecture/features/post/domain/repositories/post_repository.dart’;</blockquote><blockquote>import ‘package:flutter_api_clean_architecture/features/post/domain/usecases/get_posts_usecase.dart’;</blockquote><blockquote>import ‘package:flutter_test/flutter_test.dart’;</blockquote><blockquote>import ‘package:mocktail/mocktail.dart’;</blockquote><blockquote>class MockPostRepository extends Mock implements PostRepository {}</blockquote><blockquote>void main() {</blockquote><blockquote>late GetPostsUseCase postsUseCase;</blockquote><blockquote>late MockPostRepository repository;</blockquote><blockquote>setUp(() {</blockquote><blockquote>repository = MockPostRepository();</blockquote><blockquote>postsUseCase = GetPostsUseCase(postRepository: repository);</blockquote><blockquote>});</blockquote><blockquote>List&lt;PostEntity&gt; posts = const [</blockquote><blockquote>PostEntity(</blockquote><blockquote>postBody:</blockquote><blockquote>“since he receives and receives the accepted consequences unencumbered, and when he finds any annoyance that as soon as the whole of our affairs is and they are a thing, it will happen to the architect”,</blockquote><blockquote>postId: 1,</blockquote><blockquote>postTitle: “great but easy”,</blockquote><blockquote>userId: 1,</blockquote><blockquote>),</blockquote><blockquote>PostEntity(</blockquote><blockquote>postBody:</blockquote><blockquote>“since he receives and receives the accepted consequences unencumbered, and when he finds any annoyance that as soon as the whole of our affairs is and they are a thing, it will happen to the architect”,</blockquote><blockquote>postId: 2,</blockquote><blockquote>postTitle: “great but easy”,</blockquote><blockquote>userId: 2,</blockquote><blockquote>),</blockquote><blockquote>];</blockquote><blockquote>test(“Should get all posts from server”, () async {</blockquote><blockquote>when(() =&gt; repository.getPostsFromApi())</blockquote><blockquote>.thenAnswer((_) async =&gt; Right(posts));</blockquote><blockquote>final result = await postsUseCase(NoParams());</blockquote><blockquote>expect(result, Right(posts));</blockquote><blockquote>verify(() =&gt; repository.getPostsFromApi());</blockquote><blockquote>verifyNoMoreInteractions(repository);</blockquote><blockquote>});</blockquote><blockquote>}</blockquote><p>Here let’s understand it in a simpler way liny by line:</p><p>so first let’s understand this line of code:</p><blockquote>class MockPostRepository extends Mock implements PostRepository {}</blockquote><p>so as I told you above, we will create mock classes for testing purposes. Here we made a simple mock repository class that will implement our post repository so we can check if our concrete repository works properly or not while fetching posts from the server.</p><p>Now let’s understand what’s setup(()); method, this method will be used to initialize the variables we created it works like our init state inside our flutter stateful widgets.</p><blockquote>List&lt;PostEntity&gt; posts = const [</blockquote><blockquote>PostEntity(</blockquote><blockquote>postBody:</blockquote><blockquote>“since he receives and receives the accepted consequences unencumbered, and when he finds any annoyance that as soon as the whole of our affairs is and they are a thing, it will happen to the architect”,</blockquote><blockquote>postId: 1,</blockquote><blockquote>postTitle: “great but easy”,</blockquote><blockquote>userId: 1,</blockquote><blockquote>),</blockquote><blockquote>PostEntity(</blockquote><blockquote>postBody:</blockquote><blockquote>“since he receives and receives the accepted consequences unencumbered, and when he finds any annoyance that as soon as the whole of our affairs is and they are a thing, it will happen to the architect”,</blockquote><blockquote>postId: 2,</blockquote><blockquote>postTitle: “great but easy”,</blockquote><blockquote>userId: 2,</blockquote><blockquote>),</blockquote><blockquote>];</blockquote><p>Here we define a mock result of a list of post entities as we will get a list of post entities in a success case so we just enter some dummy data of the list of post entities.</p><p>Now let’s move towards the test we have written:</p><blockquote>test(“Should get all posts from server”, () async {</blockquote><blockquote>when(() =&gt; repository.getPostsFromApi())</blockquote><blockquote>.thenAnswer((_) async =&gt; Right(posts));</blockquote><blockquote>final result = await postsUseCase(NoParams());</blockquote><blockquote>expect(result, Right(posts));</blockquote><blockquote>verify(() =&gt; repository.getPostsFromApi());</blockquote><blockquote>verifyNoMoreInteractions(repository);</blockquote><blockquote>});</blockquote><blockquote>}</blockquote><p>test(“title”,(){}); this is the basic function declaration of a test, where the first argument is the name of test cases i.e title and the other is the function where we will write our test case.<br>Now let’s move further,</p><p>when(()): when is as simple as we use it in our daily life. so here we call our getPostFromApi method from repository and wait for the answer from the API.<br>When having three types of generators:<br>thenReturn, thenAnswer, and thenThrow<br>All of them will contains an async function inside them, thenReturn will return something when we want to return something. thenAnswer will be use with getRequest when we want to check what will be the answer either it&#39;s right side of either or a left side of either method we defined earlier when we talked about functional programming.</p><p>Now inside when we hit our repository and thenAnswer will give us a Right(posts); which means when repository is successful then return the right side of posts.</p><p>Now let&#39;s understand this line of code:</p><blockquote>final result = await postsUseCase(NoParams());</blockquote><p>Here we call our posts use-case while passing noParams(); as we won’t pass anything to our API.</p><blockquote>expect(result, Right(posts));</blockquote><p>An expect function has the same meaning as our daily life usage, this will expect the answer of what we will get in result if we talk about success case it will return the Right(posts); so we pass Right(posts) here.</p><blockquote>verify(() =&gt; repository.getPostsFromApi());</blockquote><p>Then verify will verify that a method on a mock object was called with the given arguments.</p><p>Now when everything is done so we don’t want to interact with our repository again, so we use this function when we don’t want any interaction with any class.</p><blockquote>verifyNoMoreInteractions(repository);</blockquote><p>In our case, we don’t want to interact with our repository.</p><p>HUUHHHH, That’s really really long stuff we have gone through, but to achieve something we need to lose something, I know you guys might be fed up with such a long post as we have to set up the project and then discuss the domain layer, etc, while if you don’t then do write a comment so I can see who is encouraged to get to know about another pillar “THE DATA LAYER.”</p><blockquote>IF YOU LIKE THIS STORY THEN DO CLAP AND DON’T FORGET TO COMMENT AND SHARE THE STORY SO I MAY KNOW I AM HELPING THE FLUTTER DEVS COMMUNITY.</blockquote><p>THANK YOU AND HAVE A NICE WEEKEND ❤.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=968c7fc52c5b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding of clean architecture in your flutter apps WITH TDD(TEST DRIVEN DEVELOPMENT)]]></title>
            <link>https://medium.com/@mashoodsidd97/understanding-of-clean-architecture-in-your-flutter-apps-with-tdd-test-driven-development-e674429fa0d?source=rss-5b67e4c2ebd6------2</link>
            <guid isPermaLink="false">https://medium.com/p/e674429fa0d</guid>
            <category><![CDATA[blog]]></category>
            <category><![CDATA[google]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Muhammad Mashood Siddiquie]]></dc:creator>
            <pubDate>Mon, 08 Nov 2021 15:08:23 GMT</pubDate>
            <atom:updated>2021-11-08T15:08:23.859Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MPCahLMyBGD6cKOCS94syQ.png" /></figure><p>CLEAN ARCHITECTURE, as name suggest mostly devs thinks maybe a nightmare for them, It’s hard but it’s easy if it becomes handy and I promise after the series of blogs you will definitely gonna implement It in your next flutter big projects.</p><p>Mostly developer’s around the world once think what shall we do to make our code maintainable, scalable for future purpose. Mostly we developer’s right good code that works perfectly great, but maintaining that code after a long time gets hectic for us as we don’t work on creating a good architecture for our apps which makes code tightly coupled or hardly to understand again, that’s where we need to think what shall we do to make our code more maintainable, divide into different layers etc, that’s where “CLEAN ARCHITECTURE” comes handy.</p><p>WHAT IS TDD?</p><blockquote>TDD stands for Test driven development, which means before writing our production code, we write code in parallel with our tests, if a test pass then our production will also be pass.</blockquote><p><strong>BASIC INTRODUCTION TO CLEAN ARCHITECTURE:<br></strong> <br> Clean architecture was introduced by Robert Martin, broadly known as “UNCLE BOB”. He has written multiple books for coding and best practices. He is most popular for his considerations on “CLEAN CODE”.<br> <br> Clean architecture is divided into three layers:</p><ul><li>DATA</li><li>DOMAIN</li><li>PRESENTATION<br> <br> <br> Lets talk about the Domain First, what is a domain layer, domain layer is categorized into three sub folders:</li><li>Entity</li><li>Use case</li><li>Repository<br> <br> <br> <br> ENTITY: Entity is something which defines business set of rules.<br> <br> USE CASE: Use case is something which defines what type on functionality each business logic can have, Let’s take example of a simple todo app. What business functionality are included in todo app, we can “ADD” task,”Get” tasks,”UPDATE” tasks, “DELETE” tasks, the word inside inverted commas are our use cases’ hope it’s cleared what is a use case.<br> <br> REPOSITORY: This is an interface/abstract class with declaration of a function not implementation of a function, this concrete/repository created here will be implement inside our data layer.<br> <br> <br> DATA LAYER:<br> A data layer consist of there sub folders,</li><li>Datasources.</li><li>Models.</li><li>Repository<br> <br> <br> DATA-SOURCES: Data source consist of two folders, remote and local, here we define app logics depending upon wether we need data from the api or from our mobile local storage.<br> <br> MODELS: This model is only respective to our data layer, the difference between a model and entity is, model define here contain fromJson and toJson method whereas entity doesn’t, model extends entity but entity can not extend a model, this makes separation of layers and easy to maintain code.<br> <br> REPOSITORY: Here we implement the repository we define inside our domain layer, here we take remote and local datasource as our argument also we catch exceptions as early as possible rather then inside our presentation layer.<br> <br> <br> PRESENTATION LAYER:<br> It consist of our state management and UI presentation of our app.<br> <br><br> I hope so you have understand the basic of clean architecture for flutter apps.<br> <br> <br> What will be the project structure of flutter application using clean architecture, let’s see here:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tgXqe39sm_F31CWZaeHnXQ.png" /></figure><p>DON’T WORRY ABOUT THE OTHER FOLDERS DEFINE HERE, WE WILL DISCUSS THIS ON OUR NEXT ARTICLE.<br> <br> This is just a beginning to learn something new and I wish you will enjoy the whole series of clean architecture in flutter app.<br> <br> <br> <br> In the next blog we will discuss about dependencies and other folder structures defined here, I promise you will love it and start implementing the clean architecture in your next flutter apps project.<br> <br> <br> Thank you for reading this blogpost, I hope you like this and if you like this then surely do like this post so I may know I am helping other people to write and practice good code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e674429fa0d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Streams with ListView and Smooth Scrolling]]></title>
            <link>https://medium.com/analytics-vidhya/streams-with-listview-and-smooth-scrolling-546158e1b3c5?source=rss-5b67e4c2ebd6------2</link>
            <guid isPermaLink="false">https://medium.com/p/546158e1b3c5</guid>
            <category><![CDATA[apple]]></category>
            <category><![CDATA[google]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[microsoft]]></category>
            <category><![CDATA[facebook]]></category>
            <dc:creator><![CDATA[Muhammad Mashood Siddiquie]]></dc:creator>
            <pubDate>Fri, 26 Jun 2020 17:56:45 GMT</pubDate>
            <atom:updated>2020-06-27T16:10:33.640Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello Everyone today we’ll be discussing how to use streams with listview to build items when users reached that particular position of the item, We will be using JSON Place Holder API of Photos containing 5000 images, we will learn at the end of the article that how to have smooth scrolling using stream controller and listview, so without wasting time let’s start ❤</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/311/1*zYelGAikHv77wdicCKU9qg.png" /></figure><p>Create a new flutter project with the name “flutter_stream_project” and make sure you have this project structure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*YnHcXG8jL5z3ZCZCc5dl7A.png" /></figure><p>Now first create a model class with name “Photo” and copy-paste the following code:</p><pre><strong>class </strong>Photo {<br>  <strong>final </strong>String <strong>title</strong>;<br>  <strong>final </strong>String <strong>url</strong>;<br><br>  Photo.fromJsonMap(Map map)<br>      : <strong>title </strong>= map[<strong>&#39;title&#39;</strong>],<br>        <strong>url </strong>= map[<strong>&#39;url&#39;</strong>];<br>}</pre><p>As we want only the image URL and title from the JSON place holder API.</p><p>fromJsonMap is to map the JSON data into a map.</p><p>Now let’s create a new file inside screens folder with name PhotoList, and copy-paste the following code:</p><pre><strong>import &#39;dart:async&#39;</strong>;<br><br><strong>import &#39;package:flutter/material.dart&#39;</strong>;<br><strong>import &#39;package:flutterstreamproject/models/Photo.dart&#39;</strong>;<br><strong>import &#39;dart:convert&#39;</strong>;<br><br><strong>import &#39;package:http/http.dart&#39; as </strong>http;<br><strong>class </strong>PhotoList <strong>extends </strong>StatefulWidget {<br>  @override<br>  _PhotoListState createState() =&gt; _PhotoListState();<br>}<br><br><strong>class </strong>_PhotoListState <strong>extends </strong>State&lt;PhotoList&gt; {<br>  StreamController&lt;Photo&gt; <strong>_streamController</strong>;<br>  List&lt;Photo&gt; <strong>list </strong>= [];<br><br>  @override<br>  <strong>void </strong>initState() {<br>    <strong>super</strong>.initState();<br>    <strong>_streamController </strong>= StreamController.broadcast();<br><br>    <strong>_streamController</strong>.<strong>stream</strong>.listen((p) =&gt; setState(() =&gt; <strong>list</strong>.add(p)));<br><br>    load(<strong>_streamController</strong>);<br>  }<br><br>  load(StreamController&lt;Photo&gt; sc) <strong>async </strong>{<br>    String url = <strong>&quot;https://jsonplaceholder.typicode.com/photos&quot;</strong>;<br>    <strong>var </strong>client = <strong>new </strong>http.Client();<br><br>    <strong>var </strong>req = <strong>new </strong>http.Request(<strong>&#39;get&#39;</strong>, Uri.<em>parse</em>(url));<br><br>    <strong>var </strong>streamedRes = <strong>await </strong>client.send(req);<br><br>    streamedRes.<strong>stream<br>        </strong>.transform(utf8.<strong>decoder</strong>)<br>        .transform(json.<strong>decoder</strong>)<br>        .expand((e) =&gt; e)<br>        .map((map) =&gt; Photo.fromJsonMap(map))<br>        .pipe(sc);<br>  }<br><br>  @override<br>  <strong>void </strong>dispose() {<br>    <strong>super</strong>.dispose();<br>    <strong>_streamController</strong>?.close();<br>    <strong>_streamController </strong>= <strong>null</strong>;<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    <strong>return </strong>Scaffold(<br>      appBar: AppBar(<br>        title: Text(<strong>&quot;Photo Streams&quot;</strong>),<br>      ),<br>      body: Center(<br>        child: ListView.builder(<br><em>//          scrollDirection: Axis.horizontal,<br><br>          </em>itemBuilder: (BuildContext context, int index) =&gt; _makeElement(index),<br>          itemCount: <strong>list</strong>.<strong>length</strong>,<br>        ),<br>      ),<br>    );<br>  }<br><br>  Widget _makeElement(int index) {<br>    <strong>if </strong>(index &gt;= <strong>list</strong>.<strong>length</strong>) {<br>      <strong>return null</strong>;<br>    }<br><br>    <strong>return </strong>Container(<br>        padding: EdgeInsets.all(5.0),<br>        child: Padding(<br>          padding: EdgeInsets.only(top: 200.0),<br>          child: Column(<br>            children: &lt;Widget&gt;[<br>              Image.network(<strong>list</strong>[index].<strong>url</strong>, width: 150.0, height: 150.0),<br>              Text(<strong>list</strong>[index].<strong>title</strong>),<br>            ],<br>          ),<br>        ));<br>  }<br>}</pre><p>Here we create a stream controller as a stream controller is a generic type so we need to define the datatype inside &lt;&gt; angular brackets, as we want the photo data so we pass the photo model inside angular brackets, now to initialize the stream controller we need the init state now we broadcast the stream controller i.e we subscribe to the stream controller for every change and after that we use listen method and pass p which can anything but related to the photo model class we passed in stream controller now we want changes whenever a new item is added in a list so we add the p in our list which is a photo model and then we create a method load with args as stream controller, now a load method we call our API with a get request and map the result of the stream with the help of Photo model class fromJsonMap method and then we call the dispose method to dispose all the stream controller and pass null also so that if we navigate to another screen etc so it wont take any memory or doesn&#39;t cause any memory leakage.</p><p>Now we create a simple UI with listview.builder, in which item builder we create a method makeElement which have a container and having a child as column and pass the Network image and text widget.</p><p>Now let’s run the app the UI won&#39;t be great but you’ll notice how the scrolling becomes so much smoother with this approach and also we subscribe to the changes whenever a new item added the stream controller change method will be call and make a change sudden.</p><p>I hope you understand it that how to use stream controller with listview and API, Wish to see you guys commenting out and giving a clap on this article.</p><p>Thank you ❤.</p><p>Github Repo link of sample project :</p><p><a href="https://github.com/Mashood97/flutter_stream_project">https://github.com/Mashood97/flutter_stream_project</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=546158e1b3c5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/streams-with-listview-and-smooth-scrolling-546158e1b3c5">Streams with ListView and Smooth Scrolling</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Node JS, Express, SQL Server, and Flutter Together Flirting.]]></title>
            <link>https://medium.com/analytics-vidhya/node-js-express-sql-server-and-flutter-together-flirting-a7e57bccb697?source=rss-5b67e4c2ebd6------2</link>
            <guid isPermaLink="false">https://medium.com/p/a7e57bccb697</guid>
            <category><![CDATA[facebook]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[google]]></category>
            <dc:creator><![CDATA[Muhammad Mashood Siddiquie]]></dc:creator>
            <pubDate>Fri, 19 Jun 2020 04:59:00 GMT</pubDate>
            <atom:updated>2020-06-19T13:36:09.173Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello, Today we’ll be discussing how to create a restful API with Node JS and SQL server using store procedure and use it in flutter apps.</p><p>First, we will create our database and store procedure in SQL server:</p><pre>Create database loginSignup<br><br>use loginSignup<br><br><br><br>Create table signupUser(<br>userId int primary key identity(1,1),<br>userEmail nvarchar(50),<br>userPassword nvarchar(max)<br>);<br></pre><pre>--Signup Store Procedure.<br>Create proc spSignupUser<br>@userEmail nvarchar(50),<br>@userPassword nvarchar(max),<br>@responseMessage varchar(50) output<br><br>as<br>begin<br><strong>set </strong>nocount on;<br><br>begin <strong>try<br><br></strong>IF EXISTS (Select userEmail from signupUser where userEmail = @userEmail)<br>BEGIN<br>set @responseMessage = <strong>&#39;Failed&#39;</strong>;<br>END<br>ELSE<br>BEGIN<br>Insert into signupUser<br>Output Inserted.userId,@userEmail as Email,@userPassword as Password<br>values(@userEmail,@userPassword);<br><br>set @responseMessage = <strong>&#39;Success&#39;</strong>;<br>END<br>end <strong>try<br></strong>begin <strong>catch<br></strong>set @responseMessage = ERROR_MESSAGE();<br>end <strong>catch<br></strong>end<br><br><br>Declare @userEmail nvarchar(50), @userPassword nvarchar(50),@responseMessage varchar(50)<br>Exec spSignupUser @userEmail=<strong>&#39;mashood21@gmail.com&#39;</strong>,@userPassword = <strong>&#39;</strong>$<strong>2b</strong>$<strong>10</strong>$fZe7hjws5AzGUa5J0yj2Le1fLAf3oV5SAEee3nneu4VUGEsVIAf82<strong>&#39;</strong>,@responseMessage = @responseMessage output<br>print @responseMessage;</pre><pre>--Signin Store Proc<br>Create proc spSignInUser<br>@userEmail nvarchar(50),<br>@userPassword nvarchar(max),<br>@responseMessage varchar(50) output<br><br>as<br>begin<br><strong>set </strong>nocount on;<br>begin <strong>try<br></strong>IF EXISTS (Select userEmail,userPassword from signupUser where userEmail = @userEmail and userPassword = @userPassword)<br>begin<br>Select userEmail,userPassword from signupUser where userEmail = @userEmail and userPassword = @userPassword<br>set @responseMessage = <strong>&#39;Success&#39;</strong>;<br>end<br><strong>else<br></strong>begin<br>set @responseMessage = <strong>&#39;Auth Failed&#39;</strong>;<br>end<br>end <strong>try<br><br></strong>begin <strong>catch<br></strong>set @responseMessage = <strong>&#39;Failed&#39;<br></strong>end <strong>catch<br></strong>end<br><br><br>Declare @userEmail nvarchar(50), @userPassword nvarchar(max), @responseMessage varchar(50)<br>EXEC spSignInUser @userEmail = <strong>&#39;mashood1@gmail.com&#39;</strong>,@userPassword=<strong>&#39;Passwords&#39;</strong>, @responseMessage = @responseMessage output<br>print @responseMessage</pre><p>We will not handle any encryption or decrypting from the backend as we will do it through node js.</p><p>You need to have node install on your pc.</p><p>First, let’s create a project for Node js, so goto any directory where you wanna create a project, create a folder with no space between the name of the folder and then go inside that folder and then inside address bar or title bar of the new folder, write cmd and press enter, then go through these steps:</p><ol><li>npm init</li><li>leave package name same and press enter, same for version leave it and press enter</li><li>Write a meaningful description i.e A node js restful API with SQL, press enter</li><li>Then for entry point press enter, leave test command blank press enter, if you&#39;re a git repo link paste in git repository otherwise press enter while leaving it blank</li><li>Write a keyword i.e Node js Restful API.</li><li>Then write author name i.e your name.</li><li>Then press the enter for a license, and enter yes for IS THIS OK?.</li><li>Then write code . to open the project in vs code.</li></ol><p>You’ve successfully set up the project.</p><p>Your project structure should be like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/253/1*3I6uy4jHCprel7tOLVC6gA.png" /></figure><p>Now open a terminal and install these dependencies one by one:</p><ol><li>npm install express</li><li>npm install mssql</li><li>npm install morgan</li><li>npm install body-parser</li><li>npm install bcrypt</li><li>npm install jsonwebtoken</li><li>npm install — only-dev nodemon (‘ — ‘ is double dash together).</li></ol><p>After Installing these packages, go to package.json, inside scripts, copy paste the following code:</p><pre><strong>,&quot;serve&quot;</strong>: <strong>&quot;nodemon server.js&quot;</strong></pre><p>After Installing the packages let’s set up the first settings.js remember you’ve set up the SQL server authentication.</p><pre>exports.dbConfig = {<br><strong>&#39;user&#39;</strong>: <strong>&#39;Your User name&#39;</strong>,<br><strong>&#39;password&#39;</strong>: <strong>&#39;Your password of sql&#39;</strong>,<br><strong>&#39;server&#39;</strong>: <strong>&#39;Your Server name&#39;</strong>,<br><strong>&#39;database&#39;</strong>: <strong>&#39;</strong>loginSignup<strong>&#39;</strong>,<br>options: {<br>enableArithAbort: <strong>false</strong>,<br>encrypt: <strong>false</strong>,<br>}<br>};</pre><ol><li>user: Enter your username of SQL, default username is ‘sa’.</li></ol><p>2. password: The password of your SQL server.</p><p>3. server: Your instance name of the SQL server.</p><p>4. database: Enter the name of the database you want to use.</p><p>we already export this file so we don’t need to export it below the code.</p><p>Now let’s create a server inside server.js file:</p><pre><strong>const </strong>http = require(<strong>&#39;http&#39;</strong>);<br><strong>const </strong>port = process.env.port || 3000;<br><strong>const </strong>app = require(<strong>&#39;./app&#39;</strong>);<br><br><strong>const </strong>server = http.createServer(app);<br><br>server.listen(port);</pre><p>We use the HTTP package here for network calls for API.</p><p>the port is getting from your environment or you can use hardcoded one i.e if unable to get the port from the environment then use 3000 as the port for localhost.</p><p>the app is the app.js file which we’ll cover soon, http.createServer(app) is where all the magic is done, it takes all the code and routes, etc from app.js and creates a localhost server for us.</p><p>server.listen(port) means to listen to the port we get either from an environment variable or hardcoded 3000.</p><p>Now let’s go to db.js file and copy-paste the following code:</p><pre><strong>var </strong>sqlDb = require(<strong>&#39;mssql&#39;</strong>);<br><strong>var </strong>sqlDbSettings = require(<strong>&#39;../settings&#39;</strong>);<br><br><strong>const </strong>poolPromise = <strong>new </strong>sqlDb.ConnectionPool(sqlDbSettings.dbConfig)<br>    .connect()<br>    .then(pool =&gt; {<br>console.log(<strong>&#39;Connected to MSSQL&#39;</strong>)<br><strong>return </strong>pool<br>})<br>    .<strong>catch</strong>(err =&gt; console.log(<strong>&#39;Database Connection Failed! Bad Config: &#39;</strong>, err));<br><br>module.exports = {<br>sqlDb, poolPromise<br>}</pre><p>Here we are using mssql package we installed and import the settings we created.</p><p>Now we are creating a connection with the SQL server as a singleton class so we can just import it and use it anywhere rather than creating a request pool again and again which is not a good idea to create pool again and again. Here I am exporting the SQL databaseand pool promise it’s another way of exporting.</p><p>Now let’s go to our user.js file inside API/routes and import these files:</p><pre><strong>const </strong>express = require(<strong>&#39;express&#39;</strong>);<br><strong>const </strong>router = express.Router();<br><strong>const </strong>db = require(<strong>&#39;../../core/db&#39;</strong>);<br><strong>const </strong>sql = require(<strong>&#39;mssql&#39;</strong>);<br><strong>const </strong>bcrypt = require(<strong>&#39;bcrypt&#39;</strong>);<br><strong>const </strong>jwt = require(<strong>&#39;jsonwebtoken&#39;</strong>);</pre><p>express is the node package which makes it easy for us to create API and router makes us access to get the different route of API i.e GET Request, POST Request, PUT Request. We will create only a post requests for signup and sign in.</p><p>Now copy-paste this code after importing the above packages.</p><pre>async function getpool() {<br>  <strong>const </strong>pool = await db.poolPromise;<br>  <strong>const </strong>result = await pool.request();<br>  <strong>return </strong>result;<br>}</pre><p>In this method, we run the asynchronous method to create a pool and send the query or store proc as a request and get the data back, creating a connection between SQL and node.</p><pre>router.post(<strong>&#39;/signup&#39;</strong>, (req, res, next) =&gt; {<br><br><strong>if </strong>(req.body.userEmail != <strong>null </strong>&amp;&amp; req.body.userPassword != <strong>null</strong>) {<br>bcrypt.hash(req.body.userPassword, 10, <strong>async </strong>(err, hash) =&gt; {<br><strong>if </strong>(err) {<br><strong>return </strong>res.status(500).json({<br>error: {<br>message: err<br>}<br>});<br>}<br><strong>else </strong>{<br><br><strong>const </strong>result = <strong>await </strong>getpool();<br>result.<br>input(<strong>&#39;userEmail&#39;</strong>, sql.NVarChar(50), req.body.userEmail)<br>    .input(<strong>&#39;userPassword&#39;</strong>, sql.NVarChar(sql.MAX), hash)<br>    .output(<strong>&#39;responseMessage&#39;</strong>, sql.VarChar(50))<br>    .execute(<strong>&#39;spSignupUser&#39;</strong>, function (err, data) {<br><strong>if </strong>(err) {<br>res.status(500).json({<br>error: {<br>message: err<br>}<br>});<br>}<br><strong>else </strong>{<br>console.log(data);<br><strong>if </strong>(data[<strong>&#39;output&#39;</strong>][<strong>&#39;responseMessage&#39;</strong>] == <strong>&#39;Failed&#39;</strong>) {<br>res.status(404).json({<br>error: {<br>message: <strong>&#39;User Exist&#39;<br></strong>}<br>});<br>}<br><strong>else </strong>{<br>res.status(201).json({<br>message: <strong>&#39;Success&#39;</strong>,<br>data: {<br>email: req.body.userEmail,<br>password: hash,<br>userId: data[<strong>&#39;recordset&#39;</strong>][0][<strong>&#39;userId&#39;</strong>]<br>}<br>});<br>}<br>}<br>});<br>}<br><br>});<br>}<br><strong>else </strong>{<br><strong>return </strong>res.status(404).json({<br>error: {<br>message: <strong>&#39;not found&#39;<br></strong>}<br>});<br>}<br><br>});</pre><p>Here we are creating a post request for sign up, I’ll explain why we are using /signup when we will be back in the app.js class.</p><p>Here we are checking as its the post request so we need to pass the body to the API, so here first we are checking that Email and password are not null,</p><p>we are using bcrypt package to hash the password, bcrypt first argument is the plaintext, the second arg is Salt i.e how many salting keywords we want to generate and the third arg is a function, it’s not necessary to have an async function here but as per my requirement I want to access the pool so I made it async here. Inside the bcrypt function, I check if there is an error while sending the request, then return the error with status code 500, else if there is no error, then get the pool request for accessing the database.</p><p>Now the main part is here, we are accessing this code:</p><pre>result.<br>input(<strong>&#39;userEmail&#39;</strong>, sql.NVarChar(50), req.body.userEmail)<br>    .input(<strong>&#39;userPassword&#39;</strong>, sql.NVarChar(sql.MAX), hash)<br>    .output(<strong>&#39;responseMessage&#39;</strong>, sql.VarChar(50))<br>    .execute(<strong>&#39;spSignupUser&#39;</strong>, function (err, data) {<br><strong>if </strong>(err) {<br>res.status(500).json({<br>error: {<br>message: err<br>}<br>});<br>}<br><strong>else </strong>{<br>console.log(data);<br><strong>if </strong>(data[<strong>&#39;output&#39;</strong>][<strong>&#39;responseMessage&#39;</strong>] == <strong>&#39;Failed&#39;</strong>) {<br>res.status(404).json({<br>error: {<br>message: <strong>&#39;User Exist&#39;<br></strong>}<br>});<br>}<br><strong>else </strong>{<br>res.status(201).json({<br>message: <strong>&#39;Success&#39;</strong>,<br>data: {<br>email: req.body.userEmail,<br>password: hash,<br>userId: data[<strong>&#39;recordset&#39;</strong>][0][<strong>&#39;userId&#39;</strong>]<br>}<br>});<br>}<br>}<br>});<br>}<br><br>});<br>}</pre><p>We use this for running a store procedure, i.e take some input and you may have some output as well, input means what user gonna enter in it and output to share the result, input takes three arguments:</p><ol><li>Column name you define in SQL store proc.</li><li>The data type of the column.</li><li>The text you’re entering.</li></ol><p>Execute function execute the store procedure, pass the name of your store procedure, and the second arg is a function that returns an error and a data object. We are again checking if we get err then return error with status code 500 else if we don&#39;t get any error, then in else part, we are checking if our output of store procedure returns failed, so we send a 404 request that user exists. Now if we don&#39;t get any error or failed then we will return the status code of 201 with the data, an email will be from the req.body.userEmail , the password will be the hash password we do with bcrypt and user id will be accessible from the data object we get from executing the store procedure.</p><p>Now We will create API for our Sign in.</p><pre>router.post(<strong>&#39;/signin&#39;</strong>, async (req, res, next) =&gt; {<br><strong>if </strong>(req.body.userEmail != <strong>null </strong>&amp;&amp; req.body.userPassword != <strong>null</strong>) {<br><br><strong>const </strong>result = await getpool();<br>result.<br>input(<strong>&#39;userEmail&#39;</strong>, sql.NVarChar(50), req.body.userEmail)<br>.input(<strong>&#39;userPassword&#39;</strong>, sql.NVarChar(sql.MAX), req.body.userPassword)<br>.output(<strong>&#39;responseMessage&#39;</strong>, sql.VarChar(50))<br>.execute(<strong>&#39;spSignInUser&#39;</strong>, function (err, data) {<br>  <strong>if </strong>(err) {<br>    res.status(500).json({<br>      error:<br>      {<br>        message: err<br>      }<br>    });<br>  }<br>  <strong>else </strong>{<br>    result.query(<strong>&#39;Select * from signupUser where userEmail=&#39; </strong>+ <strong>&quot;&#39;&quot; </strong>+ req.body.userEmail + <strong>&quot;&#39;&quot;</strong>).then(function (datas) {<br><br>    console.log(datas[<strong>&#39;recordset&#39;</strong>][0][<strong>&#39;userEmail&#39;</strong>] + <strong>&#39;RESULTS&#39;</strong>);<br>    bcrypt.compare(req.body.userPassword, datas[<strong>&#39;recordset&#39;</strong>][0][<strong>&#39;userPassword&#39;</strong>], (err, results) =&gt; {<br>    <strong>if </strong>(err) {<br>    <strong>return </strong>res.status(500).json({<br>    error:<br>    {<br>    message: err<br>    }<br>    });<br>    } <strong>if </strong>(results) {<br>    <strong>const </strong>token = jwt.sign({<br>    email: datas[<strong>&#39;recordset&#39;</strong>][0][<strong>&#39;userEmail&#39;</strong>],<br>    userId: datas[<strong>&#39;recordset&#39;</strong>][0][<strong>&#39;userId&#39;</strong>],<br>    },<br>    process.env.JWT_KEY,<br>    {<br>    expiresIn: <strong>&#39;1h&#39;<br>    </strong>},<br>    );<br>    console.log(results);<br>    <strong>return </strong>res.status(200).json({<br>    message: <strong>&#39;success&#39;</strong>,<br>    userdata: datas[<strong>&#39;recordset&#39;</strong>],<br>    access_token: token,<br>    });<br>    }<br>    <strong>return </strong>res.status(404).json({<br>    error:<br>    {<br>    message: <strong>&#39;Auth Failed&#39;<br>    </strong>}<br>    });<br>    });<br>    }).<strong>catch</strong>(function (err) {<br>  <strong>return </strong>res.status(500).json({<br>  error:<br>  {<br>  message: <strong>&#39;Auth Failed&#39;<br>  </strong>}<br>  });<br>  });<br>}<br><br>});<br>}<br><strong>else </strong>{<br><strong>return </strong>res.status(422).json({<br>error:<br>{<br>message: <strong>&#39;Parameter Not Supplied&#39;<br></strong>}<br>});<br>}<br>});</pre><p>Most of the code is same as above, we will focus on else part as it is necessary to understand what’s going on there, so let&#39;s talk about it:</p><pre><strong>else </strong>{<br>    result.query(<strong>&#39;Select * from signupUser where userEmail=&#39; </strong>+ <strong>&quot;&#39;&quot; </strong>+ req.body.userEmail + <strong>&quot;&#39;&quot;</strong>).then(function (datas) {<br><br>    console.log(datas[<strong>&#39;recordset&#39;</strong>][0][<strong>&#39;userEmail&#39;</strong>] + <strong>&#39;RESULTS&#39;</strong>);<br>    bcrypt.compare(req.body.userPassword, datas[<strong>&#39;recordset&#39;</strong>][0][<strong>&#39;userPassword&#39;</strong>], (err, results) =&gt; {<br>    <strong>if </strong>(err) {<br>    <strong>return </strong>res.status(500).json({<br>    error:<br>    {<br>    message: err<br>    }<br>    });<br>    } <strong>if </strong>(results) {<br>    <strong>const </strong>token = jwt.sign({<br>    email: datas[<strong>&#39;recordset&#39;</strong>][0][<strong>&#39;userEmail&#39;</strong>],<br>    userId: datas[<strong>&#39;recordset&#39;</strong>][0][<strong>&#39;userId&#39;</strong>],<br>    },<br>    process.env.JWT_KEY,<br>    {<br>    expiresIn: <strong>&#39;1h&#39;<br>    </strong>},<br>    );<br>    console.log(results);<br>    <strong>return </strong>res.status(200).json({<br>    message: <strong>&#39;success&#39;</strong>,<br>    userdata: datas[<strong>&#39;recordset&#39;</strong>],<br>    access_token: token,<br>    });<br>    }<br>    <strong>return </strong>res.status(404).json({<br>    error:<br>    {<br>    message: <strong>&#39;Auth Failed&#39;<br>    </strong>}<br>    });<br>    });<br>    }).<strong>catch</strong>(function (err) {<br>  <strong>return </strong>res.status(500).json({<br>  error:<br>  {<br>  message: <strong>&#39;No Data Found&#39;<br>  </strong>}<br>  });<br>  });<br>}</pre><p>In else part we are running a query, get all the data from the signup user where the email is equal to enter email in the body of API. After checking bcrypt.compare is a function that compares the entered password with your hash, as query returns all data to us according to the user email, we get access of that datas object which returns a recordset as an array in which we access the zero elements and get the user email or userPassword, it returns a function of error and results if there’s an error then written the 500 status code with error else if results which of type boolean, if its result that means if it&#39;s true then we create a token using JSON web token, jwt.sign is a function to create automatically token for us, inside token we pass our email and userId, then we access JWT_KEY, which we created our own, then we have an options object which takes multiple parameters, we will be using expiresIn: ‘1h’ for security purpose, then returns the data with 200 status code with customizing data of our own. now we also return Auth Failed after this, it will work when we are unable to compare the password and didn&#39;t make it into the above statements then it will trigger this function.</p><p>Now let’s go to our App.js file:</p><pre><strong>const </strong>express = require(<strong>&#39;express&#39;</strong>);<br><strong>const </strong>app = express();<br><strong>const </strong>morgan = require(<strong>&#39;morgan&#39;</strong>);<br><strong>const </strong>bodyParser = require(<strong>&#39;body-parser&#39;</strong>);<br><strong>const </strong>userRoutes = require(<strong>&#39;./api/routes/user&#39;</strong>);<br><br><br><br>app.use(morgan(<strong>&#39;dev&#39;</strong>));<br>app.use(bodyParser.urlencoded({ extended: <strong>false </strong>}));<br>app.use(bodyParser.json());<br><br><br>app.use((req, res, next) =&gt; {<br>res.header(<strong>&#39;Access-Control-Allow-Origin&#39;</strong>, <strong>&#39;*&#39;</strong>);<br>res.header(<strong>&#39;Access-Control-Allow-Headers&#39;</strong>,<br><strong>&#39;Origin, X-Requested-With, Content-Type, Accept, Authorization&#39;<br></strong>);<br><strong>if </strong>(req.method === <strong>&#39;OPTIONS&#39;</strong>) {<br>res.header(<strong>&#39;Access-Control-Allow-Methods&#39;</strong>, <strong>&#39;PUT, POST, DELETE, PATCH, GET&#39;</strong>);<br><strong>return </strong>res.status(200).json({});<br>}<br>next(); <em>// this will not block the incoming request;<br><br></em>});<br><br><br><em>//setup routes here:<br></em>app.use(<strong>&#39;/user&#39;</strong>, userRoutes);<br><br><br><em>//above throw error and whenever an error is throw this method will be triggered<br><br></em>app.use((req, res, next) =&gt; {<br><strong>const </strong>error = <strong>new </strong>Error(<strong>&#39;Not Found&#39;</strong>);<br>error.status = 404;<br>next(error);<br>});<br><br><br>app.use((error, req, res, next) =&gt; {<br>res.status(error.status || 500).json({<br>error: {<br>message: error.message,<br>}<br>});<br>});<br><br><br>module.exports = app;</pre><p>Here we are using some packages we installed and some files we created on our own i.e user routes, morgan is used for consoling the data of our API when we hit it. body-parser is used to encode our API into JSON format, we can’t pass form data into this API. Now we are using headers that allow all types of origin to access, we can also set our own URL for origin purpose. next(); is used to don&#39;t stop the API call.</p><p>Now we set up the User route as we want to run this route i.e make signup or signing request, after that if we didn&#39;t make it into user routes then we create an error not found in one function and trigger the next function to send that error.</p><p>In the last, we export the app.js file to use it in server.js.</p><p>Now one thing we have missed is JWT_KEY, create a file inside the root folder with name nodemon.json and copy-paste the following code inside it:</p><pre>{<br><strong>&quot;env&quot;</strong>:{<br><strong>&quot;JWT_KEY&quot;</strong>: <strong>&quot;secret&quot;<br></strong>}<br>}</pre><p>Now let’s start our server:</p><p>open terminal and write npm run serve, it’ll start your server with localhost:3000 and for testing purposes we will use postman to post our request.</p><p>Now first we will run the signup request to create a user:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/933/1*TX40gQJSr8Am7iiWZVdp-Q.png" /></figure><p>First setup the header of content-type as application.json.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/937/1*tN0AvA6KLDWDAEj_UM-v1g.png" /></figure><p>Now create the body as same as I have defined and then hit send button you’ll get this output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*U9_vLIMbwRqvFX0h2k3pNA.png" /></figure><p>You get success message and data object of user info.</p><p>Now if hit send button again we same data we will get this output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*5h5wAKVjy2tWDO2j9W-jig.png" /></figure><p>Now if we don&#39;t supply a parameter then we will get parameter not supplied.</p><p>Now let’s run our sign-in API:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/921/1*TgLemXwd7-RJ9dirdVXMxw.png" /></figure><p>Now we use the same email and password we get this success message and user data.</p><p>If we pass wrong password or email we will get Auth failed :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*fSTnvzJ9N5vBfyd-6cd_ZQ.png" /></figure><p>If we don&#39;t supply any parameter then we will get Parameter not Supplied.</p><p>Now let’s create a fluter project we will only console the data we won’t making any UI for this testing purpose, as my goal was to make you guys understand about node js API and SQL and integrate with flutter.</p><p>Create a flutter project with name login_signup_node:</p><p>Add these dependencies in pubspec.yaml:</p><pre><strong>http</strong>:<br><strong>provider</strong>:</pre><p>and pub get the dependencies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/309/1*x9AJWcpKUQw3JMd30IwbOw.png" /></figure><p>You must have a project structure like this.</p><p>Inside the screen, folder creates a homepage. dart file and copy-paste the following code:</p><pre><strong>import &#39;package:flutter/material.dart&#39;</strong>;<br><strong>import &#39;package:loginsignupnode/provider/auth_provider.dart&#39;</strong>;<br><strong>import &#39;package:provider/provider.dart&#39;</strong>;<br><br><br><strong>class </strong>HomePage <strong>extends </strong>StatelessWidget {<br><br>  String <strong>_email</strong>,<strong>_password</strong>;<br>  @override<br>  Widget build(BuildContext context) {<br>    <strong>return </strong>Scaffold(<br><br>      body: Center(<br>        child: Padding(<br>          padding: <strong>const </strong>EdgeInsets.all(10.0),<br>          child: Column(<br>            mainAxisAlignment: MainAxisAlignment.<strong>center</strong>,<br>            children: [<br>              TextField(<br>                decoration: InputDecoration(<br>                  labelText: <strong>&#39;Enter Email&#39;</strong>,<br>                ),<br>                keyboardType: TextInputType.<em>emailAddress</em>,<br>                onChanged: (val){<br>                  <strong>_email </strong>= val;<br>                },<br>              ),<br>              TextField(<br>                decoration: InputDecoration(<br>                  labelText: <strong>&#39;Enter password&#39;</strong>,<br>                ),<br>                keyboardType: TextInputType.<em>text</em>,<br>                obscureText: <strong>true</strong>,<br>                onChanged: (val){<br>                  <strong>_password </strong>= val;<br>                },<br>              ),<br>              RaisedButton(<br>                color: Colors.<em>blue</em>.<strong>shade700</strong>,<br>                child: Text(<strong>&#39;Press Me&#39;</strong>),<br>                onPressed: (){<br>                  Provider.<em>of</em>&lt;AuthProvider&gt;(context,listen: <strong>false</strong>).signupUser(<strong>_email</strong>, <strong>_password</strong>);<br>                },<br>              ),<br>            ],<br>          ),<br>        ),<br>      ),<br><br>    );<br>  }<br>}</pre><p>Now inside provider folder, create auth_provider.dart and copy-paste the following code:</p><pre><strong>import &#39;package:flutter/foundation.dart&#39;</strong>;<br><strong>import &#39;package:http/http.dart&#39; as </strong>http;<br><br><strong>class </strong>AuthProvider <strong>with </strong>ChangeNotifier {<br>  String <strong>_userId</strong>;<br>  String <strong>_userEmail</strong>;<br>  String <strong>_userPassword</strong>;<br><br>  String <strong>get getUserId </strong>=&gt; <strong>_userId</strong>;<br><br>  String <strong>get getUserName </strong>=&gt; <strong>_userEmail</strong>;<br><br>  String <strong>get getUserPassword </strong>=&gt; <strong>_userPassword</strong>;<br><br>  Future&lt;<strong>void</strong>&gt; signupUser(String email, String password) <strong>async </strong>{<br>    <strong>final </strong>response = <strong>await </strong>http.post(<strong>&#39;http://localhost:3000/user/signup&#39;</strong>, headers: {<br>      <strong>&quot;content-type&quot;</strong>: <strong>&quot;application/x-www-form-urlencoded; charset=UTF-8&quot;</strong>,<br>    }, body: {<br>      <strong>&#39;userEmail&#39;</strong>: email,<br>      <strong>&#39;userPassword&#39;</strong>: password,<br>    });<br><br>    print(response.<strong>body</strong>);<br>  }<br><br>  Future&lt;<strong>void</strong>&gt; signinUser(String email, String password) <strong>async </strong>{<br>    <strong>final </strong>response =<br>        <strong>await </strong>http.post(<strong>&#39;http://localhost:3000/user/signin&#39;</strong>, headers: {<br>      <strong>&quot;content-type&quot;</strong>: <strong>&quot;application/x-www-form-urlencoded; charset=UTF-8&quot;</strong>,<br>    }, body: {<br>      <strong>&#39;userEmail&#39;</strong>: email,<br>      <strong>&#39;userPassword&#39;</strong>: password,<br>    });<br><br>    print(response.<strong>body</strong>);<br>  }<br>}</pre><p>Simply we are using the HTTP package to send the request, also we set the header as URL encoded, we are only printing the response.body in the console.</p><p>Now let’s go to the main. dart copy-replace the following code:</p><pre><strong>import &#39;package:flutter/material.dart&#39;</strong>;<br><strong>import &#39;package:provider/provider.dart&#39;</strong>;<br><strong>import &#39;screens/homepage.dart&#39;</strong>;<br><strong>import &#39;./provider/auth_provider.dart&#39;</strong>;<br><strong>void </strong>main() {<br>  runApp(MyApp());<br>}<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>ChangeNotifierProvider.value(<br>    value: AuthProvider(),<br>      child: MaterialApp(<br>        title: <strong>&#39;Flutter Demo&#39;</strong>,<br>        theme: ThemeData(<br><br><br>          visualDensity: VisualDensity.<em>adaptivePlatformDensity</em>,<br>        ),<br>        home: HomePage(),<br>      ),<br>    );<br>  }<br>}</pre><p>Here we are registering the provider package to use it in children widgets.</p><p>Now if we run the app and hit the sign up or sign in we will get the response body print in our debug console.</p><p>That’s all for today, I wish you may understand all about how to connect node js with SQL server i.e create an API and use it in your flutter apps.</p><p>Leave a clap and Follow on medium for more articles ❤.</p><p>Thank you ❤</p><p>Github Repo links:</p><ol><li>SQL Queries: <a href="https://github.com/Mashood97/sql-queries">https://github.com/Mashood97/sql-queries</a></li><li>Node Js API Code: <a href="https://github.com/Mashood97/loginsignupSqlNode">https://github.com/Mashood97/loginsignupSqlNode</a></li><li>Flutter Project: <a href="https://github.com/Mashood97/login_signup_node">https://github.com/Mashood97/login_signup_node</a></li></ol><p>If you like this article leave a star and a follow on my Github as well.</p><p>My Other Articles:</p><ol><li><a href="https://medium.com/analytics-vidhya/flutter-and-automated-firebase-push-notification-complete-integration-8377b4fc928b">https://medium.com/analytics-vidhya/flutter-and-automated-firebase-push-notification-complete-integration-8377b4fc928b?source=your_stories_page---------------------------</a></li><li><a href="https://medium.com/analytics-vidhya/magic-of-flutter-provider-and-firestore-66f1a86903c3">https://medium.com/analytics-vidhya/magic-of-flutter-provider-and-firestore-66f1a86903c3</a></li><li><a href="https://medium.com/analytics-vidhya/refactoring-flutter-widgets-into-sub-widgets-3cf0f1f29645">https://medium.com/analytics-vidhya/refactoring-flutter-widgets-into-sub-widgets-3cf0f1f29645</a></li><li><a href="https://medium.com/analytics-vidhya/forms-and-its-validation-in-flutter-1c2b3f9c985c">https://medium.com/analytics-vidhya/forms-and-its-validation-in-flutter-1c2b3f9c985c</a></li><li><a href="https://medium.com/analytics-vidhya/flutter-phone-authentication-with-firebase-using-provider-package-55ffbce7c361">https://medium.com/analytics-vidhya/flutter-phone-authentication-with-firebase-using-provider-package-55ffbce7c361</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a7e57bccb697" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/node-js-express-sql-server-and-flutter-together-flirting-a7e57bccb697">Node JS, Express, SQL Server, and Flutter Together Flirting.</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter and Automated Firebase push Notification Complete Integration.]]></title>
            <link>https://medium.com/analytics-vidhya/flutter-and-automated-firebase-push-notification-complete-integration-8377b4fc928b?source=rss-5b67e4c2ebd6------2</link>
            <guid isPermaLink="false">https://medium.com/p/8377b4fc928b</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[google]]></category>
            <category><![CDATA[facebook]]></category>
            <category><![CDATA[mobile]]></category>
            <category><![CDATA[microsoft]]></category>
            <dc:creator><![CDATA[Muhammad Mashood Siddiquie]]></dc:creator>
            <pubDate>Sat, 13 Jun 2020 12:11:07 GMT</pubDate>
            <atom:updated>2020-06-13T16:09:40.194Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*e4jGUs1O3Q-5AaHRuXk0Ng.png" /></figure><p>Hello Everyone, today we’ll be covering flutter and firebase push notification.</p><p>As I have been working on an App like uber so I faced issues regarding push notifications to send a notification to available drivers about location etc.</p><p>What you need to do is to first set up the flutter project with a firebase with cloud messaging and cloud firestore.</p><p>Step 1: First we will install to firebase functions in our PC:</p><ol><li>Go to Command prompt and write: ‘npm install -g firebase-tools’ and wait until it completes.</li><li>then write ‘firebase login’ and you’ll be prompt to google chrome for login and then log in from the account you’re associated with firebase. if you want to login from different id then use: ‘firebase login — reauth ’ where ‘ — ‘ is a double dash.</li><li>Now create a directory with the command: mkdir firebasefunctions</li><li>now then go to that directory: ‘cd firebasefunctions’</li><li>now write ‘firebase init functions’ and press y.</li><li>now select the default project either create new or choose an existing project in which you want to integrate firebase functions</li><li>After selecting the project you’ll get two options javascript or typescript, select javascript.</li><li>then it’ll ask to install dependencies through npm, press y. it’ll take a couple of minutes</li><li>now enter ‘code .’ to open the project in visual studio code or any other ide you have.</li></ol><p>you’ve successfully installed firebase functions on your PC for a specific project.</p><p>Step 2: Now enable cloud firestore from firebase database options and create a collection, as we are doing it with dummy data you can also integrate it according to your need, let&#39;s do it with me with dummy data:</p><p>Go to firebase console and go to the database and create firestore DB in a test mode then do this what I am doing:</p><ol><li>tap on start collection and name collections with offers as below:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JfcI4D1IlhHcIgcEcULkcg.png" /></figure><p>2) In document id field press auto-id and then give field names as below, all should be the same to work correctly and save it, always remember field name should be the same.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lCT_0pnV1CidxDZ_FMpCRw.png" /></figure><p>3)Now tap on add document and again do the same for document id press auto-id and the same name with different data, always remember field name should be the same.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lCT_0pnV1CidxDZ_FMpCRw.png" /></figure><p>Step 2: Now go visual studio code where you have your firebase setup, inside firebase folder goto index.js and remove all the code and copy-paste the following code:</p><pre><strong>const </strong>functions = require(<strong>&#39;firebase-functions&#39;</strong>);<br><br><br><strong>const </strong>admin = require(<strong>&#39;firebase-admin&#39;</strong>);<br><br><br>admin.initializeApp(functions.config().firebase);<br><strong>var </strong>msgData;<br><br><br>exports.offerTrigger = functions.firestore.document(<br><strong>&#39;offers/{offerId}&#39;<br></strong>).onCreate((snapshot,context)=&gt;{<br><br>msgData = snapshot.data();<br><br>admin.firestore().collection(<strong>&#39;tokens&#39;</strong>).<strong>get</strong>().then((snapshots)=&gt;{<br><strong>var </strong>tokens = [];<br><strong>if</strong>(snapshots.empty)<br>{<br>console.log(<strong>&#39;No Devices Found&#39;</strong>);<br>}<br><strong>else</strong>{<br><strong>for</strong>(<strong>var </strong>pushTokens <strong>of </strong>snapshots.docs){<br>tokens.push(pushTokens.data().token);<br>}<br><br><strong>var </strong>payload ={<br>   <strong>&#39;notification&#39;</strong>:{<br>         <strong>&#39;title&#39;</strong>: <strong>&#39;From &#39; </strong>+ msgData.businessType,<br>         <strong>&#39;body&#39;</strong>: <strong>&#39;Offer is : &#39; </strong>+ msgData.offer,<br>         <strong>&#39;sound&#39;</strong>: <strong>&#39;default&#39;</strong>,<br>       },<br><strong>&#39;data&#39;</strong>:{<br>        <strong>&#39;sendername&#39;</strong>: msgData.businessType,<br>        <strong>&#39;message&#39;</strong>: msgData.offer,<br>      }<br>    };<br><br><strong>return </strong>admin.messaging().sendToDevice(tokens,    payload).then((response) =&gt; {<br>       console.log(<strong>&#39;pushed them all&#39;</strong>)<br>     }).<strong>catch</strong>((err) =&gt; {<br>           console.log(err);<br>       });<br>     }<br>   });<br>});</pre><p>Now let&#39;s understand this what happening here because this is the main part to set up your notification system:</p><ol><li>First, we have initialized the firebase app.</li></ol><pre>exports.offerTrigger = functions.firestore.document(<br><strong>&#39;offers/{offerId}&#39;<br></strong>)</pre><p>This method will always call whenever we add a new document or data into our offers collection that we have already created above as dummy while integrating into your project always remember that you’ve to put here the collection name where little change in a collection will push a notification to the user.</p><pre>admin.firestore().collection(<strong>&#39;tokens&#39;</strong>).<strong>get</strong>().then((snapshots)=&gt;{<br><strong>var </strong>tokens = [];<br><strong>if</strong>(snapshots.empty)<br>{<br>console.log(<strong>&#39;No Devices Found&#39;</strong>);<br>}<br><strong>else</strong>{<br><strong>for</strong>(<strong>var </strong>pushTokens <strong>of </strong>snapshots.docs){<br>tokens.push(pushTokens.data().token);<br>}<br><br><strong>var </strong>payload ={<br>   <strong>&#39;notification&#39;</strong>:{<br>         <strong>&#39;title&#39;</strong>: <strong>&#39;From &#39; </strong>+ msgData.businessType,<br>         <strong>&#39;body&#39;</strong>: <strong>&#39;Offer is : &#39; </strong>+ msgData.offer,<br>         <strong>&#39;sound&#39;</strong>: <strong>&#39;default&#39;</strong>,<br>       },<br><strong>&#39;data&#39;</strong>:{<br>        <strong>&#39;sendername&#39;</strong>: msgData.businessType,<br>        <strong>&#39;message&#39;</strong>: msgData.offer,<br>      }<br>    };<br><br><strong>return </strong>admin.messaging().sendToDevice(tokens,    payload).then((response) =&gt; {<br>       console.log(<strong>&#39;pushed them all&#39;</strong>)<br>     }).<strong>catch</strong>((err) =&gt; {<br>           console.log(err);<br>       });<br>     }<br>   });<br>});</pre><p>Now this collection will work on tokens node, don&#39;t worry we will generate token dynamically but first, we may understand this code, This Code will go inside the tokens collection and get all the tokens, if there is no token so no devices found else if it finds one token then it’ll loop through the documents and take out a token from it, now understand this:</p><p>The Business type and offer will get from the offer collection we created like below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q0pmz6wBKGLhPmg8c8ZiJg.png" /></figure><p>as you can see business-type and offer is the same as written in our index.js file.</p><pre><strong>for</strong>(<strong>var </strong>pushTokens <strong>of </strong>snapshots.docs){<br>tokens.push(pushTokens.data().token);<br>}</pre><p>Tokens.push is adding data into tokens array.</p><pre>pushTokens.data().token</pre><p>now the ‘token’ written here is the field name of the document i.e if you save your token key as MyToken then ‘token’ will be replace to ‘MyToken’.</p><pre><strong>var </strong>payload ={<br>   <strong>&#39;notification&#39;</strong>:{<br>         <strong>&#39;title&#39;</strong>: <strong>&#39;From &#39; </strong>+ msgData.businessType,<br>         <strong>&#39;body&#39;</strong>: <strong>&#39;Offer is : &#39; </strong>+ msgData.offer,<br>         <strong>&#39;sound&#39;</strong>: <strong>&#39;default&#39;</strong>,<br>       },<br><strong>&#39;data&#39;</strong>:{<br>        <strong>&#39;sendername&#39;</strong>: msgData.businessType,<br>        <strong>&#39;message&#39;</strong>: msgData.offer,<br>      }<br>    };<br><br><strong>return </strong>admin.messaging().sendToDevice(tokens,    payload).then((response) =&gt; {<br>       console.log(<strong>&#39;pushed them all&#39;</strong>)<br>     }).<strong>catch</strong>((err) =&gt; {<br>           console.log(err);<br>       });<br>     }<br>   });<br>});</pre><p>Now payload is the notification setup data that we want to send to the user.</p><p>notification: it should be the same as well, a notification will take the title and body which will be shown on the notification to the user.</p><p>data: this takes who sends the data and what’s the message.</p><pre><strong>return </strong>admin.messaging().sendToDevice(tokens,    payload).then((response) =&gt; {<br>       console.log(<strong>&#39;pushed them all&#39;</strong>)<br>     }).<strong>catch</strong>((err) =&gt; {<br>           console.log(err);<br>       });<br>     }<br>   });<br>});</pre><p>This part tell us that push this notification to all the tokens available in our collections.</p><p>Now open the cmd where you’ have your firebase functions, for eg you have saved your firebase functions inside D drive then go to D drive and inside address bar remove all and write cmd and press enter, and then cd firebasefunctions after you’re at the address where you deploy your firebase functions run this command:</p><p>‘firebase deploy — only functions’ where — means two dashes, if you get an auth error then write this command ‘firebase login — reauth’ where — means two dashes.</p><p>Then goto firebase and check out the functions under develop hierarchy you’ll see a trigger appears there. if you don&#39;t see then you probably have forgotten step above.</p><p>Now let&#39;s go towards our app, go to main.dart, remove all the code, and copy-paste the following code:</p><pre><strong>import &#39;package:cloud_firestore/cloud_firestore.dart&#39;</strong>;<br><strong>import &#39;package:firebase_messaging/firebase_messaging.dart&#39;</strong>;<br><strong>import &#39;package:flutter/material.dart&#39;</strong>;<br><br><strong>void </strong>main() {<br>  runApp(MyApp());<br>}<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;Flutter Demo&#39;</strong>,<br>      theme: ThemeData(<br>        primarySwatch: Colors.<em>blue</em>,<br>        visualDensity: VisualDensity.<em>adaptivePlatformDensity</em>,<br>      ),<br>      home: MyHomePage(),<br>    );<br>  }<br>}<br><br><strong>class </strong>MyHomePage <strong>extends </strong>StatefulWidget {<br>  @override<br>  _MyHomePageState createState() =&gt; _MyHomePageState();<br>}<br><br><strong>class </strong>_MyHomePageState <strong>extends </strong>State&lt;MyHomePage&gt; {<br>  <strong>final </strong>FirebaseMessaging <strong>firebaseMessaging </strong>= FirebaseMessaging();<br>  <strong>final _firestore </strong>= Firestore.<em>instance</em>;<br>  <strong>final key </strong>= GlobalKey&lt;ScaffoldState&gt;();<br><br>  @override<br>  <strong>void </strong>initState() {<br>    <strong>super</strong>.initState();<br>    <strong>firebaseMessaging</strong>.getToken().then((token) {<br>      saveTokens(token);<br>    });<br><br>  <br>  }<br><br>  Future&lt;<strong>void</strong>&gt; saveTokens(<strong>var </strong>token) <strong>async </strong>{<br>    <strong>try </strong>{<br>      <strong>await _firestore</strong>.collection(<strong>&#39;tokens&#39;</strong>).add({<br>        <strong>&#39;token&#39;</strong>: token,<br>      });<br>    } <strong>catch </strong>(e) {<br>      print(e);<br>    }<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    <strong>return </strong>Scaffold(<br>      key: <strong>key</strong>,<br>      appBar: AppBar(<br>        title: Text(<strong>&#39;Push Notification&#39;</strong>),<br>      ),<br>      body: Center(<br>        child: Column(<br>          mainAxisAlignment: MainAxisAlignment.<strong>center</strong>,<br>          children: &lt;Widget&gt;[],<br>        ),<br>      ),<br>    );<br>  }<br>}</pre><p>Now here in init state we get token and save it to the firestore with a new collection, you need to do it once so that your device id is saved into the firestore.</p><p>Let’s run the app, you’ll see the firestore as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q4WXCtHirbN76nnhenAhfw.png" /></figure><p>A tokens collection is generated with a token field which is the same as in our index.js field.</p><p>Now copy-paste the code in init state:</p><pre>@override<br>  <strong>void </strong>initState() {<br>    <strong>super</strong>.initState();<br><em>//    firebaseMessaging.getToken().then((token) {<br>//      saveTokens(token);<br>//    });<br><br>    </em><strong>firebaseMessaging</strong>.configure(<br>      <em>//called when app is in foreground<br>      </em>onMessage: (Map&lt;String, <strong>dynamic</strong>&gt; message) <strong>async </strong>{<br>        print(<strong>&#39;init called onMessage&#39;</strong>);<br>        <strong>final </strong>snackBar = SnackBar(<br>          content: Text(message[<strong>&#39;notification&#39;</strong>][<strong>&#39;body&#39;</strong>]),<br>          action: SnackBarAction(label: <strong>&#39;GO&#39;</strong>, onPressed: () {}),<br>        );<br>        <strong>key</strong>.<strong>currentState</strong>.showSnackBar(snackBar);<br>      },<br>      <em>//called when app is completely closed and open from push notification<br>      </em>onLaunch: (Map&lt;String, <strong>dynamic</strong>&gt; message) <strong>async </strong>{<br>        print(<strong>&#39;init called onLaunch&#39;</strong>);<br>      },<br>      <em>//called when app is in background  and open from push notification<br><br>      </em>onResume: (Map&lt;String, <strong>dynamic</strong>&gt; message) <strong>async </strong>{<br>        print(<strong>&#39;init called onResume&#39;</strong>);<br>      },<br>    );<br><br>  }</pre><p>we have commented out the token code because we don’t want it anymore as we saved a token already.</p><p>Let&#39;s understand the config part:</p><ol><li>OnMessage: This method is called when the app is in the foreground, i.e the user is using the app, so we show some type of pop up to the user about notification for e.g a snack bar or a dialog or a toast, etc.</li><li>onLaunch: This method is called when the app is completely destroyed i.e It’s not in background or completely closed and whenever a notification occurs the app will open with it.</li><li>onResume: This method is called when the app is not completely destroyed i.e It’s in the background and the user is not using the application and whenever a notification occurs the app will open with it.</li></ol><p>The Map&lt;String,dynamic&gt; message is the JSON we return on index.js file i.e:</p><pre><strong>var </strong>payload ={<br>  <strong>&#39;notification&#39;</strong>:{<br>    <strong>&#39;title&#39;</strong>: <strong>&#39;From &#39; </strong>+ msgData.businessType,<br>    <strong>&#39;body&#39;</strong>: <strong>&#39;Offer is : &#39; </strong>+ msgData.offer,<br>    <strong>&#39;sound&#39;</strong>: <strong>&#39;default&#39;</strong>,<br>  },<br>  <strong>&#39;data&#39;</strong>:{<br>    <strong>&#39;sendername&#39;</strong>: msgData.businessType,<br>    <strong>&#39;message&#39;</strong>: msgData.offer,<br>  }<br>};</pre><p>This is the JSON we get in our ‘Map&lt;String, dynamic&gt; message’ parameter.</p><p>Now go to the android folder, then the app , then src then main and then manifest file and copy-paste this intent-filter inside activity tag:</p><pre>&lt;<strong>intent-filter</strong>&gt;<br>    &lt;<strong>action android:name=&quot;FLUTTER_NOTIFICATION_CLICK&quot; </strong>/&gt;<br>    &lt;<strong>category android:name=&quot;android.intent.category.DEFAULT&quot; </strong>/&gt;<br>&lt;/<strong>intent-filter</strong>&gt;</pre><p>Now, let’s run the app and check out the notification magic:</p><ol><li>Let’s first check the onMessage state of our application i.e don’t exit the Application and wait to get a notification now go to Firestore and add a new document inside offers node. you may see after you save the document inside a couple of mins you’ll receive a notification as a snack bar in your app.</li><li>Now Let’s make our app in a background state to test our onResume method working or not, so press the home button on your mobile and create a document again inside offers collection. you may see after you save the document inside offers node, a notification will appear on notification bar of your phone when you press the notification it’ll go to the app.</li><li>Now Let’s make our app in a completely destroyed or closed state to test our on launch method working or not, create a document again inside offers collection. you may see after you save the document inside offers node, a notification will appear on the notification bar of your phone. when you press the notification it’ll go to the app.</li></ol><p>Keep in mind in the token process, you save the token of each user when you&#39;re registering the user in your app.</p><p>That’s all for today, we have learned today how to send automated notifications on flutter using firebase push notifications. You can customize it with your needs, it’ll be useful in uber type app or e-commerce or chat app user to user.</p><p>This is the basic setup on how to use such notifications. I haven’t added the index.js in GitHub so copy-paste from the above where I explained index.js code.</p><p>Leave a clap and also follow me on medium if it is helpful for you.</p><p>Thank you.</p><p>Github Repo link:</p><p><a href="https://github.com/Mashood97/flutter_push_notification">Mashood97/flutter_push_notification</a></p><p>Leave a star and also follow me on GitHub ❤</p><p>Thank you again ❤</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8377b4fc928b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/flutter-and-automated-firebase-push-notification-complete-integration-8377b4fc928b">Flutter and Automated Firebase push Notification Complete Integration.</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Magic of Flutter, Provider, and Firestore]]></title>
            <link>https://medium.com/analytics-vidhya/magic-of-flutter-provider-and-firestore-66f1a86903c3?source=rss-5b67e4c2ebd6------2</link>
            <guid isPermaLink="false">https://medium.com/p/66f1a86903c3</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[provider]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[google]]></category>
            <dc:creator><![CDATA[Muhammad Mashood Siddiquie]]></dc:creator>
            <pubDate>Thu, 11 Jun 2020 12:23:31 GMT</pubDate>
            <atom:updated>2020-06-11T16:01:19.121Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*e4jGUs1O3Q-5AaHRuXk0Ng.png" /></figure><p>Hello everyone today we will be learning flutter with firestore as a backend with Provider package in easy steps. Before starting into this article first, you should have already integrated a firebase in your application and also set up a firestore as a database with a testing mode. We will be building a simple app for products and apply CRUD operation on it.</p><p>Step 1: Let’s dive into the project structure first, you must have the same project structure as I am having so things will be more clear to you.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*w8GDrJvK6j2VYZwZiMhmzw.png" /></figure><p>Step 2: Copy-paste the following dependencies in your pubspec.yaml file:</p><pre><strong>cloud_firestore</strong>: ^0.13.4+2<br><strong>provider</strong>: ^4.0.5<br><strong>uuid</strong>: ^2.0.4</pre><ol><li>cloud_firestore: This gives access to use of firestore functions in our flutter application.</li><li>provider: This will be used to manage the state of our app i.e differentiate the UI and logical parts.</li><li>UUID: This package will be used to generate the id of a product.</li></ol><p>Step 3: First goto models folder and create a product.dart class. The model class is basically referred to as a user-generated data type, in which data is classified according to the user requirements.</p><pre><strong>class </strong>Product{<br>  String <strong>productId</strong>;<br>  String <strong>productName</strong>;<br>  double <strong>price</strong>;<br><br>  Product({<strong>this</strong>.<strong>price</strong>,<strong>this</strong>.<strong>productId</strong>,<strong>this</strong>.<strong>productName</strong>});<br><br><br>  Map&lt;String,<strong>dynamic</strong>&gt; createMap(){<br>    <strong>return </strong>{<br>      <strong>&#39;productId&#39;</strong>: <strong>productId</strong>,<br>      <strong>&#39;productName&#39;</strong>: <strong>productName</strong>,<br>      <strong>&#39;productPrice&#39;</strong>: <strong>price<br>    </strong>};<br>  }<br><br>  Product.fromFirestore(Map&lt;String,<strong>dynamic</strong>&gt; firestoreMap): <br><strong>productId </strong>= firestoreMap[<strong>&#39;productId&#39;</strong>],<br>   <strong>productName </strong>= firestoreMap[<strong>&#39;productName&#39;</strong>],<br>   <strong>price </strong>= firestoreMap[<strong>&#39;productPrice&#39;</strong>];<br>}</pre><p>In this class we have three properties:</p><p>a) String productId.</p><p>b) String productName.</p><p>c)double price.</p><p>we created a named constructor i.e the order while passing data to the constructor is not necessary.</p><p>There are two functions that are defined in the product.dart model class:</p><ol><li>Map&lt;String, dynamic&gt; createmap(): This means it converts the product properties into a map and returns it as a Map.</li><li>Product.fromFirestore(Map&lt;String, dynamic firestoreMap): This means that the firestore returns the data in form of a map so this method is used to convert the map into the properties which means the vice-versa of create map function.</li></ol><p>Step 4: Go to the provider folder and create a new class inside it with name products_provider.dart and copy-paste the following code inside it.</p><pre><strong>class </strong>ProductProvider <strong>with </strong>ChangeNotifier{<br>  String <strong>_name</strong>;<br>  String <strong>_productId</strong>;<br>  double <strong>_price</strong>;<br><br>//getters:</pre><pre>  String <strong>get getName </strong>=&gt; <strong>_name</strong>;<br>  double <strong>get getPrice </strong>=&gt; <strong>_price</strong>;<br><br><em>//Setters:<br><br>  </em><strong>void </strong>changeProductName(String val) {<br>    <strong>_name </strong>= val;<br>    notifyListeners();<br>  }<br><br>  <strong>void </strong>changeProductPrice(String val) {<br>    <strong>_price </strong>= double.<em>parse</em>(val);<br>    notifyListeners();<br>  }</pre><p>we created three private properties underscore defines the property as private and simply we created getters and setters for our properties. As we are not getting any product id and setting because it’ll be dynamically or auto-generated.</p><p>Step 5: Go to main.dart, remove all the code, and copy-paste the following code:</p><pre><strong>import &#39;package:flutter/material.dart&#39;</strong>;<br><strong>import &#39;package:flutter_responsiveness/providers/product_provider.dart&#39;</strong>;<br><strong>import &#39;package:flutter_responsiveness/screens/edit_add_product.dart&#39;</strong>;<br><strong>import &#39;package:provider/provider.dart&#39;</strong>;<br><strong>import &#39;./screens/product_list.dart&#39;</strong>;<br><strong>import &#39;./services/firestore_service.dart&#39;</strong>;</pre><pre><strong>void </strong>main()=&gt;runApp(MyApp());<br><br><br><strong>class </strong>MyApp <strong>extends </strong>StatelessWidget {<br>  @override<br>  Widget build(BuildContext context) {<br>    <strong>return </strong>MultiProvider(<br>      providers: [<br>        ChangeNotifierProvider.value(value: ProductProvider()),<br>      ],<br>          child: MaterialApp(<br>        debugShowCheckedModeBanner: <strong>false</strong>,<br>        theme: ThemeData(<br>          primaryColor: Colors.<em>blueAccent</em>[700],<br>          accentColor: Colors.<em>indigoAccent</em>[700],<br>          canvasColor: Colors.<em>white</em>,<br>        ),<br>        home: ProductList(),<br>      ),<br>    );<br>  }<br>}</pre><p>Multi Providers enable us to use multiple providers in our app. it contains providers&#39; property which takes an array of providers and a child property which contains a widget.</p><p>Step 6: Go to screens folder and create a new file with the name product_list.dart and copy-paste the following code:</p><pre><strong>import &#39;package:flutter/material.dart&#39;</strong>;<br><br><strong>class </strong>ProductList <strong>extends </strong>StatelessWidget {<br>  @override<br>  Widget build(BuildContext context) {<br>    <strong>return </strong>Scaffold(<br>      appBar: AppBar(<br>        title: Text(<strong>&#39;Product&#39;</strong>),<br>        actions: [<br>          IconButton(<br>            icon: Icon(<br>              Icons.<em>add</em>,<br>            ),<br>            onPressed: () {},<br>          ),<br>        ],<br>      ),<br>    );<br>  }<br>}</pre><p>Simply we have an app bar widget with title and actions as IconButton. Actions are the widgets that are defined at the right side of the app bar.</p><p>Step 7: Create another class inside the screens folder with name edit_add_product.dart and copy-paste the following code:</p><pre><strong>import &#39;package:flutter/material.dart&#39;</strong>;<br><strong>import &#39;package:provider/provider.dart&#39;</strong>;<br><strong>import &#39;../providers/product_provider.dart&#39;</strong>;<br><br><strong>class </strong>AddEditProduct <strong>extends </strong>StatefulWidget {<br>  <strong>static const </strong><em>routeArgs </em>= <strong>&#39;/add-edit-screen&#39;</strong>;<br><br>  @override<br>  _AddEditProductState createState() =&gt; _AddEditProductState();<br>}<br><br><strong>class </strong>_AddEditProductState <strong>extends </strong>State&lt;AddEditProduct&gt; {<br>  <strong>final _formKey </strong>= GlobalKey&lt;FormState&gt;();</pre><pre><strong>final nameController </strong>= TextEditingController();<br><strong>final priceController </strong>= TextEditingController();</pre><pre>@override<br><strong>void </strong>dispose() {<br>  <strong>super</strong>.dispose();<br>  <strong>nameController</strong>.dispose();<br>  <strong>priceController</strong>.dispose();<br>}<br>  @override<br>  Widget build(BuildContext context) {<br>    <strong>final </strong>productProvider = Provider.<em>of</em>&lt;ProductProvider&gt;(context);<br>    <strong>return </strong>Scaffold(<br>      appBar: AppBar(<br>        title: Text(<strong>&#39;Add or Edit Product&#39;</strong>),<br>      ),<br>      body: Center(<br>          child: Form(<br>        key: <strong>_formKey</strong>,<br>        child: SingleChildScrollView(<br>          child: Padding(<br>            padding: <strong>const </strong>EdgeInsets.all(10.0),<br>            child: Column(<br>              children: [<br>                TextFormField(</pre><pre>                 controller: <strong>nameController</strong>,                                                     validator: (value) {<br>                    <strong>if </strong>(value.<strong>isEmpty</strong>) {<br>                      <strong>return &#39;Please Enter Name&#39;</strong>;<br>                    }<br>                    <strong>return null</strong>;<br>                  },<br>                  decoration: InputDecoration(<br>                    hintText: <strong>&#39;Enter Product Name&#39;</strong>,<br>                  ),<br>                  onChanged: (val) =&gt; productProvider.changeProductName(val),<br>                ),<br>                TextFormField(</pre><pre>                 controller: <strong>priceController</strong>,<br>                  validator: (value) {<br>                    <strong>if </strong>(value.<strong>isEmpty</strong>) {<br>                      <strong>return &#39;Please Enter Price&#39;</strong>;<br>                    }<br>                    <strong>return null</strong>;<br>                  },<br>                  decoration: InputDecoration(<br>                    hintText: <strong>&#39;Enter Product Price&#39;</strong>,<br>                  ),<br>                  onChanged: (value) =&gt;<br>                      productProvider.changeProductPrice(value),<br>                ),<br>                SizedBox(<br>                  height: 20,<br>                ),<br>                RaisedButton(<br>                  child: Text(<strong>&#39;Save&#39;</strong>),<br>                  onPressed: () {<br>               <br>                  },<br>                  color: Theme.<em>of</em>(context).<strong>accentColor</strong>,<br>                  textColor: Colors.<em>white</em>,<br>                ),<br>                RaisedButton(<br>                  child: Text(<strong>&#39;Delete&#39;</strong>),<br>                  onPressed: () {<br>                  },<br>                  color: Colors.<em>red</em>,<br>                  textColor: Colors.<em>white</em>,<br>                )<br>              ],<br>            ),<br>          ),<br>        ),<br>      )),<br>    );<br>  }<br>}</pre><p>onchanged method takes the parameterized function, which contains the string data and also we are using the setter of our products provider to change the name and price of a product.</p><p>As you can see we are using forms and I have already covered forms in flutter so you can check out my medium article of forms and its validation:</p><p><a href="https://medium.com/@mashoodsidd97/forms-and-its-validation-in-flutter-1c2b3f9c985c">Forms and its validation in Flutter</a></p><p>Also, the code has multiple useable widgets we can also do some code refactoring, this article of mine explains code refactoring in deep and simple steps check out here:</p><p><a href="https://medium.com/@mashoodsidd97/refactoring-flutter-widgets-into-sub-widgets-3cf0f1f29645">Refactoring Flutter Widgets into Sub widgets</a></p><p>I won’t be doing any code refactoring or form explanation as the article would too long.</p><p>Now Let’s move towards the CRUD operation of flutter,</p><p>Step 8: Go to services and create a new file with name firestore_services.dart and copy-paste the following code inside it:</p><pre><strong>import &#39;package:cloud_firestore/cloud_firestore.dart&#39;</strong>;<br><strong>import &#39;package:flutter_responsiveness/models/product.dart&#39;</strong>;<br><br><strong>class </strong>FireStoreService {<br>  Firestore <strong>_db </strong>= Firestore.<em>instance</em>;<br><br>  Future&lt;<strong>void</strong>&gt; saveProduct(Product product) {<br>    <strong>return _db<br>        </strong>.collection(<strong>&#39;Products&#39;</strong>)<br>        .document(product.<strong>productId</strong>)<br>        .setData(product.createMap());<br>  }<br><br>  Stream&lt;List&lt;Product&gt;&gt; getProducts() {<br>    <strong>return _db</strong>.collection(<strong>&#39;Products&#39;</strong>).snapshots().map((snapshot) =&gt; snapshot<br>        .<strong>documents<br>        </strong>.map((document) =&gt; Product.fromFirestore(document.<strong>data</strong>))<br>        .toList());<br>  }<br><br>  Future&lt;<strong>void</strong>&gt; removeItem(String productId) {<br>    <strong>return _db</strong>.collection(<strong>&#39;Products&#39;</strong>).document(productId).delete();<br>  }<br>}</pre><p>Firestore works on a collection and documents basis. Which is a different approach from SQL database.</p><ol><li>save product: This method saves data into our firestore. The code I have written means that as firestore works on collections and it’s a different approach from the SQL Database, we have created a firestore instance to use its functions. _db.collections(‘Products’) means that goto firestore and add a new collection with the Products and concatenation .documents means that we are passing our own custom id inside the collections and setData means the data we want to save inside this collection which should be in the form of Map.</li><li>GetProducts: This method returns a stream. A stream is like a pipe, you put a value on the one end, and if there’s a listener on the other end that listener will receive that value. A Stream can have multiple listeners and all of those listeners will receive the same value when it’s put in the pipeline. Lines of code explanation:</li></ol><pre><strong>_db</strong>.collection(<strong>&#39;Products&#39;</strong>).snapshots().map((snapshot) =&gt; snapshot<br>        .<strong>documents<br>        </strong>.map((document) =&gt; Product.fromFirestore(document.<strong>data</strong>))<br>        .toList());</pre><p>This means go to the products collection and gets snapshots which returns the stream of data and map it that means to map the data which you get from streams which takes a function in which we access the document inside the Products collection and also map that document as firestore returns data in form of Map so we need to convert it into the properties so we can populate them into our widgets as we have already created the method which converts map to properties inside our product model class i.e from firestore so we access it and pass the document.data which is a map also the return type of our method is a list so we add .toList() at the end of the method to return the data in the form of the list.</p><p>3. Remove Item Method: This method simply takes a Product id and deletes that from the app as well as the backend and since we are using streams we don&#39;t need to refresh the application to see the changes, Streams makes it easier for us to detect live changes within the app.</p><p>Step 9: Now go to products_provider.dart class:</p><p>a) import the Firestore Service class and UUID:</p><pre><strong>import &#39;../services/firestore_service.dart&#39;</strong>;<br><strong>import &#39;package:uuid/uuid.dart&#39;</strong>;</pre><p>b) Create a final field of products_provider inside ProductProvider and also UUID to get random ids</p><pre><strong>final service </strong>= FireStoreService();<br><strong>var uuid </strong>= Uuid();</pre><p>c) Now create a method inside Products Provider to save data into firestore:</p><pre><strong>void </strong>saveData() {<br><strong>var </strong>newProduct =    Product(productName: <strong>getName</strong>, productId: </pre><pre><strong>uuid</strong>.v4(), price: <strong>getPrice</strong>);</pre><pre><strong>service</strong>.saveProduct(newProduct);</pre><pre>}</pre><p>As in our service class, our saveProduct takes a Product model class as a parameter so we need to first define a product then pass it into the parameter of saving product, where getName is the name which is set to the edit_add_product.dart class like this:</p><pre>TextFormField(<br>  validator: (value) {<br>    <strong>if </strong>(value.<strong>isEmpty</strong>) {<br>      <strong>return &#39;Please Enter Name&#39;</strong>;<br>    }<br>    <strong>return null</strong>;<br>  },<br>  controller: <strong>nameController</strong>,<br>  decoration: InputDecoration(<br>    hintText: <strong>&#39;Enter Product Name&#39;</strong>,<br>  ),<br>  onChanged: (val) =&gt; productProvider.changeProductName(val),<br>),</pre><p>Similarly for getPrice as well. product is the UUID.v4 which will be a unique id for every product we add in the firestore.</p><p>Step 10: Let&#39;s go back to the edit_add_product.dart class and go to the Save Raised Button compressed method and replace the code of Save Raised Button with this code:</p><pre>RaisedButton(<br>  child: Text(<strong>&#39;Save&#39;</strong>),<br>  onPressed: () {<br>    <strong>if</strong>(<strong>_formKey</strong>.<strong>currentState</strong>.validate())<br>    {<br>    productProvider.saveData();<br>    Navigator.<em>of</em>(context).pop();<br>  }<br>  },<br>  color: Theme.<em>of</em>(context).<strong>accentColor</strong>,<br>  textColor: Colors.<em>white</em>,<br>),</pre><p>In this, we validate the form that if all fields are entered then save the data to the firebase, and pop means after adding data to the firestore immediately pop the screen from the stack of screens.</p><p>Now run the app, press the “+” button on the app bar, and then enter the product name and price, you’ll see that the data is added to the firestore.</p><p>Step 11: let&#39;s get back to the main. dart file as we are getting the product data in the form of a stream so we have to register it as well to it&#39;s my approach for using firestore in a flutter app. There are different approaches as well, you can find out more on documentation or googling it for different approaches. Let’s come back to the point, replace the main. dart code with this code:</p><pre><strong>import &#39;package:flutter/material.dart&#39;</strong>;<br><strong>import &#39;package:flutter_responsiveness/providers/product_provider.dart&#39;</strong>;<br><strong>import &#39;package:flutter_responsiveness/screens/edit_add_product.dart&#39;</strong>;<br><strong>import &#39;package:provider/provider.dart&#39;</strong>;<br><strong>import &#39;./screens/product_list.dart&#39;</strong>;<br><strong>import &#39;./services/firestore_service.dart&#39;</strong>;<br><strong>void </strong>main()=&gt;runApp(MyApp());<br><br><br><strong>class </strong>MyApp <strong>extends </strong>StatelessWidget {<br>  @override<br>  Widget build(BuildContext context) {<br>        <strong>final </strong>firestoreService = FireStoreService();<br><br>    <strong>return </strong>MultiProvider(<br>      providers: [<br>        ChangeNotifierProvider.value(value: ProductProvider()),<br>        StreamProvider.value(value: firestoreService.getProducts()),<br>      ],<br>          child: MaterialApp(<br>        debugShowCheckedModeBanner: <strong>false</strong>,<br>        theme: ThemeData(<br>          primaryColor: Colors.<em>blueAccent</em>[700],<br>          accentColor: Colors.<em>indigoAccent</em>[700],<br>          canvasColor: Colors.<em>white</em>,<br>        ),<br>        home: ProductList(),<br>      routes: {<br>        AddEditProduct.<em>routeArgs</em>:(ctx)=&gt;AddEditProduct(),<br>      },<br>      ),<br>    );<br>  }<br>}</pre><p>we are using stream provider to get all the products from firebase to get updates of each action taken on our data.</p><p>Step 12: Now goto product_list.dart and copy-paste the following code:</p><pre><strong>import &#39;package:flutter/material.dart&#39;</strong>;<br><strong>import &#39;package:flutter_responsiveness/models/product.dart&#39;</strong>;<br><strong>import &#39;package:flutter_responsiveness/screens/edit_add_product.dart&#39;</strong>;<br><strong>import &#39;package:provider/provider.dart&#39;</strong>;<br><br><strong>class </strong>ProductList <strong>extends </strong>StatelessWidget {<br>  @override<br>  Widget build(BuildContext context) {<br>    <strong>final </strong>productList = Provider.<em>of</em>&lt;List&lt;Product&gt;&gt;(context);<br>    <strong>return </strong>Scaffold(<br>      appBar: AppBar(<br>        title: Text(<strong>&#39;Product&#39;</strong>),<br>        actions: [<br>          IconButton(<br>            icon: Icon(<br>              Icons.<em>add</em>,<br>            ),<br>            onPressed: () {<br>          Navigator.<em>of</em>(context).pushNamed(AddEditProduct.<em>routeArgs</em>);<br>            },<br>          ),<br>        ],<br>      ),<br>      body: productList != <strong>null<br>          </strong>? ListView.builder(<br>              itemCount: productList.<strong>length</strong>,<br>              itemBuilder: (ctx, i) =&gt; ListTile(<br>                title: Text(productList[i].<strong>productName</strong>),<br>                trailing: Text(productList[i].<strong>price</strong>.toString()),<br>                onTap: () =&gt; Navigator.<em>of</em>(context)<br>                    .pushNamed(AddEditProduct.<em>routeArgs</em>, arguments: {<br>                  <strong>&#39;productId&#39;</strong>: productList[i].<strong>productId</strong>,<br>                  <strong>&#39;productName&#39;</strong>: productList[i].<strong>productName</strong>,<br>                  <strong>&#39;productPrice&#39;</strong>: productList[i].<strong>price</strong>,<br>                }),<br>              ),<br>            )<br>          : Center(<br>              child: CircularProgressIndicator(),<br>            ),<br>    );<br>  }<br>}</pre><p>we create a product list of provider. As ‘of ‘ is a generic type so we need to pass the data type in &lt;&gt; brackets. so we passed the list&lt;products&gt; as we want to get all the products. creating a body part we are checking with ternary operator that if products are not null then create a listview.builder in which item count is the length of list items and builder takes the context and index of each item. We use fat arrow notation to return the list tile widget with title and trailing means it will be at the most right of the screen, also we used on tap on the list tile widget in which we are going to the Add_Edit_product class and arguments means what data we want to pass to this class we are passing map data to add_edit_product, it’s not always necessary to use arguments until unless you need to pass the data to the ongoing class, also after this ‘:’ we return circular progress indicator and when we get data this will automatically hide and our list view will be populated with data.</p><p>Lets hot restart the app and check that your first screen will be populated with data you entered.</p><p>Step 13: It’s time to update the data, first go to products provider and inside save data copy-replace the following code:</p><pre><strong>void </strong>saveData() {<br>  <strong>if </strong>(<strong>_productId </strong>== <strong>null</strong>) {<br>    <strong>var </strong>newProduct =<br>        Product(productName: <strong>getName</strong>, productId: <strong>uuid</strong>.v4(), price: <strong>getPrice</strong>);<br>    <strong>service</strong>.saveProduct(newProduct);<br>  } <strong>else </strong>{<br>    <strong>var </strong>updatedProduct =<br>        Product(productName: <strong>getName</strong>, price: <strong>getPrice</strong>, productId: <strong>_productId</strong>);<br>    <strong>service</strong>.saveProduct(updatedProduct);<br>  }<br>}</pre><p>we are checking here if the product id is null so that means we will add new data to the firestore if we found any product id that means we will update that data to Firestone.</p><p>Step 14: Let’s move towards the add_edit_products and create init state inside it:</p><pre>@override<br><strong>void </strong>initState() {<br>  <strong>super</strong>.initState();<br>  <strong>new </strong>Future.delayed(Duration(microseconds: 10), () {<br>    <strong>routeData </strong>=<br>        ModalRoute.<em>of</em>(<strong>context</strong>).<strong>settings</strong>.<strong>arguments as </strong>Map&lt;String, <strong>dynamic</strong>&gt;;<br>  }).then((_) =&gt; <strong>routeData </strong>== <strong>null<br>      </strong>? <strong>new </strong>Future.delayed(Duration.<em>zero</em>, () {<br>          clearData();<br>          <strong>final </strong>productProvider =<br>              Provider.<em>of</em>&lt;ProductProvider&gt;(<strong>context</strong>, listen: <strong>false</strong>);<br>          productProvider.loadValues(Product());<br>        })<br>      : Future.delayed(Duration.<em>zero</em>, () {<br>          print(<strong>routeData</strong>);<br>          <strong>nameController</strong>.<strong>text </strong>= <strong>routeData</strong>[<strong>&#39;productName&#39;</strong>];<br>          <strong>priceController</strong>.<strong>text </strong>= <strong>routeData</strong>[<strong>&#39;productPrice&#39;</strong>].toString();<br><br>          <strong>final </strong>productProvider =<br>              Provider.<em>of</em>&lt;ProductProvider&gt;(<strong>context</strong>, listen: <strong>false</strong>);<br>          Product p = Product(<br>            productId: <strong>routeData</strong>[<strong>&#39;productId&#39;</strong>],<br>            price: <strong>routeData</strong>[<strong>&#39;productPrice&#39;</strong>],<br>            productName: <strong>routeData</strong>[<strong>&#39;productName&#39;</strong>],<br>          );<br>          productProvider.loadValues(p);<br>        }));<br>}</pre><p>We passed the data from the product list to add_edit_product class as map argument so we accept it like this:</p><pre><strong>routeData </strong>=<br>        ModalRoute.<em>of</em>(<strong>context</strong>).<strong>settings</strong>.<strong>arguments as </strong>Map&lt;String, <strong>dynamic</strong>&gt;;</pre><p>since init, the state has no access to context directly because its the first lifecycle method of the stateful widget, so to access context inside init state we use Future. delayed which takes duration and a method inside it and then means that when the given operation is completed inside future then we want run these lines of code, so inside then we are checking if the route data is null then we are entering new data into text fields else we are updating the data from text field which will be populated automatically for edit purpose.</p><p>Since there will be a bug because the data will always be there if we edit or add a product so we need to load tell the provider too about it so we will create a new method inside products_provider.dart class:</p><pre>loadValues(Product product) {<br>  <strong>_name </strong>= product.<strong>productName</strong>;<br>  <strong>_price </strong>= product.<strong>price</strong>;<br>  <strong>_productId </strong>= product.<strong>productId</strong>;<br>}</pre><p>This method makes our state up to date according to add or update data.</p><p>Now run the app and tap on the list item and you’ll see the data is populated inside the text field try to change the data inside the field and hit save you’ll see the data is updated inside the app due to streams and also to firestore as well.</p><p>Step 15: Now let&#39;s remove the item from Firestore, goto to the products_provider class and add this method:</p><pre><strong>void </strong>removeData() {<br>  <strong>service</strong>.removeItem(<strong>_productId</strong>);<br>}</pre><p>This method will remove the item from the firestore.</p><p>Step 16: Let’s go to the add_edit_product class and inside the second raised button for delete replace it with this code:</p><pre>RaisedButton(<br>  child: Text(<strong>&#39;Delete&#39;</strong>),<br>  onPressed: () {<br>    productProvider.removeData();<br>    Navigator.<em>of</em>(context).pop();<br>  },<br>  color: Colors.<em>red</em>,<br>  textColor: Colors.<em>white</em>,<br>)</pre><p>This will remove the following data and pop the screen from the stack of the screen.</p><p>Run the app from scratch and check out by adding, update and deleting, and reading data.</p><p>For any queries, Leave me a note or comment on the article.</p><p>That’s all for today. It was really a deep dive and a big article of flutter with firestore and provider.</p><p>I have made a lot of effort to write this article in the simplest way so don’t forget to give a clap and a follow.</p><p>Github Repo Link:</p><p><a href="https://github.com/Mashood97/flutter_firestore">Mashood97/flutter_firestore</a></p><p>Don’t forget to start the repo and follow me.</p><p>Thank you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=66f1a86903c3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/magic-of-flutter-provider-and-firestore-66f1a86903c3">Magic of Flutter, Provider, and Firestore</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>