<?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 Chathuranga Edirisinghe on Medium]]></title>
        <description><![CDATA[Stories by Chathuranga Edirisinghe on Medium]]></description>
        <link>https://medium.com/@edirisinghe.cha?source=rss-e75762970f01------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*F7kk-FFsnVsZWnrz6UrE-Q.png</url>
            <title>Stories by Chathuranga Edirisinghe on Medium</title>
            <link>https://medium.com/@edirisinghe.cha?source=rss-e75762970f01------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 19:35:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@edirisinghe.cha/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: The Big Picture]]></title>
            <link>https://medium.com/ascentic-technology/flutter-the-big-picture-c326163b926c?source=rss-e75762970f01------2</link>
            <guid isPermaLink="false">https://medium.com/p/c326163b926c</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[dart]]></category>
            <dc:creator><![CDATA[Chathuranga Edirisinghe]]></dc:creator>
            <pubDate>Fri, 24 Jun 2022 09:26:33 GMT</pubDate>
            <atom:updated>2022-06-24T09:26:33.986Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gI_HfBZIktfYg5m7mIHY3w.jpeg" /></figure><p>In short, Flutter is a framework to build apps from a single code base. With the current version of Flutter, you can build apps for mobile, web, desktop, and even embedded devices with the same code base.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yh-ucffUyr7kN9WmZRyH9g.png" /></figure><h4><strong>It has several points of strength</strong></h4><ul><li>Flutter increases productivity. Not only can you use the same code base for Android, iOS, web, and desktop, but you can also leverage the hot reload feature, meaning that you can change your code while debugging and see the changes immediately without manually recompiling your code.</li><li>It’s fast as it uses. Skia for rendering, which is the same rendering library used by Chrome browser and Chrome OS, among others.</li><li>It uses ahead‑of‑time compilation to increase the speed while executing.</li><li>It’s a free and open source. It’s developed by Google and open to the community. It’s been created with the ease of developers and designers in mind, and there are many details that make it easy and pleasant to learn and use.</li><li>Flutter has pixel‑perfect replications of the iOS UI with the Cupertino widgets and Android’s UI with Material widgets. So, it’s easy for developers and designers bring a device‑specific experience to the users.</li></ul><p>There are several great apps out there that were made with Flutter. For some apps, you’ll also find interesting stories about the projects and the development process, the challenges and solutions they found. One app in particular made by Alibaba is used by more than <strong>50 million</strong> people. Google Ads run on Flutter, and you’ll find financial services, streaming services, productivity apps, and of course games.</p><p>But, more important is that whoever you talk to that has developed an app with Flutter will tell you that it took less time and was more straightforward doing it with Flutter, and that certainly includes me, and hopefully one day you as well. Okay, let’s have a look at what you need to start building apps with Flutter.</p><h4><strong>In order to start your Flutter adventure, you need a few tools</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1LlAVuKAKwvU3cXQNnkLDg.png" /></figure><ul><li>A PC or a Mac with a recent Windows, macOS, Linux or Chrome OS machine. To target iOS devices, you will need a Mac unless you use a third‑party service. For desktop devices, you need to use the same system you are targeting. If you want to create a Windows app, you’ll need Windows. If you want to create a macOS app, you’ll need a Mac. And the same for Linux or Chrome OS.</li><li>The Flutter SDK, you can download it at the flutter developers page. There all instructions they gave you how to setup in your environment.</li><li>If you want to develop for mobile, you will need to set up your environment. To try out your code, you should also have an Android or iOS device. Alternatively, you can install an emulator or simulator. They tend to take system resources, so if you are working on a slow machine, the physical device may be a better option.</li><li>The editor of your choice, the supported editors are <strong>Android Studio or IntelliJ IDEA, Visual Studio Code, and Emacs</strong>. Actually, you could use any text editor combined with the Flutter command line tools, but your life will be much easier if you use the plugins that are available for Visual Studio Code, Android Studio or IntelliJ IDEA as you get code completion and debug features and several other advantages.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yKyusR8PQFBy4MMzVFaMcQ.png" /></figure><p>When you develop for Flutter, you use a language called <strong>Dart</strong>. It’s now at version 2. It’s a strongly typed, object‑oriented programming language developed by Google. If you don’t know Dart, don’t worry. If you are familiar with C# or Java or Kotlin or Swift or TypeScript or even JavaScript, you’ll have no problems at all with Dart. You’ll see that it’s intuitive and easy to learn<strong>.</strong></p><p>After having installed everything, the end result is that in your editor you have the Flutter project templates available. This is <strong>Visual Studio Code</strong>. In order to create a new Flutter app from the command palette, you can just type new flutter project, and after choosing a name and selecting the location.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ESu-ogceMbvAjUUJQ7ZM_w.png" /></figure><p>The project with all the required files and templates will be created for you with a Hello World app ready to be tried and used. You can try it out immediately on an emulator or a physical device and see whether it’s working as expected. The code for this app is almost entirely contained in the <strong>main.dart</strong> file in the lib folder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kN2lGz36RA57wSm7amk3Eg.png" /></figure><p>Something went wrong, you can use the <strong>flutter docto</strong>r command from the command line or from your editor. This will give you useful information about the state of your Flutter installation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LISR4ck_yr09O09F7JG-RQ.png" /></figure><p>The complete setup starting from an empty machine might take roughly an hour, but this may vary drastically depending on the speed of your machine and your internet connection.</p><h4><strong>Overview of the architecture of a Flutter app</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7xegIbADRFUA_011mBsHqg.png" /></figure><ul><li>In particular, we’ll talk about <strong>widgets</strong>, which are the main building block of an app user interface in Flutter, and you’ll see a few examples of widgets.</li><li>We’ll introduce <strong>state</strong>, which will allow you to make apps interactive.</li><li>Next, you’ll see these concepts in action with two very basic examples of a <strong>Hello World app</strong>.</li><li>Finally, we’ll talk about the <strong>BLoC pattern</strong>, which may let you create reusable code by making clean and scalable apps.</li></ul><h4><strong>Let’s get started</strong></h4><p>One of the concepts you’ll often hear when dealing with Flutter is that in Flutter, everything is a widget.</p><p>So, what is a widget?</p><p><strong>A widget is the basic building block of the user interface in a Flutter app.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xvhwm33yIt5-cmm3Psd5bQ.png" /></figure><p>More precisely, each widget is an immutable declaration of part of the user interface. So, a text, a button or an image are widgets, but a font or a color scheme are also widgets, styles like padding that you use to create space between elements and theme are also widgets, layout elements like columns, rows, tables are widgets. Even MaterialApp, which is the container that you’ll most likely use for creating Material Design apps is a widget itself.</p><p>By the way, Material Design is a design language that, Google developed in 2014 based on materials like paper and ink, but with an implementation even more advanced than physical materials.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oHKi8GOn4bw4NC9EOJc-Pw.png" /></figure><p>If you want to learn more about that, have a look at the <a href="http://material.io/"><strong>material.io</strong></a> website. This is a rich website aimed at designers and developers full of examples and ideas that can be used for the web, iOS, Android, and of course your next great app in Flutter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2PXlxzAzjxZwFa2jfC2rjQ.png" /></figure><p>Flutter in particular has a library called <strong>material.dart</strong> that contains widgets that implement the material design principles. We’ll talk more about developing interfaces for iOS and Android later. But to sum it up, it’s absolutely okay to use Material Design on iOS devices and not only Android.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7oN9ZV2jW5iIw1U67l2bNA.png" /></figure><p>Let’s get back to the widget definition for a moment. The <strong>immutable</strong> part in the definition might be confusing at first, even misleading. If widgets are immutable, how can you interact with them? Well, not all widgets are created equal, and one of the first questions you’ll need to ask yourself when designing a widget is will this widget be static or dynamic?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_SyCpb29v8-dyRK_IF8AKQ.png" /></figure><p>Let’s say you want to put some text into your app. Will the text change or not? If the text is supposed to change, like in a text field asking your users some data and making some, action over it, you’ll create a <strong>stateful widget</strong>.</p><p>If the text never changes, like in the title of your app, you’ll create a <strong>stateless widget</strong>. Another example of a stateless widget may be an image containing your logo on the screen.</p><p>The only data the image needs is configured when the widget is created, and it will never change during its lifetime, so it may well be a stateless widget. To sum it up, you use a stateless widget when the part of the user interface you are describing does not depend on anything other than the configuration information of the object. What really changes in a stateful widget is not the widget itself, which by definition is immutable, but its state.</p><p>To put it simply, the state is the information attached to a widget that can change during the widget’s lifecycle. You may be used in other frameworks that completely separate layouts from the logic of the app. With a completely different language, like maybe XML, Flutter has a consistent, unified object model, the widget, and you write widgets in Dart like the business logic of your app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a19-kVukfNFo4sF51e4I5A.png" /></figure><p>So, there are no layout files in Flutter. This may be counterintuitive at first, but with time it becomes a consistent and friendly way of dealing with your layouts. The main advantage of this approach is that you can customize your widgets however you like far more easily than in other languages.</p><p>In Flutter, you build a custom widget by composing smaller widgets instead of extending them. If you need to create a button with a label, an icon, and an animation, you create your own widget that contains all of them. You can also add custom logic to your new component and reuse it easily in other apps. On the flip side, you do not have any drag‑and‑drop design in Android Studio or Visual Studio Code. At this time, you have to write the code of the layout yourself, even if the editors help you with that.</p><p>Actually, it’s now probably worth mentioning the Flutter Studio project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*njkpzdTZNadBxndtRmcAAA.png" /></figure><p>It’s a web application accessible at the link you see on the screen. Its <a href="http://flutterstudio.app/"><strong>flutterstudio.app</strong></a>, Here, you can design your UI using drag and drop.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xEJ3FLDZ_NPJpm8UQP_XLw.png" /></figure><p>So for example, you could design a textbox, change its properties, and then copy the generated code to your favorite editor. If you’re a designer and don’t care much about coding or if you want to create a prototype very quickly, this could be an invaluable tool.</p><p>You can also try it on different devices, both iOS and Android, and you can even try your layout with different orientations.</p><p>It really is a very interesting project, and hopefully it will be maintained and developed further in the future.</p><h4><strong>Widgets</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8LMmTJniJk1OCbAYGeejjw.png" /></figure><p>There are, of course, all kinds of widgets in Flutter.</p><p>Let’s see three of them</p><ul><li>Layout widgets</li><li>Gestures</li><li>Animations.</li></ul><p>Layout widgets generally contain other widgets. So you don’t really see them, but they have properties and features that you can use when dealing with their content. For a full list of them, have a look at the official documentation. As you can see, there are several layout widgets, but here introduce you to four layout widgets that you’ll probably use in most of your apps.</p><ul><li>Row</li><li>Column</li><li>Stack</li><li>ListView</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0YDOMLsVjrRurvyif_UJqA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WGZqG_yes792fiYla-pDlQ.png" /></figure><p>The row layout is a list of child widgets placed horizontally, and the column is a list of child widgets placed vertically. These are probably the simplest layout widgets, you’ll use in your apps.</p><p>When there are many widgets you want to show, more than fit the screen, you’ll want to use a ListView. When you use a ListView, the children will scroll automatically, and you can use it both horizontally and vertically.</p><p>A stack is a layout widget that positions its children relative to the edges of its box. So this is ideal when you want to overlay widgets on top of each other, but also when you want to decide exactly how to position an element inside another element.</p><p>There are widgets that put elements on your screen, like a button, or a text, or an image. There are widgets that deal with the layout, like rows, columns, ListView, and stacks. An important feature your mobile app will certainly have is dealing with gestures, and there’s one widget called GestureDetector.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b9MHinpsZ03KG2nvpriRiQ.png" /></figure><p>As the name implies, a GestureDetector is a widget that detects gestures. Inside the GestureDetector, you can insert any other widget. It works like this. In the body of your layout, you insert a GestureDetector. This widget has properties that respond to gestures of your user.</p><p>In the document you can see a few examples of that</p><ul><li>onTap</li><li>onDoubleTap</li><li>onLongPress</li></ul><p>There are, of course, several others including vertical and horizontal drags. Inside each of those gesture properties, you can add your code to react to the event. It’s incredibly flexible and easy to implement.</p><p>Another of the defining features of Flutter is probably how fast you can create great animations.</p><p>In Flutter, you can use two kinds of animations</p><ul><li>Tween animations</li><li>Physics-based animations.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xs7HjMgQMzWsgxByZsYjOA.png" /></figure><p>Tween is the short for in betweening. In a tween animation, you define the beginning and ending points, the timeline, and the curve the defines the timing and speed of the transition.</p><p>Flutter will calculate automatically how to transition from the beginning to the end of your animation. And this is the easiest way of creating an animation.</p><p>In physics-based animation, motion is modeled to resemble real-world behavior. An example of this can be flipping a coin, or making an object fall down to the ground. Its speed will depend on its weight and the distance from the ground. Physics-based animations are governed by physics laws and forces. This is an extremely powerful tool that was added to Flutter to create realistic compelling advanced animations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hrzXXSEPu7P1DRiHE7H4PA.png" /></figure><p>To sum up what we’ve seen so far, from an architectural point of view, every UI element in Flutter is a widget. You compose widgets to create rich and complex UIs, and this is called the widget tree.</p><p>All widgets are immutable, so if you have to make changes to the information attached to the UI, you interact with the state of a widget. When the state changes, the widget is rebuilt.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/662/1*N6KMv7TZ2KMajfgDKI1GOw.png" /></figure><p>There is a useful tool called <strong>Widget Inspector</strong> that shows the widget tree of your user interface. It also has a great feature. When you select any widget from your device, the inspector will automatically recognize it, showing its properties, ancestors, and descendants. So, as you might guess from these concepts, the actual code that you write for your Flutter apps to make them interactive and, well, useful, your business logic in other words, is dealing with the state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QbLhwt_uasl1WWhZT35F0w.png" /></figure><p>Of course, you can create your own classes that have nothing to do with the UI, for example a class that reads and writes data from a database or from a web service. But at some point you’ll need to present the results of your logic to the user interface, and so at some point you’ll need to interact with the state of your widgets. So, you’ve seen that you design the UI through widgets in Flutter and make widgets interactive with state. Let’s see how you can do all.</p><p>We have introduced several concepts so far, so let’s have a look at some code to make it a bit clearer<strong>.</strong></p><p>So here we won’t go into many details with the code. It’s to give you an example of the concepts we’ve discussed so far. The examples will be extremely basic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PPR3UMGs68vlrj6qjDXafA.png" /></figure><p>I’ve created an app in Flutter, following the process we have seen in the previous , using Visual Studio Code and an iOS emulator, but of course, you can use any other configuration we’ve discussed.</p><p>In the main.dart file, I have changed the content with the code you see on the attached screen shot. This is probably the simplest Flutter app we can make right now.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qcah3-1au3572McbSd2Ytg.png" /></figure><p>Let’s have a look at the result first on an iOS emulator, and then we’ll get to the code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*46JQno5oTEVkEYJVSpGY7A.png" /></figure><p>So, we have a white screen and in the center there’s a text, Hello. Very creative of course. Then there’s an app bar that contains another text, App Bar Title.</p><p>Okay, as simple as it is, it still looks like an app, right? So let’s get to the code.</p><pre>import &#39;package:flutter/material.dart&#39;;</pre><p>The first line imports the material.dart library that we mentioned previously. You might remember that this contains several widgets that follow the Material Design pattern.</p><pre>void main() {</pre><pre>runApp(const MyApp());</pre><pre>}</pre><p>Then we have the entry point of every Flutter app, which is the main method. In here, we are calling a class called MyApp, which we define here. This is a StatelessWidget. Every stateless widget has a build method that returns a widget. Here, we are returning a MaterialApp, which is what you’ll likely do for most, if not all, your apps.</p><p>Remember, MaterialApp is also a widget. This widget has some properties, for example, title, which is the title of the app.</p><pre>return Scaffold(</pre><pre>appBar: AppBar(</pre><pre>title: const Text(&quot;Hello&quot;),</pre><pre>),</pre><pre>body: const Center(</pre><pre>child: Text(&quot;Hello&quot;),</pre><pre>),</pre><pre>);</pre><p>Here we call another widget called Scaffold. The Scaffold has an AppBar widget, the blue bar we see on our app, and the AppBar has a title property that contains a Text widget whose content is App Bar Title.</p><p>The Scaffold also has a body property that contains a layout widget called Center that centers its content, both horizontally and vertically, and as its child property, it has another text widget whose content is Hello.</p><p>So you see, composing the widgets in a hierarchical order makes the UI of your app.</p><p>Now showing off the hot reload feature. Let’s change the text in the center widget to <strong>HOT RELOA</strong>D, and you see that the app responds immediately.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hN2eExsfB_1ua-DgYx5mEQ.png" /></figure><p>Now, we’ve seen before that this is a StatelessWidget, so we cannot change anything here after the first configuration.</p><p>Let’s have a look at something a bit more interactive. Here we’ll use the state that, as you remember, is the information attached to a widget that can change during the widget lifecycle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u94qMAsUquLQxxD-zYybYw.png" /></figure><p>So in this second version of the Hello World app, there’s a text field. Here, you can write something, your name for instance, and below the text field widget there’s some text. In the text, this incredibly useless app will say Hello, then concatenate your name transformed into uppercase, and then it will even put an exclamation mark after your name. As you can guess, the interesting part is not the app itself, but the fact that the text changes.</p><p>And as all widgets are immutable, the only explanation is that we are dealing with a state of the widgets here.</p><p>Let’s briefly see how with the code. The app is the same as before, but in the body of the Scaffold, instead of putting the text, we are now calling a HelloText object.</p><pre>class HelloText extends StatefulWidget {</pre><pre>const HelloText({Key? key}) : super(key: key);</pre><pre>@override</pre><pre>State&lt;HelloText&gt; createState() =&gt; _HelloTextState();</pre><pre>}</pre><pre>class _HelloTextState extends State&lt;HelloText&gt; {</pre><pre>String helloText = &quot;&quot;;</pre><pre>@override</pre><pre>Widget build(BuildContext context) {</pre><pre>return Column(</pre><pre>children: [</pre><pre>TextField(</pre><pre>onChanged: (text) =&gt; sayHello(text),</pre><pre>controller: myController,</pre><pre>),</pre><pre>Text(helloText)</pre><pre>],</pre><pre>);</pre><pre>}</pre><pre>void sayHello(String text) {</pre><pre>setState(() {</pre><pre>helloText = &quot;Hello &quot; + text.toUpperCase() + &quot;!&quot;;</pre><pre>});</pre><pre>}</pre><pre>final myController = TextEditingController();</pre><pre>}</pre><p>HelloText is a class that extends a StatefulWidget. StatefulWidgets have the state, and here we are calling the createState method to return HelloState, which is defined below. HelloState extends a state of HelloText, and as a UI, we are building a column that contains the TextField, and below it, the text.</p><p>Note that in the HelloState class, we have define a helloText string that will contain the information that changes during the lifetime of the HelloText widget.</p><pre>void sayHello(String text) {</pre><pre>setState(() {</pre><pre>helloText = &quot;Hello &quot; + text.toUpperCase() + &quot;!&quot;;</pre><pre>});</pre><pre>}</pre><p>Now, here comes the interesting part. When you type something in the TextField, this is the onChanged property, we call a function that’s called sayHello, and we pass the text to the function. This function, sayHello, then changes the state, calling the setState method and concatenating hello and the text that was passed and an exclamation mark.</p><p>The widget then gets rethrown. So to sum this up, HelloText is a stateful widget that has a state called HelloState.</p><pre>return Column(</pre><pre>children: [</pre><pre>TextField(</pre><pre>onChanged: (text) =&gt; sayHello(text),</pre><pre>controller: myController,</pre><pre>),</pre><pre>Text(helloText)</pre><pre>],</pre><pre>);</pre><p>In the HelloState class, we build the layout that is a column that contains two children widgets, the TextField and the Text. When the content of the TextField changes, the setState method is called to update the UI. So, this is the first method to write your logic. In this case, the sayHello method in Flutter, and this is done in the same class as the UI. While this is a simple and effective approach, I recommend you only use it with small apps and prototypes because it has some pitfalls. Let’s see what they are and a possible approach to solve them.</p><p>You’ve seen that using the setState method makes your apps interactive, but this is not necessarily the best approach unless your apps are very simple.</p><p>There are a few reasons for that.</p><p>First, and most important, you would put at least part of the logic of your app in the same class as your layout. And, generally speaking, it is never a good idea to mix layout and code, both for the risk of writing spaghetti code and because it makes it difficult to maintain and reuse the same code in different apps.</p><p>Second, if you have data that changes in your app and you need to update several widgets in different places, you also risk unnecessarily duplicating your code.</p><p>You have several other ways to write your business logic in Flutter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FE0kG1nFfC7x1Z6-Nl5wrw.png" /></figure><p>The one that mention here is the BLoC pattern that stands for business logic component. That’s because it’s officially supported by Google.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hIK8_59MhiOWGcLzK2zZBQ.png" /></figure><p>BLoCs are based on streams, stream controllers, and sinks. Okay, a lot of concepts here. Let’s see what all this means. The main building part of a BLoC, or business logic component, is a stream.</p><p>You could think of a stream as a pipe. The pipe has two ends, one allows you to insert data into it and the other one is where data gets out. It’s a one‑way pipe.</p><p>When you insert something into the pipe, it flows inside the pipe and goes out by the other end. In Flutter, the pipe is called a stream.</p><p>To control the stream, you use a StreamController.</p><p>The way in into the stream is the sink property of the StreamController.</p><p>The way out of the stream is the stream property of the StreamController.</p><p>In order to use the stream and be notified when something gets out of it, you need to listen to the stream, which in this case is not music, but data. So you define a listener with a StreamSubscription object.</p><p>The StreamSubscription gets notified every time an event related to the stream is triggered, for example whenever some data flows out of the stream or when there is an error. You can also transform the data inside the stream through an object called *StreamTransformer, for example to filter or modify the data.</p><p>Okay, now we have enough elements to talk about the BLoC pattern.</p><p>This was introduced in January 2018 at the Dart Conference.</p><p>In short, the business logic of your app should be moved to BLoCs, and therefore be removed from the UI.</p><p>It should rely on the use of streams for input with sink and output with stream. It should remain platform and environment independent. To sum this up, BLoCs are components that contain the business logic of your app.</p><p>Use sinks to take events from widgets and streams to output the results to the widgets. What happens inside the BLoC is independent from the UI. Ideally with this pattern, you can scale your Flutter apps, reuse code and test them more easily.</p><p>If you have some experience in programming, you are already familiar with null exceptions in your code.</p><p>These are tricky errors because they only happen at runtime and only when specific conditions are met. Another way Flutter makes developers more productive is by enforcing null safety.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qMaKs5e1jEuIbxZH5Z2CBw.png" /></figure><p>In a nutshell, null safety means that by default variables cannot be assigned a null value. And the same is true for function parameters or class fields.</p><p>Let me show you an example of that. you see DartPad attached image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6mvw-7lu4HACRLEjOpI6GQ.png" /></figure><p>It is a tool that lets you play with Dart in your browser, and it’s perfect when you want to try out some Dart syntax without creating a new project or edit the code in an existing one. You can find it at <a href="http://dartpad.dev/"><strong>dartpad.dev</strong></a>.</p><pre>int doubleNumber(int oldNumber) =&gt; oldNumber*2;</pre><p>In the example you see on the screen, there is a method called doubleNumber that takes an integer as a parameter and multiplies it by 2. In the main method, we declare an integer called myNumber and then we call the doubleNumber method, passing myNumber. I guess you already see the problem here, don’t you? Wen we run this code as expected we get a type error because you cannot multiply a null value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ydDMeBdGojrsyi8uLHXihQ.png" /></figure><p>And as you can see, now the code won’t even run as DartPad tells us that we must give a value to myNumber before using it.</p><p>So, let’s give it a value of 21 and then let’s run the code again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dmn2Ub7wbG3oE6FC0uDQ_A.png" /></figure><p>Now, our code works and we get 42 as a result. You see how much time you can save enforcing little safety. If your code is not null safe, it won’t even compile. In this way, Dart and Flutter help you write cleaner and safer code in your apps.</p><h4>Basic Flutter Tools</h4><p>Here , I’ll be using Visual Studio Code on a mac machine, but everything you’ll see is almost identical on a Windows or on a Linux machine.</p><p>Let’s begin with a basic Flutter app.</p><p>We’ll just create a new Flutter app<strong>.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G2WTi68utz2TaL0i2v8vpA.png" /></figure><p>And after everything is set up, we’ll be able to see it on an emulator that’s been already started.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kXdUu50Y82bnES7rWksILA.png" /></figure><p>This is the basic app we’ve already seen in a previous slides. There’s not much to debug here, but let’s see the process anyway.</p><p>Probably the single most important tool to debug an app is being able to step into the code you have written, and to do that, you use breakpoints. In order to put a breakpoint, you can click at the left of the line where you want to interrupt your code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jl3KhgRse3615AsheEBtIQ.png" /></figure><p>And now, when we press the plus button in our app, the execution stops at the breakpoint we set.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K1VT4OI4ggP0ndoR76EhxA.png" /></figure><p>This is extremely useful as you can check what’s happening during the execution of your app.</p><p>In the Variables pane, you can see the values of all the variables that are in scope.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OIygTQtNExbovC9DAcFTZQ.png" /></figure><p>So for example, you can see that the _counter variable now equals to 0.</p><p>Here you have the option to step into the selected line and see what happens after we step over the counter++ instruction where our _counter variable is now equal to 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*8r6BBdkP7y4cqNggUqF7Og.png" /></figure><p>A feature I love is the ability to change the code and see the results in real time during debug.</p><p>For example, let’s change the _counter increment command to _counter+=2. So, we can press the Hot Reload button and remove the breakpoint, and now each time we press the plus button, the number increment will be two instead of one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hkFScQA_xJuBpc_kF8wzsg.png" /></figure><p>Okay, let’s say we want to add a few widgets. You’ve seen in previous modules that you can just type the code and add widgets to the screen, but there’s a faster way called snippets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ABuN50jCDGyQzxMt4sPcig.png" /></figure><p>For example, if you want to create a stateless widget, you can just type “<strong>stles”</strong>, and as you can see, the editor creates all the structure and the code of a stateless widget.</p><p>You can create stateless widgets, stateful widgets, and animations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EfaiiLLHYdzGZlLGryhVdg.png" /></figure><p>Another great tool you can use on Visual Studio Code are assists.</p><p>Let’s see an example. Let’s say that we want to put a widget into a center widget. In order to do that, we can just put the cursor on the widget we want to modify.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n6liJm-50BB-Ec8bb4PM1w.png" /></figure><p>A light bulb appears, and if you click on that, the assist will show up. Now you can see that there are a number of actions you can choose from. If you want to include this widget into a Center widget, you can just choose the action to do so.</p><p>An alternative to call the assist instead of clicking on the light bulb is pressing Ctrl+period or Command+period on a Mac. Very similar to assists are quick fixes.</p><p>They work exactly in the same way, but they are used when there is an error into your code, and the editor helps you fix your errors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CWNk2drjfUVH6x-pxJE5LA.png" /></figure><p>And by the way, if you want to view all your code problems, you can just select View, Problems, or Ctrl+Shift+M, or Command+Shift+M on a Mac.</p><p>An issue that can be seen while developing is shown in the Problems pane.</p><p>There are also other advanced debugging techniques that you can use for your more complex apps. If you want to learn more about those, have a look at the flutter documentation.</p><p>The last tool I’d like to show you is automatic formatting. To format the code in the current code window, you can just right-click and select Format Document.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*UhB-0eglI_w7KlDY7QbS1Q.png" /></figure><p>It is also possible to automatically format the code whenever you save a file. In order to do that, we can change the Visual Studio Code settings by adding the Editor: Format On Save property and setting it to true.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3ezMr8ElVMqrr6zT8lV9eQ.png" /></figure><p>Great! Now that you have an idea on how Visual Studio Code helps you with Flutter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sfGSrBfBkdAHfMkrD7ZPnw.png" /></figure><p>let’s see how to use packages in a Flutter app.</p><p>We don’t always need to reinvent the wheel, and what may influence the decision to use one framework over another is how many tools and libraries are available for the most common and also some uncommon features your software will build upon.</p><p>The approach the Flutter developers chose to make the language complete are packages.</p><p>According to the official Flutter website, Flutter supports using shared packages contributed by other developers to the Flutter and Dart ecosystems.</p><p>Basically, packages are libraries you can import into your own projects to speed some of the features you want to include in your app.</p><p>There are packages to deal with the device pictures, like image picker, packages for network recasts, like HTTP, packages for databases, like SQLite, to play videos, like video player, to control the camera of your device, like camera.</p><p>The list could go on and on, but you get the idea. This is a very flexible approach. Actually, you could be the author of the next great package in Flutter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_RIlPWCcmNr-XZJw5_Mv7g.png" /></figure><p>There’s a website called <a href="http://pub.dev/">pub.dev</a> that contains an extensive list of packages that can be searched and ordered. What’s also great is that these packages are checked, analysed, and rated for factors like health, popularity, and maintenance.</p><p>Let’s say, for example, that you want to include a database into your app. In the <a href="http://pub.dev/"><strong>pub.dev</strong></a> website.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TA3bkZCoqkp81wAlXJXd2Q.png" /></figure><p>If you search database, you get a list of results with a number of likes, the pub points, which is a rating system where the highest score is 130, and the popularity.</p><p>You can also check which platforms are supported by the package.</p><p>And other useful information you find is whether the package supports null safety.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EyO6JqHs2KcBqG3P5XCc7Q.png" /></figure><p>If you click on one of the packages, let’s say sembast, you get to the main package page.</p><p>Here, you can find a lot of information, examples, use cases, and documentation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lyLEP2WzWG6MK5LXPmShAg.png" /></figure><p>In the Installing page, you have information on how to include this package into your project.</p><p>The process is basically the same for every package, and it is rather straightforward. So once you follow the required steps for one package, you’ll be able to do it for any other. In the Versions page, you get the list of the updates of the library.</p><p>To sum it up, packages are another tool that can make working with Flutter a real pleasure. And there’s one package particularly useful if you want to support languages other than English. Let’s talk about internationalizations, next.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iZavBbVCiZSApWxD-jVQMQ.png" /></figure><p>By default, Flutter only provides US English localisation, but you might want to add other languages and locales for dates, currency or measures. Fortunately, there’s a package called Flutter_localizations that, at the time of this recording, supports 78 languages.</p><p>But let’s have a look at the main steps required to internationalise your app.</p><p>There’s a Locale class used to identify the user’s language. When you build your app, you can choose which locales you want to support. When you build an internationalised app, your app will respond by displaying values that are locale‑specific.</p><p>For example, if you have an internationalised text widget, an English user might see Hello on the screen, but an Italian user would see Ciao, and a Spanish one, Hola.</p><p>The main steps to achieve these results are shown below.</p><p>First, you add the localisation dependencies. In particular, you need to add the Flutter_localizations package to the <strong>pubspec.yaml</strong> configuration file in your project.</p><p>Then, you create the app Localization class that will have all the localization helpers to use in the whole app.</p><p>Then, you create the string translations. The translations are made using application resource bundle files, which have an .arb extension. Each ARB file contains a single JSON table that maps from resource IDs to localized values.</p><p>To finalize the localization, we have to say to our app to use the AppLocalizationsDelegate class as the app Localization class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xqWxA6OD0USFdNflta1Sdg.png" /></figure><p>You can see an example of two ARB files, one for English and one for Italian. As you can see, they are just JSON files. When you need to support other languages, you just need to add the new language in your configuration and add the ARB file to your project. This is an extremely flexible way of adding support to different languages into your app.</p><p>While most Flutter apps target mobile platforms, it’s also very easy to create and publish web and desktop apps.</p><p>For this example, I’ll be using the default app that you get when you create a new Flutter project.</p><p>Let’s begin with the web. You can target the web through the command line interface or from your editor. So, from your terminal, you can just type flutter build web.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9wHrZfkaimojFKZi-1fboQ.png" /></figure><p>This will make your code compile to JavaScript. It will also be minified for use in production. You’ll find an index.html file in the build\web folder of your project once you build the web.</p><p>You can run it immediately to see how it looks. Using flutter run -d chrome command</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sblHbgL2DSuN2DDbv_GCaw.png" /></figure><p>I’ll do it with Visual Studio Code, but you can also run it from any other editor or from the command line.</p><p>And here it is. The demo app is working perfectly on a browser.</p><p>Most Flutter developers recommend using Flutter for the web when you want to build single‑page applications or progressive web applications or when you need to port mobile apps to the web.</p><p>I would not recommend Flutter for static, text‑based HTML content, but, of course, Flutter fully supports this scenario as well. Once you build your Flutter app for the web, you can deploy it to any web server. The procedure is quite similar for desktop apps.</p><p>Before running your app on a desktop, you have to enable your platform first. Here, I’m using macos, but, of course, you can deploy an app for a Windows or Linux as well.</p><p>From the terminal, you can type</p><pre>flutter config ‑‑enable‑macos‑desktop</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m33r_fF9i-dCq5cN8AffAg.png" /></figure><p>Once the platform is enabled, you may need to restart your editor, then you can run the app targeting your desktop system. So, let’s select macos as target and run the app or you can run.</p><pre>flutter run -d macos</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DWk_3i4H8ud0JMRcQ8t3VQ.png" /></figure><p>And as you can see, you have a fully functional desktop app. That’s the power of Flutter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fUeCLBmhuMy0D7rGDKBlXA.png" /></figure><h4>Conclusion</h4><p>As you can see, Flutter is one of the most innovative mobile technologies on the market right now. For businesses looking to create applications on both iOS and Android, Flutter is a great option. If you are seeking apps with amazing UI and high performance — Flutter is the best option as well.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c326163b926c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ascentic-technology/flutter-the-big-picture-c326163b926c">Flutter: The Big Picture</a> was originally published in <a href="https://medium.com/ascentic-technology">Ascentic Technology</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android Jetpack Compose]]></title>
            <link>https://medium.com/@edirisinghe.cha/android-jetpack-compose-fb4cab297c28?source=rss-e75762970f01------2</link>
            <guid isPermaLink="false">https://medium.com/p/fb4cab297c28</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <dc:creator><![CDATA[Chathuranga Edirisinghe]]></dc:creator>
            <pubDate>Mon, 29 Nov 2021 07:07:52 GMT</pubDate>
            <atom:updated>2021-11-29T07:07:52.578Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*5qgGqCQdwolbL5x0coBXSA.png" /></figure><p><strong>What is Jetpack Compose</strong></p><p>Jetpack compose is just a new way of designing native android apps using Kotlin , so normally we do interface designing in android using xml, that was terrible in my opinion it was really not much fun and it made things so complicated because so often you didnt know should we put that in the xml file should we create a drawable file should we put that into our themes file all that were things we dont need to worry about anymore because now we design our android apps in Kotlin, and simply Jetpack Compose is no more xml.</p><p>lets move into whats this jetpack compose is,</p><p>1. Its Android’s new, modern declarative UI toolkit.</p><p>2. Compose is built on Kotlin using its full power and express enough to build intuitive APIs.</p><p>3. Jetpack Compose is unbundled, like all Jetpack libraries so you can update at your own pace and have consistent behavior across API versions.</p><p>4. And lastly, we know that you have existing apps which you can’t just rewrite with compose although after you’ve used it, you might want to.</p><p>Composeis designed to interoperate with Android Views. so you can gradually migrate</p><p>today, jetpack Compose is in Beta. That means it’s feature complete for 1.0 ,and we’ll focusing on polishing and stabilizing the APIs.</p><p>Now is a great time to learn Compose and get ready to adopt it.The most exciting thing about Jetpack Compose is that it makes building Android UI faster and easier.</p><p>Lets examine how it does this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*LlVOIZ4j8gKrYPcA67OenA.png" /></figure><p>Compose is a declarative UI toolkit. Lets break those two concepts apart and look at each in turn.</p><p>First the declarative part</p><p>Today apps aren’t static data, they update, they’are alive. Traditionally with Android Views you would declare your UI in XML but then, to update your UI, if any data changed, you need to mutate it. You do this by looking up views and setting properties on them.</p><p>So whenever your appplication state changed, for example once a database or network call loads or after user interaction, you would have to update your UI with this new info to keep everything in sync.</p><p>This can get complex as each view holds some state that you need to ensure you update.</p><p>This overhead of synchronizing state between your model and your UI is a huge source of bugs. Its your responsiblility as a developer to ensure that everything is updated.</p><p>As your app and UI gets more complex, its easy to get this wrong. Declarative UIs like Compose, take a different approach. They transform state into UI. The UI is immutable. Theres no way to update it after its been produced. So if your app state changed, we re-execute to transform this new state into a new representation.</p><p>This avoids the synchronization issues entirely. You rgenereate your entire UI. Compose is actually smart enoughf to skip any work for elements that havent changed to make it more efficient, but conceptually, it regenereates the entire UI for a given state. Your code describes what the UI should look like for a givem state, not how to produce it. So, jetpack compose is very new, it’s not included in stable android studio, so what we need to do is we need to download android studio Canary, so the Canary version of android studio is just kind of an experimental version. We can download it go to <a href="http://developer.android.com/">developer.android.com</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*oq9D0fwV5C8kllhSTSKHBA.png" /></figure><p>Main difference is there is no layout folder anymore, becuase we don’t have xml files anymore.</p><pre>class MainActivity : ComponentActivity() {<br>     override fun onCreate(savedInstanceState: Bundle?) {<br>         super.onCreate(savedInstanceState)<br>         <em>setContent </em><strong>{<br> <br>             </strong><em>Greeting</em>(&quot;Android&quot;)<br> <br>         <strong>}<br>     </strong>}<br> }<br> <br> @Composable<br> fun Greeting(name: String) {<br>     <em>Text</em>(text = &quot;Hello $name!&quot;)<br> }<br> <br> @Preview(showBackground = true)<br> @Composable<br> fun DefaultPreview() {<br> <br>     <em>Greeting</em>(&quot;Android1&quot;)<br> <br> }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IPhSQyCDdnLChs6gJ-RbzQ.png" /></figure><p>This is a basic code structure in Jetpack. onCreate function is called when our activity is created and in that function have that setContent function, so before compose it had setContentview that was used to assign a layout resource id so an xml layout to our activity. Now it dont have views anymore because in compose we speak of Composables what it called view before is now a Composable and you can see that here this function Greeting is annotated with at composable and that is actually now what was a view before an android so to define UI now in android we simply write functions in Kotlin and we annotate these functions that composable so what we try to do here is we try to separate our UI into single components if you come from web development if you come from flutter or whatever then you will probably know that concept. Its basically separating the UI into cmponents that makes it very reusable so if we consider Android Studio here you might make this project list composable you might make each individual item of that project listed composable so you can reuse that over and over again without having all that boilerplate code we had in xml because there we just needed to copy a view if we wanted to have it like five times now with Composer we can define how that view looks like just once and reuse that.</p><p>So now every activity now has its own setContent function here which just has all the components or the composables it should draw the actual components and composables we will put these into these kotlin functions and of course we can put these into single files to structure our project in a nice way.</p><p>Here are some of the basic functions I am going to discuss here.</p><p>· Rows Columns &amp; Basic Sizing</p><p>· Modifiers</p><p>· Creating an Image Card Composable</p><p>· State</p><p>· Styling Text</p><p><strong>Rows , Columns &amp; Basic Sizing</strong></p><pre><em>setContent </em><strong>{</strong></pre><pre><strong>    </strong><em>Text</em>(&quot;Hello&quot;)</pre><pre>    <em>Text</em>(&quot;World&quot;)</pre><pre><strong>}</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CV8YtWmBDvBSUV7x-5m6kw.png" /></figure><p>If we write a two text like above, you can see jetpack compose places these texts on top of each other by default, and this is of course not what we want here and the solution to this is either a row or a column so there is composable which is called Column. Now these texts are displayed on top of each other, because we chose a column-based layout here, so these items are placed like that.</p><pre><em>Column </em><strong>{</strong></pre><pre><strong>    </strong><em>Text</em>(&quot;Hello&quot;)</pre><pre>    <em>Text</em>(&quot;World&quot;)</pre><pre><strong>}</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*elcedl-hSlhJPfjr78Ft8g.png" /></figure><p>Now what happend if we choose Row instead of a column here , now its placed next to each other , but there’s a lot more cool stuff we can do with these rows and columns, we can add extra option here when we press “control+p”, there are much more things we can add between these two paranthasees, I will add vertical arrangement and horizontal alignment, whats the diference between alignment and arrangement and for that we need to know that each column and each row has a main axis and a cross axis so the main axis is alway the axis in which new items are basically stacked so if we take a look in our device that is still a row here for a row the main axis is the horizontal axis because thats the direction in which we basically put in our items and the cross axis for a row is the vertical axis because you can think of that like this road was a street and if you want to cross that street then you would go that direction and if you would drive that street, then you would go that direction so driving on that street is the main axis and crossing the street is called the cross axis, and we take a look at our column here there our axis are basically swapped so far a coloumn those text are basically stacked on top of each other so this one is on the top and this one is at the bottom so in this case the street would go from top to bottom bcz this direction in which our items are stacked and the cross axis for a column would be the horizontal axis so with horizontal alignment and vertical arrangement we can just position these items and align these in our column or row.</p><pre><em>Column</em>(</pre><pre>    horizontalAlignment = Alignment.CenterHorizontally</pre><pre>) <strong>{</strong></pre><pre><strong>    </strong><em>Text</em>(&quot;Hello&quot;)</pre><pre>    <em>Text</em>(&quot;World&quot;)</pre><pre><strong>}</strong></pre><p>Now I add horizontal Alignmant, so if we would launch this app right now nothing really changes so why is that the reason is that by default compose will make these column and rows and any other composable only as wide and as high as it needs to be, and to actually visualize that a little bit easier we can add what is called a modifire.</p><pre><em>Column</em>(</pre><pre>    modifier = Modifier.<em>background</em>(Color.Green),</pre><pre>    horizontalAlignment = Alignment.CenterHorizontally</pre><pre>) <strong>{</strong></pre><pre><strong>    </strong><em>Text</em>(&quot;Hello&quot;)</pre><pre>    <em>Text</em>(&quot;World&quot;)</pre><pre><strong>}</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M436GCr80g0rAHj-3VLaBA.png" /></figure><p>I won’t go deep into modifires here in this I will discuss it later, but it will help us to understand this alignment here and it will help us to size our containers our columns and rows, we can set the modifire, import that background and with that we can basically give our coloumn a background color we can choose “color. Green” as example.</p><pre><em>Column</em>(</pre><pre>    modifier = Modifier</pre><pre>        .<em>fillMaxSize</em>()</pre><pre>        .<em>background</em>(Color.Green),</pre><pre>    horizontalAlignment = Alignment.CenterHorizontally</pre><pre>) <strong>{</strong></pre><pre><strong>    </strong><em>Text</em>(&quot;Hello&quot;)</pre><pre>    <em>Text</em>(&quot;World&quot;)</pre><pre><strong>}</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1uUwkdIe7Fj0nkxENPQZjQ.png" /></figure><p>And you will much better see now why our centering didnt work because it Coloumn width it takes on the text width, so what we can do to fix this add “fillMaxSize()” to modifire. Now it fills our whole page, and our text are centerd horizontally.</p><pre><em>Column</em>(</pre><pre>    modifier = Modifier</pre><pre>        .<em>fillMaxSize</em>()</pre><pre>        .<em>background</em>(Color.Green),</pre><pre>    horizontalAlignment = Alignment.CenterHorizontally,</pre><pre>    verticalArrangement = Arrangement.SpaceEvenly</pre><pre>) <strong>{</strong></pre><pre><strong>    </strong><em>Text</em>(&quot;Hello&quot;)</pre><pre>    <em>Text</em>(&quot;World&quot;)</pre><pre><strong>}</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vnjjZAXbeiWz2RsARho0tw.png" /></figure><p>Now verticalArrangement, now I can arrange our text in vertically choosing those options. When I give space between it takes as much space between the text If I add another text we can see it nicely</p><pre><em>Column</em>(</pre><pre>    modifier = Modifier</pre><pre>        .<em>fillMaxSize</em>()</pre><pre>        .<em>background</em>(Color.Green),</pre><pre>    horizontalAlignment = Alignment.CenterHorizontally,</pre><pre>    verticalArrangement = Arrangement.SpaceBetween</pre><pre>) <strong>{</strong></pre><pre><strong>    </strong><em>Text</em>(&quot;Hello&quot;)</pre><pre>    <em>Text</em>(&quot;World&quot;)</pre><pre>    <em>Text</em>(&quot;World&quot;)</pre><pre><strong>}</strong></pre><p>When I change this to Row, see it doesnt know these attributes because as I said for a row these two axes are swapped so that means for a row, it has horizontalArrangement and verticalAlignment. I can modify it like this.</p><pre><em>Row</em>(</pre><pre>    modifier = Modifier</pre><pre>        .<em>fillMaxSize</em>()</pre><pre>        .<em>background</em>(Color.Green),</pre><pre>    horizontalArrangement = Arrangement.SpaceEvenly,</pre><pre>    verticalAlignment = Alignment.CenterVertically</pre><pre>) <strong>{</strong></pre><pre><strong>    </strong><em>Text</em>(&quot;Hello&quot;)</pre><pre>    <em>Text</em>(&quot;World&quot;)</pre><pre>    <em>Text</em>(&quot;World&quot;)</pre><pre><strong>}</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RNUp0dRc-pJtW8NOTF8erw.png" /></figure><p>Those are super important to understand this arrangement and alignment because you will need these two all the time when creating layouts with compose.</p><p>Now I going to show add size modifires, so right now we only choose to “fillMaxSize()” which will fill all the size there is but we can also set own size.So you can modify parameter in “fillMaxSize()” , that is by default is set to 1, it will fill 100 percent but we could set this as to 0.5f (fractional unit) to 50 percent of our screen, now its takes fifty percent of our height and width.</p><pre><em>Row</em>(</pre><pre>    modifier = Modifier</pre><pre>        .<em>fillMaxSize</em>(0.5f)</pre><pre>        .<em>background</em>(Color.Green),</pre><pre>    horizontalArrangement = Arrangement.SpaceEvenly,</pre><pre>    verticalAlignment = Alignment.CenterVertically</pre><pre>) <strong>{</strong></pre><pre><strong>    </strong><em>Text</em>(&quot;Hello&quot;)</pre><pre>    <em>Text</em>(&quot;World&quot;)</pre><pre>    <em>Text</em>(&quot;World&quot;)</pre><pre><strong>}</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VTSHja4Qotc3K28wQvgYCQ.png" /></figure><p>You can also remove “fillMaxSize(0.5f)”and just directly set the width and height, width is some amount of dp units.</p><pre><em>Row</em>(</pre><pre>    modifier = Modifier</pre><pre>        .<em>width</em>(200.<em>dp</em>)</pre><pre>        .<em>height</em>(300.<em>dp</em>)</pre><pre>        .<em>background</em>(Color.Green),</pre><pre>    horizontalArrangement = Arrangement.SpaceEvenly,</pre><pre>    verticalAlignment = Alignment.CenterVertically</pre><pre>) <strong>{</strong></pre><pre><strong>    </strong><em>Text</em>(&quot;Hello&quot;)</pre><pre>    <em>Text</em>(&quot;World&quot;)</pre><pre>    <em>Text</em>(&quot;World&quot;)</pre><pre><strong>}</strong></pre><p>For example if you like to set set the height to a fractional unit you can do like this</p><p>fillMaxHeight(0.7f) as 70 percent.</p><pre><em>Row</em>(</pre><pre>    modifier = Modifier</pre><pre>        .<em>width</em>(200.<em>dp</em>)</pre><pre>        .<em>fillMaxHeight</em>(0.7f)</pre><pre>        .<em>background</em>(Color.Green),</pre><pre>    horizontalArrangement = Arrangement.SpaceEvenly,</pre><pre>    verticalAlignment = Alignment.CenterVertically</pre><pre>) <strong>{</strong></pre><pre><strong>    </strong><em>Text</em>(&quot;Hello&quot;)</pre><pre>    <em>Text</em>(&quot;World&quot;)</pre><pre>    <em>Text</em>(&quot;World&quot;)</pre><pre><strong>}</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I95KOOGkzKH1aHUo4T5HuQ.png" /></figure><p><strong>Modifiers</strong></p><p>Now here I will dive a little deeper into modifiers, previously I explain you little bit in modifires. So Modifires can be applied to any composable in jetpack compose we can apply this to coloumns, rows , texts , images, and other every components basically change the appearance of everything. So first of all lets create column again and two text like previously , then to the column add “modifire” then add properties like background , fillMaxHeight and width.</p><pre><em>Column</em>(modifier = Modifier</pre><pre>    .<em>background</em>(Color.Green)</pre><pre>    .<em>fillMaxHeight</em>(0.5f)</pre><pre>    .<em>width</em>(300.<em>dp</em>)</pre><pre>) <strong>{</strong></pre><pre><strong>    </strong><em>Text</em>(&quot;Hello&quot;)</pre><pre>    <em>Text</em>(&quot;World&quot;)</pre><pre><strong>}</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sns2h2SOR3Gwv0gdIIiq3w.png" /></figure><p>Another property we can change here with “requredwidth()”, what is the actually difference here we can force the width to be exactly as wide as we specify. So if we set to 300dp it would look exactly the same as width property in a code, what happend if change something like 600dp, and comment required width, now you can see 600dp is wider than our screen. again use requiredwidth now you can see our text are missing , now its really fill that 600dp so the text is some where outside the view so that is just important to know these two attributes.</p><pre><em>Column</em>(modifier = Modifier</pre><pre>    .<em>background</em>(Color.Green)</pre><pre>    .<em>fillMaxHeight</em>(0.5f)</pre><pre>    .<em>width</em>(300.<em>dp</em>)</pre><pre>    .<em>requiredWidth</em>(600.<em>dp</em>)</pre><pre>) <strong>{</strong></pre><pre><strong>    </strong><em>Text</em>(&quot;Hello&quot;)</pre><pre>    <em>Text</em>(&quot;World&quot;)</pre><pre><strong>}</strong></pre><p>I use “fillMaxWidth()” here.</p><pre><em>Column</em>(modifier = Modifier</pre><pre>                .<em>background</em>(Color.Green)</pre><pre>                .<em>fillMaxHeight</em>(0.5f)</pre><pre>                .<em>fillMaxWidth</em>()</pre><pre>// .width(300.dp)</pre><pre>// .requiredWidth(600.dp)</pre><pre>            ) <strong>{</strong></pre><pre><strong>                </strong><em>Text</em>(&quot;Hello&quot;)</pre><pre>                <em>Text</em>(&quot;World&quot;)</pre><pre>            <strong>}</strong></pre><p>Next property to explain you which you already know if you have some experience with android xml layouts if not thats not a problem, which is just padding so padding is a very known concept in designing UIs all the does is it will take a container, in our case the coloumn and it will push the content of that container into its middle basically.</p><p>The padding here to 16dp, then you can see the content of our container pushed to the middle. It is getting 16dp from top and 16 dp from left, we can add padding indvidulay for a specific side without applyng all. If you need to apply only top padding you can set “.padding(top = 16.dp)”.</p><pre><em>Column</em>(modifier = Modifier</pre><pre>    .<em>background</em>(Color.Green)</pre><pre>    .<em>fillMaxHeight</em>(0.5f)</pre><pre>    .<em>fillMaxWidth</em>()</pre><pre>    .<em>padding</em>(16.<em>dp</em>)</pre><pre>) <strong>{</strong></pre><pre><strong>    </strong><em>Text</em>(&quot;Hello&quot;)</pre><pre>    <em>Text</em>(&quot;World&quot;)</pre><pre><strong>}</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rn2NMteTbCdiGhOS4y_w1g.png" /></figure><p>Next property going to show you is offset which we want to apply to our text, we need to add modifire here and add offset.</p><pre><em>setContent </em><strong>{</strong></pre><pre><strong>    </strong><em>Column</em>(modifier = Modifier</pre><pre>        .<em>background</em>(Color.Green)</pre><pre>        .<em>fillMaxHeight</em>(0.5f)</pre><pre>        .<em>fillMaxWidth</em>()</pre><pre>        .<em>padding</em>(top = 16.<em>dp</em>)</pre><pre>    ) <strong>{</strong></pre><pre><strong>        </strong><em>Text</em>(&quot;Hello&quot;,</pre><pre>            Modifier</pre><pre>                .<em>offset</em>(50.<em>dp </em>, 20.<em>dp</em>)</pre><pre>        )</pre><pre>        <em>Text</em>(&quot;World&quot;)</pre><pre>    <strong>}</strong></pre><pre><strong>}</strong></pre><p>It will offset our text, this is like margin, but its wont push away other elements. Offset always starts from the top left corner of a composable, what we do here is we move it to the right by 50dp and to the bottom by 20dp. Now I removed this offset x here and set it to 0, again relaunch, these two text will overlap because we only push down our first text because its offset and not margin this wont effect the text that use below it so if that were margin in xml also push down the bottom text by 20dp to the bottom but here with offset thats not the case.</p><pre><em>setContent </em><strong>{</strong></pre><pre><strong>    </strong><em>Column</em>(modifier = Modifier</pre><pre>        .<em>background</em>(Color.Green)</pre><pre>        .<em>fillMaxHeight</em>(0.5f)</pre><pre>        .<em>fillMaxWidth</em>()</pre><pre>        .<em>padding</em>(top = 20.<em>dp</em>)</pre><pre>    ) <strong>{</strong></pre><pre><strong>        </strong><em>Text</em>(&quot;Hello&quot;,</pre><pre>            Modifier</pre><pre>                .<em>offset</em>(0.<em>dp </em>, 20.<em>dp</em>)</pre><pre>        )</pre><pre>        <em>Spacer</em>(modifier=Modifier.<em>height</em>(50.<em>dp</em>))</pre><pre>        <em>Text</em>(&quot;World&quot;)</pre><pre>    <strong>}</strong></pre><pre><strong>}</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O6y4VBb-dvDrstjB9RjvyA.png" /></figure><p>We can push the second text by using a composable called spacer which will well just lead to some extra space, and we can just apply modifier to that and modify the height and set this to 50dp, that will just insert an empty composable that has a height 50dp, now its no overlap anymore.</p><pre><em>setContent </em><strong>{</strong></pre><pre><strong>    </strong><em>Column</em>(modifier = Modifier</pre><pre>        .<em>background</em>(Color.Green)</pre><pre>        .<em>fillMaxHeight</em>(0.5f)</pre><pre>        .<em>fillMaxWidth</em>()</pre><pre>        .<em>padding</em>(top = 20.<em>dp</em>)</pre><pre>        .<em>border</em>(5.<em>dp</em>,Color.Magenta)</pre><pre>    ) <strong>{</strong></pre><pre><strong>        </strong><em>Text</em>(&quot;Hello&quot;)</pre><pre>        <em>Spacer</em>(modifier=Modifier.<em>height</em>(50.<em>dp</em>))</pre><pre>        <em>Text</em>(&quot;World&quot;)</pre><pre>    <strong>}</strong></pre><pre><strong>}</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2hfIVcBHs3kyM5xwXwGm1g.png" /></figure><p>Next property is border, I will remove this offset here, because that annoying. border property is used to well give our elements a border, lets apply that to our coloumn. I set border width to 5 dp, and color, I will choose Magenta, I leave it like that, and we can see its not sarounded by border because we applied padding to that container.</p><p>I remove this top padding here so the border will actually go around our whole container, but the cool thing here is and these functions we call on this modifier are applied sequentially so we can apply the same function here multiple times on the same modifier and it will lead to a different result, what that mean is we can make use of that border now which we set the width to 5dp, now we want to push the content of our container into the middle by set padding to 5dp,</p><pre><em>setContent </em><strong>{</strong></pre><pre><strong>    </strong><em>Column</em>(modifier = Modifier</pre><pre>        .<em>background</em>(Color.Green)</pre><pre>        .<em>fillMaxHeight</em>(0.5f)</pre><pre>        .<em>fillMaxWidth</em>()</pre><pre>        .<em>border</em>(5.<em>dp</em>,Color.Magenta)</pre><pre>        .<em>padding</em>(5.<em>dp</em>)</pre><pre>        .<em>border</em>(5.<em>dp</em>, Color.Blue)</pre><pre>        .<em>padding</em>(5.<em>dp</em>)</pre><pre>        .<em>border</em>(10.<em>dp</em>, Color.Red)</pre><pre>        .<em>padding</em>(10.<em>dp</em>)</pre><pre>    ) <strong>{</strong></pre><pre><strong>        </strong><em>Text</em>(&quot;Hello&quot;)</pre><pre>        <em>Spacer</em>(modifier=Modifier.<em>height</em>(50.<em>dp</em>))</pre><pre>        <em>Text</em>(&quot;World&quot;)</pre><pre>    <strong>}</strong></pre><pre><strong>}</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VOnc64StGjjK0_vrTdNDOw.png" /></figure><p>so then we can apply a border again, then apply padding again and border and padding, and finally adding padding 10dp to see our text here. Now three borders applied to our container and these padding were just applied sequentially. If you want to do this in xml you had so much work.</p><p>Next add border and padding and offset to text and then border and padding, now our text is here which is not readable but you get what this allows you to do actually so you can get so creative with that.</p><pre><em>setContent </em><strong>{<br> </strong><em>Column</em>(modifier = Modifier<br> .<em>background</em>(Color.Green)<br> .<em>fillMaxHeight</em>(0.5f)<br> .<em>fillMaxWidth</em>()<br> .<em>border</em>(5.<em>dp</em>,Color.Magenta)<br> .<em>padding</em>(5.<em>dp</em>)<br> .<em>border</em>(5.<em>dp</em>, Color.Blue)<br> .<em>padding</em>(5.<em>dp</em>)<br> .<em>border</em>(10.<em>dp</em>, Color.Red)<br> .<em>padding</em>(10.<em>dp</em>)<br> ) <strong>{<br> </strong><em>Text</em>(“Hello”, modifier=Modifier<br> .<em>border</em>(5.<em>dp</em>,Color.Yellow)<br> .<em>padding</em>(5.<em>dp</em>)<br> .<em>offset</em>(20.<em>dp </em>,20.<em>dp</em>)<br> .<em>border</em>(10.<em>dp</em>, Color.Black)<br> .<em>padding</em>(10.<em>dp</em>)<br> )<br> <em>Spacer</em>(modifier=Modifier.<em>height</em>(50.<em>dp</em>))<br> <em>Text</em>(“World”)<br> <strong>}<br> }</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HsiobyoVm92uvPRTBMYFmA.png" /></figure><p>One last thing I want to show you which is making our composables interactable , lets say we want to be able to click on this little text here so we can add, modifire clickable comes with a lamda funtion and we can just put in some code that should be called whenever we click on that text just a normal on click listner but this also comes with a click effect so if we launch our app, now we click on hello text you can see there is a little shadow.</p><pre><em>setContent </em><strong>{<br> </strong><em>Column</em>(modifier = Modifier<br> .<em>background</em>(Color.Green)<br> .<em>fillMaxHeight</em>(0.5f)<br> .<em>fillMaxWidth</em>()<br> .<em>border</em>(5.<em>dp</em>,Color.Magenta)<br> .<em>padding</em>(5.<em>dp</em>)<br> .<em>border</em>(5.<em>dp</em>, Color.Blue)<br> .<em>padding</em>(5.<em>dp</em>)<br> .<em>border</em>(10.<em>dp</em>, Color.Red)<br> .<em>padding</em>(10.<em>dp</em>)<br> ) <strong>{<br> </strong><em>Text</em>(“Hello”, modifier = Modifier<br> .<em>clickable </em><strong>{<br> }<br> </strong>)<br> <em>Spacer</em>(modifier=Modifier.<em>height</em>(50.<em>dp</em>))<br> <em>Text</em>(“World”)<br> <strong>}<br> }</strong></pre><p>Not only clickable we also have dragable, there are some more we can do with modifire. you can explore so much more when you just apply.</p><p><strong>Creating an Image Card Composable</strong></p><p>In here just take what ever image you like, and put it into this drawable folder, I will go below of mainActivity and I will create a composable function that we need to annotate with @composable, that will be a function and its going to be called ImageCard, the naming convention for composable functions is that these start with a capital letter, so normal functions start with a lower letter and are wriiten in CamelCase but these composable functions are starting with a capital letter thats important so now we need image that we want to display so we can have multiple cards and each card should have a different image and each card have a different title and the content description,</p><pre> @Composable<br> fun ImageCard(<br> )<br> {<br> }</pre><p>so starting with the image for that we need what is called a painter. In a jetpack compose, here we can give our image resources to display that in our image card, then we will have the contentdescription, title, and modifire and I will set this by default empty modifire.</p><pre> @Composable<br> fun ImageCard(<br> painter: Painter,<br> contentDescription:String,<br> title:String,<br> modifier: Modifier=Modifier<br> )<br> {<br> }</pre><p>After that we use card component here in jetpack compose, and add modifire here I use this modifire, and choose fillMaxwidth() and shape to the card give it rounded corners and corner radius to some kind of dp amount, then I need to add elevation , that will give little shadow like, 5.dp.</p><pre> @Composable<br> fun ImageCard(<br> painter: Painter,<br> contentDescription:String,<br> title:String,<br> modifier: Modifier=Modifier<br> )<br> {<br> <em>Card</em>(<br> modifier = modifier.<em>fillMaxWidth</em>(),<br> shape= <em>RoundedCornerShape</em>(15.<em>dp</em>),<br> elevation = 5.<em>dp<br> </em>)<strong>{<br> }<br> </strong>}</pre><p>Now need to show the content inside picture and alignment to the bottom left, here we want to use Box is just as a column and a row a normal container we can put composable into that and just apply a modifire, I want to set the size , capital m for modifire just use a new modifire and set the height to 200.dp, now what ever put into this block here will be stacked on top of each other, so what ever we put first here in our code will be at the bottom of our stack, so since our image should be at the bottom then we actually want to have the gradient which is above the image but below the text and then we want to have the text.</p><pre> @Composable<br> fun ImageCard(<br> painter: Painter,<br> contentDescription:String,<br> title:String,<br> modifier: Modifier=Modifier<br> )<br> {<br> <em>Card</em>(<br> modifier = modifier.<em>fillMaxWidth</em>(),<br> shape= <em>RoundedCornerShape</em>(15.<em>dp</em>),<br> elevation = 5.<em>dp<br> </em>)<strong>{<br> </strong><em>Box</em>(modifier = Modifier.<em>height</em>(200.<em>dp</em>))<strong>{<br> }<br> }<br> </strong>}</pre><p>so Image, we just have an Image component here and that has painter we actually passed as a prameter and also takes the content description. we want to set the content scale property to crop, next thing is our gradient so before that I put my text, so I use another Box and set fillMaxsize of its parent container and also want to give some padding (12.dp). We can use content alignment, and of that box we can put our text, we want to assign our title as a parameter, we can use style for style our text box , so set color white so in android we use sp for font size.</p><pre> @Composable<br> fun ImageCard(<br> painter: Painter,<br> contentDescription:String,<br> title:String,<br> modifier: Modifier=Modifier<br> )<br> {<br> Card(<br> modifier = modifier.fillMaxWidth(),<br> shape= RoundedCornerShape(15.dp),<br> elevation = 5.dp<br> )<strong>{<br> </strong>Box(modifier = Modifier.height(200.dp))<strong>{<br> </strong>Image(<br> painter = painter,<br> contentDescription = contentDescription,<br> contentScale = ContentScale.Crop<br> )<br> Box(modifier = Modifier<br> .fillMaxSize()<br> .padding(12.dp),<br> contentAlignment = Alignment.BottomStart<br> )<strong>{<br> </strong>Text(text = title, style = TextStyle(color = Color.White, fontSize = 16.sp ) )<br> <strong>}<br> }<br> }<br> </strong>}</pre><p>In setContent we want to pecify our painter so that is used to get the image from our resources, we can use painterResource here so thats pass our drawable resource id , then we can set description of our image and title, then we need create our imageCard composable, we can reuse this composable again and again, when we run it you can see right now its streches the whole width of our screen and cannot read our text because its white on white so thats the reason why I want to apply the gradient from black to transparent,</p><pre>setContent <strong>{<br> </strong>val painter = painterResource(id =    R.drawable.ic_launcher_background)<br> var contentDescription = “Hello”<br> var title = “Hello”<br> ImageCard(painter = painter, contentDescription = contentDescription, title = title)<br> <strong>}</strong></pre><p>then need to put it this half of the screen. we can easily accomplish that by putting it into a box, and applying a modifier to that box fillmaxwidth 50 percent of our width, then we put our code int that box, and give little bit padding.</p><pre>Box(modifier= Modifier<br> .fillMaxWidth(0.5f)<br> .padding(12.dp)<br> )<strong>{<br> </strong>ImageCard(painter = painter, contentDescription = contentDescription, title = title)<br> <strong>}</strong></pre><p>We can finally get to our gradient it should be put between our image and text then that will also be a box and and give modifiere a fillMaxsize and can apply background property, now I not going to use color, I use brush, and with these brushes we can define a gradient. Gradiant work top to bottom so I can start with tranparent to Black</p><pre>Box(modifier = Modifier<br> .fillMaxSize()<br> .background(Brush.verticalGradient( colors =<br> listOf(<br> Color.Transparent,<br> Color.Black,<br> ),<br> startY = 300f<br> ))<br> )</pre><p><strong>State</strong></p><p>State basically describes how our given ui looks at a moment, because so far we have only deal with static content here, but real app we actually have dynamic contents. In jetpack compose when we have a composable function and this composable function make use of some kind of state so let’s say you have a simple increment counter you have a button and when you click on that button just the counter is increased and button displays that corresponding counter, so this counter variable would be the state of the button , because every time we press the button the text on that button needs to change which will lead to jetpack compose re-rendering that button bcz it needs to be redrawn in our ui and this process of redrawing ui componets is called recomposing in jetpack compose , what I m going to explain here, I use color box so just a box that if we press on that it will change its background color to any random color and that color that background color of that box will be the state that we use here.</p><pre>@Composable<br> fun ColorBox(modifier: Modifier = Modifier){<br> Box(modifier = Modifier<br> .background(Color.Yellow)<br> .clickable <strong>{<br> }<br> </strong>)<br> }</pre><p>First create our composable function, called ColorBox and just pass a modifire, inside here we just have a simple Box, and set background like yellow , and make this clickable. In here it actually changes the background color of our box to a random color so we can do that using state.</p><pre> @Composable<br> fun ColorBox(modifier: Modifier = Modifier){<br> val color = mutableStateOf(Color.Yellow);<br> Box(modifier = Modifier<br> .background(color.value)<br> .clickable <strong>{<br> </strong>color.value = Color(<br> Random.nextFloat(),<br> Random.nextFloat(),<br> Random.nextFloat(),<br> 1f<br> )<br> <strong>}<br> </strong>)<br> }</pre><p>We declare our state on top of our composable, we could create that state by using mutablestateof and then set that to color yellow default for example and then we could take that color and put it here instead of this color yellow into the background property by using color.value. In the clickable we re assign that state color any random color. So we can just use random.nextfloat three times here and for the alpha value we can pass the 1f which is actually the default, so whenever we set this state here this line , what this will do is it will tell compose the state changed so ur composable should actually look differently than before so what compose will do behind the scenes is it will recompose this color box so it wil redraw it on our ui so that it can actually show that state change so it can actually show that color change and display that box with a different color now,</p><pre> @Composable<br> fun ColorBox(modifier: Modifier = Modifier){<br> val color = remember<strong>{<br> </strong>mutableStateOf(Color.Yellow);<br> <strong>}<br> </strong>Box(modifier = modifier<br> .background(color.value)<br> .clickable <strong>{<br> </strong>color.value = Color(<br> Random.nextFloat(),<br> Random.nextFloat(),<br> Random.nextFloat(),<br> 1f<br> )<br> <strong>}<br> </strong>)<br> }</pre><p>the problem here now is that when this composable is recomposed then this function is called again and well if this function is recalled basically then we also reset this state to color yellow here in the first line and that is not optimal of course so that would mean it wouldn’t really work here because we always reset the color state here to yellow in the first line to fix this what we need to do is we need to use what is called remember that is a lambda function that comes from compose, it will just remember the value of this state from the last composition so it wont reset that value on every recomposition and you will stumble over this remember keyword here quite a lot in compose so it just means okay when this box is recomposed we actually dont want to reset this value thats all it does and by the way we should use this modifier (in box) instead of the deafault one otherwise that is pretty pointless.</p><pre>setContent <strong>{<br> </strong>ColorBox(<br> Modifier.fillMaxSize()<br> )<br> <strong>}</strong></pre><p>So now I will set content to actually use our color box and for the modifire I will use modifire dot fill max size to just fill our whole page and now run the app,</p><p>you can see all screen its yellow by default and when I click on it changes to a random color. So that is how we can actually change our ui by using state so this was pretty easy so far because this state only effected this color box here so when we clicked on this color box then we also wanted to change the bckground color of this color box but what actually happens if we want to click on this color box and we want to change the background color of a another box so inside of this composable we actually dont have access to this other box,</p><pre>setContent <strong>{<br> </strong>Column(Modifier.fillMaxSize()) <strong>{<br> </strong>ColorBox(<br> Modifier<br> .fillMaxSize()<br> .weight(1f)<br> )<br> Box(modifier = Modifier<br> .background(color.value)<br> .weight(1f)<br> )<br> <strong>}<br> }<br> </strong>////<br> ColorBox(<br> Modifier<br> .weight(1f)<br> .fillMaxSize()<br> )<br> Box(modifier = Modifier<br> .background(color.value)<br> .weight(1f)<br> .fillMaxSize()<br> )</pre><p>so lets say we have another box and lets wrap these two boxes into a column and that should just fill the max size here and we specify another box where we set the modifire to a modifire.dot background and now here I want to have that color value that we actually specified down here in that color box but we dont have acces to that so we cannot write color.value, it doesnt know color but before we fix that lets actually also assign a weight to this box of 1f and weight for other box, weight is a actually a property we can only apply in rows and coloumns so what this will do here is it will in our case weight our both boxes here with the same weight so both will actually get the same space in our coloumn so both will fill the same space and move this fill max size after that weight and then lets fix this issue.</p><pre>class MainActivity : ComponentActivity() {<br> override fun onCreate(savedInstanceState: Bundle?) {<br> super.onCreate(savedInstanceState)<br> <em>setContent </em><strong>{<br> </strong>val color = <em>remember</em><strong>{<br> </strong><em>mutableStateOf</em>(Color.Yellow);<br> <strong>}<br> </strong><em>Column</em>(Modifier.<em>fillMaxSize</em>()) <strong>{<br> </strong><em>ColorBox</em>(<br> Modifier<br> .<em>weight</em>(1f)<br> .<em>fillMaxSize</em>()<br> )<strong>{<br> </strong>color.value = <strong>it<br> }<br> </strong><em>Box</em>(modifier = Modifier<br> .<em>background</em>(color.value)<br> .<em>weight</em>(1f)<br> .<em>fillMaxSize</em>()<br> )<br> <strong>}<br> }<br> </strong>}<br> }<br> @Composable<br> fun ColorBox(modifier: Modifier = Modifier,<br> updateColor: (Color)-&gt;Unit<br> )<br> {<br> <em>Box</em>(modifier = modifier<br> .<em>background</em>(Color.Red)<br> .<em>clickable </em><strong>{<br> </strong>updateColor(//2<br> <em>Color</em>(<br> Random.nextFloat(),<br> Random.nextFloat(),<br> Random.nextFloat(),<br> 1f )<br> )<br> <strong>}<br> </strong>)<br> }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IibeHvYm6nMwJ7-v3SfSzw.png" /></figure><p>First of all we want to define our state not in color box instead here in our column so here we have a val color and set it to color yellow by default in mutable state, now we can remove that state bcz now when we click on that color box we want to change the background color not of this box instead of this box, we will define callback function to actually change the state of our parent composable so we can call that for example updatColor and that will take our color value that we actually updated here when we clicked on this box and it wont return anything so a unit and then here for the background color just choose red , because this time we dont change this background color, when we click on this box we now want to call our lambda function with our new color value that we randomly generated here so we actually just use updateColor, and in here we pass thats color value, now here we need to set parameters to our lambda function, that lambda block now called when our color state changes when we clicked on our color box , it gives us the new color and can use color state we defined up here and set its value to the new color, now relaunch the app.</p><p>But you can imagine for bigger apps doing it like this can become quite messy because you will have a lot of these satate values , that will have other solutions we can just handle state in our view model which we will do later. So i hope you understand this concept of state here.</p><p><strong>Styling Text</strong></p><p><a href="https://fonts.google.com/">Browse Fonts - Google Fonts</a></p><pre><em>setContent </em><strong>{<br> </strong><em>Box</em>(modifier = Modifier<br> .<em>fillMaxSize</em>()<br> .<em>background</em>(<em>Color</em>(0xFF101010)))<br> <strong>{<br> </strong><em>Text</em>(text = “Jetpack Compose”,<br> color = Color.White,<br> fontSize = 30.<em>sp</em>)<br> <strong>}<br> }</strong></pre><p>In here I will show you how you can actually style your text in compose. So to start I just want to wrap my text here into box because iI want to give my app a background color , so we set the modifire of that box to fill maxsize and background to 0xff101010 hex color ,its dark gray , then inside our box we will have our actuall text, so now lets see how we can actually style the text and make it look really cool, now default text color is black so in gray background we want to change the text color so simply we use the color to white , then font size for example fontsize 30sp, then we want to use our own downloaded font instead of default font , for download that I went to google fonts and I choose this lexend fonts, once I download, and our names of font all needs be lower case and dashes need to be replaced to underscore because that is the naming convention for resource files, and goto res folder right click and choose android resource directory type will be font and in that paste it.</p><pre>val fontFamily = FontFamily(<br> Font(R.font.lexend_bold , FontWeight.Bold)<br> )</pre><p>Now we need to create our kotlin code to just define what font we have and weight levells. for example light bold regular and so on , for that i go inside of oncreate here for our needs I will create a val font family and set that new font family and I can put in a list of fonts here , using Font and resource id and font weight.</p><pre><em>Text</em>(<br> text = “Jetpack Compose”,<br> color = Color.White,<br> fontSize = 30.<em>sp</em>,<br> fontFamily = fontFamily,<br> fontWeight = FontWeight.Bold,<br> fontStyle = FontStyle.Italic,<br> textAlign = TextAlign.Center,<br> textDecoration = TextDecoration.Underline<br> )</pre><p>After added all of this font , lets go back and assign a font family we declared above. and we can set font weight.bold for example , then we can use font style make it italic , then we could change the textAlign center , and textDecoration for underline I think this not possible on xml.</p><p>The actual improvement here for text styling in compose are so called annotated strings , so we cannot only pass string here for text parameter instead we can also pass a annotated string and with that we can basically apply different styles to different parts of our our string of our text and that was possible before in android of course but it wasnt really convenient, now we have a really cool builder for those annotated strings and you will see how easy that is so instead of setting that to jetpack compose we will set it to.</p><pre>Text(<br> text = buildAnnotatedString <strong>{<br> </strong>append()<br> <strong>}</strong>,<br> color = Color.White,<br> fontSize = 30.<em>sp</em>,</pre><p>Build annotated string and that is a function that gives us a scope of annotated string builder so you might already know string builders this works very similler, just call append here a caracter or just a string so we can basically construct our very own string here and we can apply different styles to different sections of our string.</p><pre>Text(<br> text = buildAnnotatedString <strong>{<br> </strong><em>withStyle</em>(<br> style = SpanStyle(<br> color = Color.Green,<br> fontSize = 50.<em>sp<br> </em>)<br> ) <strong>{<br> </strong>append(“J”)<br> <strong>}<br> </strong>append(“etpack”)<br> withStyle(<br> style = SpanStyle(<br> color = Color.Green,<br> fontSize = 50.<em>sp<br> </em>)<br> ) <strong>{<br> </strong>append(“C”)<br> <strong>}<br> </strong>append(“ompose”)<br> <strong>}</strong>,</pre><p>So instead of using append use withstyle that allows us to give individual style, so we can set style equal newspan style and in the span style we can now define a normal text style how this part of that string will look like so we can set the color to color.green for example we could increase the font size to 50 sp you could chnage the font weight ,family what ever, Ill leave it for a little bit like that right now , then after the style parentheses we open curly brackets and in this now use append to append the section of our string we actually want to apply this style here for the first letter for a “J” then after this style block we can append our remaining letters so that these together make up a jetpack , “J” actually has this style then other part has this style the default style, then use same with style block below that and replace this “C” now and after that we append remaining letters. Now lets see in phone, so thats everything i wanted to show you about text styles</p><p><strong>Conclusion</strong></p><p>With a brand-new declarative UI toolkit, Android development is all set to get a lot more fun. Although Compose is still in its infancy, its already showing a lot of promise and the community is very excited about it. There are enough signals to point to the fact that Compose is going to be the de-facto way of building Android apps. It also lowers the barrier to entry for a lot of non-engineers with its intuitive APIs that are easy to understand.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fb4cab297c28" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vuex Store]]></title>
            <link>https://medium.com/@edirisinghe.cha/vuex-store-dedf0dc54408?source=rss-e75762970f01------2</link>
            <guid isPermaLink="false">https://medium.com/p/dedf0dc54408</guid>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[vuex]]></category>
            <dc:creator><![CDATA[Chathuranga Edirisinghe]]></dc:creator>
            <pubDate>Fri, 06 Aug 2021 06:09:08 GMT</pubDate>
            <atom:updated>2021-09-30T04:13:14.194Z</atom:updated>
            <content:encoded><![CDATA[<p>Vuex is a simple state management library for Vue js. It is the fundamental object in Vuex. A store wraps your app’s state in a convenient object and gives you access to powerful features and patterns, like mutations and getters.</p><p><strong>What is the state management?</strong></p><p>State management in an application with many components can be a real pain. The more components you have, the more you’ll need to pass the data up the component tree with the use of events (until you reach a parent component), and then down to the component that needs the data with the use of props.</p><p>With fewer components, this relatively is simple:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/344/1*Zc3AZXi0-SKICxYlUVRlew.png" /></figure><p>With more, however, things become complicated, like in this example component structure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/1*JBDMBLmGefp45DZh9UPMfg.png" /></figure><p>If component A has the data needed by component D, then you will need to move the data through B and C, if component D has data needed by component C, you will need to move the data through C, B, and A by emitting events, and then to C through props. As you can imagine, this can become a huge mess as the number of components and nesting grows.</p><p>With Vuex, you can access application-level data and functions from all the components, easily and predictably. Look at the diagram below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/478/1*_suntHmzQracCHPnarsASA.png" /></figure><p>Before we continue, here are a few important Vuex terminologies to keep in mind:</p><p><a href="https://vuex.vuejs.org/guide/state.html#single-state-tree"><strong>Store </strong></a>— In Vuex, a Store is a global state that is available throughout our app. Store contains the application’s state, mutations, and actions. Stores are reactive, if a component is using the store’s state and there is a change in the state, the component will be re rendered optimally to reflect the change</p><p><a href="https://vuex.vuejs.org/guide/state.html#single-state-tree"><strong>State </strong></a>— A state is a simple object that contains an application-level state. Vue provides an in-component state through the data hook, but if you want the data to be accessible by any component, it is recommended that you store it in the state.</p><p><a href="https://vuex.vuejs.org/guide/getters.html"><strong>Getters</strong></a> — These enable computation to be done with data from the store’s state. Alternatively, you can retrieve the state from the store, and perform the computation as needed by a component, but this can become tedious and repetitive if you have several components that need the same computation. With a getter handling the computation, you can just retrieve the computed value</p><p><a href="https://vuex.vuejs.org/guide/mutations.html#commit-with-payload"><strong>Mutations</strong></a> — The store’s state is immutable and can only be mutated through mutations. Mutations are linked with actions. Imagine Vuex’s mutation as just a block of code. This code will not run unless it is executed.</p><p><a href="https://vuex.vuejs.org/guide/actions.html"><strong>Action</strong></a> — An action performs mutations. An action is a command that executes the “block of code” I mentioned in the definition of mutations above. Without this command, the block of code will not be executed.</p><p><strong>Flow of data in vuex</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6oVaS9DdS5hwd6ybOnj6Kg.png" /></figure><p><strong>Install Vuex</strong></p><pre>npm install vuex — save</pre><h3>Initialize Vuex</h3><pre>import Vue from &#39;vue&#39;</pre><pre>import Vuex from &#39;vuex&#39;Vue.use(Vuex)</pre><h3>Store</h3><p>Create a store:</p><pre>export default new Vuex.Store({</pre><pre> state: {</pre><pre>  // Current state of the application lies here.</pre><pre> },</pre><pre> getters: {</pre><pre>  // Compute derived state based on the current state. More like computed property.</pre><pre> },</pre><pre> mutations: {</pre><pre>  // Mutate the current state</pre><pre> },</pre><pre> actions: {</pre><pre>  // Get data from server and send that to mutations to mutate the current state</pre><pre> }</pre><pre>})// You can assign a store to variable and export. </pre><pre> export const store = new Vuex.Store({})</pre><pre>// Import the store</pre><pre>import {store } from &#39;/path/to/file&#39;</pre><h3>State</h3><p>First thing in the store is state.</p><pre>state: {</pre><pre>  name:&#39;Jame Smith&#39;,</pre><pre>  email:’james@gmail.com’</pre><pre> }</pre><h3>Access State</h3><p>Accessing a state is simpler than every other library.</p><p>You can read the state directly like</p><pre>store.state.name // Jame Smith</pre><p>If you don’t want to change the name of the property, then go with this:</p><p>computed: {<br> …mapState([‘name’, ‘email’])<br> // Now you can read the name by using this.name<br> }</p><p>But if you want to change the name then you must use an object like notation</p><p>computed: {<br> …mapState({<br> userName : state =&gt; state.name,<br> userEmail: state =&gt; state.email<br> })<br> // Now you can read the name by using this.userName<br> }</p><p>Finally, the component looks like this:</p><pre>&lt;template&gt;</pre><pre> &lt;div&gt;</pre><pre>     Name: {{name }}</pre><pre>     Email: {{email }}</pre><pre> &lt;/div&gt;</pre><pre>&lt;/template&gt;&lt;script&gt;<strong>import { mapState } from &#39;vuex&#39;</strong>export default {</pre><pre>  name:&#39;Profile&#39;,</pre><pre><strong>  computed: {</strong></pre><pre><strong>   ...mapState([&#39;name&#39;, &#39;email&#39;])</strong></pre><pre><strong>   </strong>// Now you can read the name by using this.name</pre><pre>  <strong>}</strong></pre><pre> }</pre><pre>&lt;/script&gt;</pre><h3>Mutation</h3><p>Mutation is the only object which has a proper right to mutate the state.</p><p>Mutation looks like this.</p><pre>updateName(state, name) {</pre><pre>   state.name = name</pre><pre>  }</pre><p>A mutation may have two arguments as state and payload.</p><p><strong>State </strong>has the current state of an application.</p><p><strong>Payload</strong> is an optional one, which will give the data to mutate.</p><p>So, after adding mutation, the store look like this.</p><pre>import Vue from &#39;vue&#39;</pre><pre>import Vuex from &#39;vuex&#39;Vue.use(Vuex)export default new Vuex.Store({</pre><pre> state: {</pre><pre>  name:’Jame Smith’,</pre><pre>email:’james@gmail.com’</pre><pre> },</pre><pre><strong> mutations: {</strong></pre><pre><strong>  updateName(state, name) {</strong></pre><pre><strong>   state.name = name</strong></pre><pre><strong>  }</strong></pre><pre> }</pre><pre>})</pre><h3>Invoke Mutation</h3><p>If we have the reference to store object, then we can call the mutation directly like these.</p><pre>store.commit(&#39;updateName&#39;,&#39;James&#39;)</pre><p>Object-Style Commit</p><pre>store.commit({</pre><pre>  type: &#39;updateName&#39;,</pre><pre>  name: &#39;James&#39;</pre><pre>})</pre><p>We will use the store.commit() notation in a router and inside the store but in components, we have another way to invoke mutation.</p><p>Inside a component, we will Import a helper function ‘mapMutations’ from Vuex and spread that into methods to invoke a mutation.</p><pre>methods: {</pre><pre>   ...mapMutations([&#39;updateName&#39;])</pre><pre>  }</pre><pre>// Now this.updateName(James&#39;) will call the mutation in the store and update the state.</pre><p>If you want to change the name, then</p><pre>methods: {</pre><pre>   ...mapMutations({</pre><pre>    editName: &#39;updateName&#39;</pre><pre>   })</pre><pre>  }</pre><pre>// Now this.editName(&#39;James&#39;) will call the mutation in the store and update the state.</pre><p>Now the component looks like this.</p><pre>&lt;template&gt;</pre><pre> &lt;div&gt;</pre><pre>     Name: {{name }}</pre><pre>     Email: {{email }}</pre><pre> &lt;/div&gt;</pre><pre>&lt;/template&gt;&lt;script&gt;import { mapState, mapMutations } from &#39;vuex&#39;export default {</pre><pre>  name:&#39;Profile&#39;,</pre><pre>  computed: {</pre><pre>   ...mapState([&#39;name&#39;,&#39;email&#39;])</pre><pre>  },</pre><pre> <strong> methods: {</strong></pre><pre>  <strong> ...mapMutations([&#39;updateName&#39;])</strong></pre><pre><strong>  }</strong></pre><pre>}&lt;/script&gt;</pre><p>But “Mutations Must Be Synchronous” So if you require data from sever then you must create actions.</p><h3>Actions</h3><p>Actions can contain arbitrary asynchronous operations; action commits mutation after doing the asynchronous operation.</p><p>The payload is the optional one, which will carry optional data to do actions.</p><pre>getUserData(context,payload){</pre><pre>      // Get the data from server</pre><pre>            axios.get(&#39;www.api.yourdomain&#39;).then((response)=&gt;{</pre><pre>      // commit to the store to mutate the state</pre><pre>            context.commit(&#39;loadUserData&#39;,response)</pre><pre>      })</pre><pre>    }</pre><p>After adding actions to store</p><pre>import Vue from &#39;vue&#39;</pre><pre>import Vuex from &#39;vuex&#39;Vue.use(Vuex)export default new Vuex.Store({</pre><pre> state: {</pre><pre>  name:&#39;James Smith&#39;,</pre><pre>  email:’james@gmail.com’</pre><pre> },</pre><pre> mutations: {</pre><pre>  updateName(state, name) =&gt; {</pre><pre>   state.name = name</pre><pre>  },</pre><pre>  loadUserData(state,payload){</pre><pre>      state.name = payload.name.</pre><pre>      state.email = payload.email</pre><pre>  }</pre><pre>  },</pre><pre> <strong> actions: {</strong></pre><pre><strong>    getUserData(context,payload){</strong></pre><pre><strong>      // Get the data from server</strong></pre><pre><strong>      axios.get(&#39;www.api.yourdomain&#39;).then((response)=&gt;{</strong></pre><pre><strong>      // commit to the store</strong></pre><pre><strong>        context.commit(&#39;loadUserData&#39;,response)</strong></pre><pre><strong>      })</strong></pre><pre><strong>    }</strong></pre><pre>})</pre><p><strong>Access actions</strong></p><p>If you have reference to store, then dispatch an action using,</p><pre>store.dispatch(&#39;nameOfAction&#39;);</pre><p>Inside the store and router, we use this method. In components we may use mapActions helper functions</p><pre>&lt;template&gt;</pre><pre> &lt;div&gt;</pre><pre>     Name: {{ name }}</pre><pre>     Email: {{ email }}</pre><pre> &lt;/div&gt;</pre><pre>&lt;/template&gt;</pre><pre>&lt;script&gt;</pre><pre>import { mapState, mapMutations, mapActions } from &#39;vuex&#39;</pre><pre>export default {</pre><pre>  name:&#39;Profile&#39;,</pre><pre>  computed:{</pre><pre>   ...mapState([&#39;name&#39;,&#39;email&#39;])</pre><pre>  },</pre><pre>  methods:{</pre><pre>   ...mapMutations([&#39;updateName&#39;]),</pre><pre>  <strong> ...mapActions([&#39;getUserData&#39;])</strong></pre><pre>  }</pre><pre>}</pre><pre>&lt;/script&gt;</pre><p>Now we can use this.getUserData() to dispatch an action.</p><p><strong>Getters</strong></p><p>We need some computed functions in all components, so we define all those functions inside these getters. Every function inside getters computes derived state based on store state.</p><p>It has two arguments state and getters.</p><p>The <strong>state </strong>has current state values.</p><p><strong>Getters </strong>are optional, all other getters can be used inside one getter function.</p><pre>getters:{<br> isAdult(state,getters){<br> return state.age &gt;=18 ? true : false<br> }<br>}</pre><p><strong>Call getters</strong></p><pre>store.getters.isAdult;</pre><p>Inside components use mapGetters helper function and spread that into the computed property.</p><pre>&lt;template&gt;<br> &lt;div&gt;<br> Name: {{ name }}<br> Age: {{ age }}<br> Email: {{ email }}<br> &lt;/div&gt;<br> &lt;/template&gt;<br> &lt;script&gt;<br> import { mapState, mapMutations, mapActions, mapGetters } from ‘vuex’<br> export default {<br> name:’Profile’,<br> computed:{<br> …mapState([‘name’,’age’,email])<br> <strong>…mapGetters([‘isAdult’])</strong><br> },<br> methods:{<br>   …mapMutations([‘updateName’]),<br>   …mapActions([‘getUserData’])<br> }<br> }<br> &lt;/script&gt;</pre><p>Now you can access the getter by this.isAdult</p><p>PS: mapMutations, mapActions must be inside methods, and mapState, mapGetters must be inside a computed property.</p><p><strong>Computed</strong></p><p>And if you must change the computed property then you can use a set function for computed property</p><pre>computed: {<br> name: {<br> // getter<br> get: () =&gt; {<br>      return this.$store.name <br> },<br> // setter<br> set: (newValue) =&gt; {<br>       this.$store.dispatch(‘updateName’,newValue)<br>    }<br> }<br> }</pre><p>When you try to mutate the computed property then you will get an error saying no setter function is available for that computed property. So, if you want to mutate the computed property then write a set function.</p><p><strong>Conclusion</strong></p><p>Vuex is a simple approach to state management. We can store shared state in Vue apps with Vuex. That contains everything that you need for your application’s state including: <strong>state</strong>, <strong>actions</strong>, <strong>mutations</strong>, <strong>getters</strong>, and <strong>setters</strong>. Your state is a sole source of truth or a single data source that is shared across all components and views of your single page application. Getters to get data from states, mutations to change data, and actions to run one or more mutations or other actions and them asynchronously.</p><p>We can map states into computed properties with <strong>mapGetters </strong>and map mutations and actions with <strong>mapMutations </strong>and <strong>mapActions </strong>methods respectively and divide our store into modules to segregate them into smaller pieces.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dedf0dc54408" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>