<?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 sahar vanunu on Medium]]></title>
        <description><![CDATA[Stories by sahar vanunu on Medium]]></description>
        <link>https://medium.com/@sir.x5x?source=rss-2489d2e7b36------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*GvxjbNGyksqOnzOqxX4VyA.png</url>
            <title>Stories by sahar vanunu on Medium</title>
            <link>https://medium.com/@sir.x5x?source=rss-2489d2e7b36------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 15:51:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sir.x5x/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[PDF Viewer using Coil]]></title>
            <link>https://proandroiddev.com/pdfviewer-using-coil-240338f9b5ac?source=rss-2489d2e7b36------2</link>
            <guid isPermaLink="false">https://medium.com/p/240338f9b5ac</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[pdf]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[sahar vanunu]]></dc:creator>
            <pubDate>Thu, 11 Jul 2024 10:10:18 GMT</pubDate>
            <atom:updated>2024-07-18T08:37:44.982Z</atom:updated>
            <content:encoded><![CDATA[<p>When I set out to integrate a PDF viewer into my Android app, I was surprised to find a lack of clear solutions on Google. After much research and experimentation, I developed a method using Coil, a popular image loading library for Android. In this article, I’ll walk you through the steps to set up a PDF viewer using Coil.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WR5gPh-735ZbQJs3evweDA.png" /></figure><h4>Step 1: Create a PDF Decoder for Coil</h4><p>First, we need a custom decoder to handle PDF files in Coil. Here’s the code snippet for the PdfPageDecoder:</p><pre>class PdfPageDecoder(<br>    private val context: Context,<br>    private val data: PdfPage<br>) : Decoder {<br><br>    companion object {<br>        const val NUMBER_PDF_PAGES = &quot;numberPages&quot;<br>        const val SPACE_BETWEEN_PAGES = &quot;spaceBetweenPages&quot;<br>    }<br><br><br>    override suspend fun decode(): DecodeResult {<br>        val bitmap = withContext(Dispatchers.IO) {<br>            renderPagesToBitmap(<br>                data.file,<br>                context.resources.displayMetrics.density,<br>                data.numberPages,<br>                data.spaceBetweenPages<br>            )<br>        }<br>        val drawable = BitmapDrawable(context.resources, bitmap)<br>        return DecodeResult(drawable = drawable, isSampled = false)<br>    }<br><br>    class Factory : Decoder.Factory {<br>        override fun create(<br>            result: SourceResult,<br>            options: Options,<br>            imageLoader: ImageLoader<br>        ): Decoder? {<br>            return if (isApplicable(result)) {<br>                val numberPages = (options.parameters.values()[NUMBER_PDF_PAGES] as? Int) ?: Int.MAX_VALUE<br>                val spaceBetweenPages =<br>                    (options.parameters.values()[SPACE_BETWEEN_PAGES] as? Int) ?: 0<br>                PdfPageDecoder(<br>                    context = options.context,<br>                    data = PdfPage(<br>                        file = result.source.file().toFile(),<br>                        numberPages = numberPages,<br>                        spaceBetweenPages = spaceBetweenPages<br>                    )<br>                )<br>            } else {<br>                null<br>            }<br>        }<br><br>        private fun isApplicable(result: SourceResult): Boolean {<br>            return result.mimeType?.contains(&quot;pdf&quot;) == true<br>        }<br>    }<br><br>    private fun renderPagesToBitmap(<br>        file: File,<br>        density: Float,<br>        pagesNumber: Int,<br>        spaceBetweenPages: Int<br>    ): Bitmap {<br>        val fileDescriptor = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY)<br>        val pdfRenderer = PdfRenderer(fileDescriptor)<br><br>        val spaceBetweenPagesPx = (spaceBetweenPages * density).toInt()<br>        val pagesSize = pagesNumber.coerceIn(1, pdfRenderer.pageCount)<br>        val (maxWidth, totalHeight) = calculateTotalHeightAndWidth(<br>            pdfRenderer,<br>            density,<br>            pagesSize,<br>            spaceBetweenPagesPx<br>        )<br><br>        // Create a bitmap with the total height and max width<br>        val combinedBitmap = Bitmap.createBitmap(maxWidth, totalHeight, Bitmap.Config.ARGB_8888)<br>        val canvas = Canvas(combinedBitmap)<br><br>        var currentY = 0<br>        for (i in 0 until pdfRenderer.pageCount) {<br>            pdfRenderer.openPage(i).use { page -&gt;<br>                val pageBitmap = createPageBitmap(page, density)<br>                page.render(pageBitmap, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY)<br><br>                // Draw the page bitmap on the combined bitmap<br>                canvas.drawBitmap(pageBitmap, 0f, currentY.toFloat(), null)<br>                currentY += pageBitmap.height + spaceBetweenPagesPx<br><br>                pageBitmap.recycle() // Recycle the page bitmap to free memory<br>            }<br>        }<br><br>        pdfRenderer.close()<br>        fileDescriptor.close()<br><br>        return combinedBitmap<br>    }<br><br>    private fun calculateTotalHeightAndWidth(<br>        pdfRenderer: PdfRenderer,<br>        density: Float,<br>        pagesSize: Int,<br>        spaceBetweenPagesPx: Int<br>    ): Pair&lt;Int, Int&gt; {<br>        var totalHeight = 0<br>        var maxWidth = 0<br>        for (i in 0 until pagesSize) {<br>            pdfRenderer.openPage(i).use { page -&gt;<br>                totalHeight += (page.height * density).toInt() + spaceBetweenPagesPx<br>                maxWidth = maxOf(maxWidth, (page.width * density).toInt())<br>            }<br>        }<br>        totalHeight -= spaceBetweenPagesPx<br>        return Pair(maxWidth, totalHeight)<br>    }<br><br>    private fun createPageBitmap(page: PdfRenderer.Page, density: Float): Bitmap {<br>        val pageWidth = (page.width * density).toInt()<br>        val pageHeight = (page.height * density).toInt()<br>        return Bitmap.createBitmap(pageWidth, pageHeight, Bitmap.Config.ARGB_8888)<br><br>    }<br>    <br>    data class PdfPage(val file: File, val numberPages: Int, val spaceBetweenPages: Int)<br>}</pre><h4>Step 2: Add the Decoder in the Application Class</h4><p>Next, we need to add this decoder to the Coil configuration in our application class. This will ensure that Coil uses our custom decoder for PDF files.</p><pre>class MyApplication : Application(), ImageLoaderFactory {<br> override fun newImageLoader(): ImageLoader {<br> return ImageLoader.Builder(this)<br>        .componentRegistry { add(PdfPageDecoder.Factory()) }<br>        .build() <br>  } <br>}</pre><h4>Step 3: Using the PDF Decoder in your activity or using compose</h4><p>Finally, we can use Coil to load and display PDF pages in our activity or fragment.</p><p>Short explanation of how the PdfPageDecoder works:</p><ul><li><strong>Loading the PDF</strong>: When Coil encounters a PDF file, it uses the PdfPageDecoder to process it. This decoder reads the PDF file and prepares it for rendering.</li><li><strong>Rendering the PDF</strong>: The PdfPageDecoder opens the PDF using Android&#39;s PdfRenderer class. It then opens the first page of the PDF.</li><li><strong>Creating a Bitmap</strong>: A Bitmap object is created with the dimensions of the PDF page. The PDF page is rendered onto this Bitmap.</li><li><strong>Returning the Result</strong>: The Bitmap is then wrapped in a DecodeResult object, which Coil uses to display the image.</li></ul><pre>class MainActivity : AppCompatActivity() {<br><br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        setContentView(R.layout.activity_main)<br>        <br>        val pdfFileUri = &quot;file:///android_asset/sample.pdf&quot;<br>        val imageRequest = ImageRequest.Builder(LocalContext.current)<br>                                .setParameter(NUMBER_PDF_PAGES, 1)<br>                                .setParameter(SPACE_BETWEEN_PAGES, 20)<br>                                .data(pdfFileUri)<br>                                .build()<br>        imageView.load(imageRequest)<br>    }<br>}</pre><p><strong>Compose example</strong></p><pre>@Composable<br>fun PdfViewer(pdfFileUri: String) {<br>    val imageRequest = ImageRequest.Builder(LocalContext.current)<br>                                .setParameter(NUMBER_PDF_PAGES, 1)<br>                                .setParameter(SPACE_BETWEEN_PAGES, 20)<br>                                .data(pdfFileUri)<br>                                .build()<br>    AsyncImage(<br>        model = imageRequest,<br>        contentDescription = null,<br>    )<br>}</pre><p>With these steps, you should be able to integrate a PDF viewer into your Android app using Coil, both in traditional views and with Jetpack Compose. This approach leverages Coil’s extensibility to handle non-standard image formats, providing a seamless way to display PDF pages.</p><p>Feel free to adapt the code snippets to suit your needs. I hope this solution saves you time and effort, allowing you to focus on building great apps. If you have any questions or run into issues, please leave a comment below!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=240338f9b5ac" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/pdfviewer-using-coil-240338f9b5ac">PDF Viewer using Coil</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[“Stop” using state management libraries]]></title>
            <link>https://medium.com/flutter-community/stop-using-state-management-libraries-48a81ed7979d?source=rss-2489d2e7b36------2</link>
            <guid isPermaLink="false">https://medium.com/p/48a81ed7979d</guid>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[plugins]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <dc:creator><![CDATA[sahar vanunu]]></dc:creator>
            <pubDate>Tue, 26 Apr 2022 08:56:48 GMT</pubDate>
            <atom:updated>2022-05-19T18:54:46.614Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pNFE4yEDG1dOUbkR0qhbow.png" /></figure><p>Since the release of flutter in 2017, I have seen many changes in the platform, mainly in state management libraries such as provider, bloc, Getx, Mobx, and more.</p><p>Most beginners start using libraries without yet knowing what is going on behind the scenes. As a result, when asked a question during an interview regarding the behind-the-scenes aspects, maybe 5% of interviewees were actually able to answer.</p><p>In this article, I will explain the most important underlying components for most libraries, including:</p><ul><li>FutureBuilder</li><li>StreamBuilder</li><li>ChangeNotifier</li><li>Set State (yes, I know that most users are familiar with this, but I will explain its relevance below)</li></ul><p><strong>ChangeNotifier:</strong></p><p>These component is used often in “Provider”, but wait, how do it truly work without the use of additional libraries?!</p><p>First example how to implement it</p><p><strong>HomeController</strong></p><p>controller that increment the <em>count </em>variable then <em>notifyListeners called.</em></p><pre>class HomeController extends ChangeNotifier {<br>  var _count = 0;<br>  get count =&gt; _count;</pre><pre>set count(value) {<br>    _count = value;<br>  }</pre><pre>increment(){<br>    _count++;<br>    notifyListeners();<br>  }<br>}</pre><p><strong>HomePage</strong></p><p>Handle to display our <em>count</em> changes</p><pre>class HomePage extends StatefulWidget {<br>  const HomePage2({Key? key}) : super(key: key);</pre><pre>@override<br>  State&lt;HomePage&gt; createState() =&gt; _HomePageState();<br>}</pre><pre>class _HomePageState extends State&lt;HomePage&gt; {<br>  final controller = HomeController();</pre><pre>@override<br>  void initState() {<br>    controller.addListener(() {<br>      print(&quot;${controller.count}&quot;);<br>      setState(() {});<br>    });<br>    super.initState();<br>  }</pre><pre>@override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(<br>        title: const Text(&quot;My app bar&quot;),<br>      ),<br>      body: Center(<br>        child: Column(<br>          mainAxisAlignment: MainAxisAlignment.center,<br>          children: [<br>            Text(&quot;${controller.count}&quot;),<br>            OutlinedButton(<br>              child: const Text(&quot;increment&quot;),<br>              onPressed: controller.increment,<br>            ),<br>          ],<br>        ),<br>      ),<br>    );<br>  }<br>}</pre><p>Behind the scenes ChangeNotifier contains</p><pre>List&lt;VoidCallback?&gt; _listeners = List&lt;VoidCallback?&gt;.filled(0, null);</pre><p>This is simply a list of callbacks, so for each “addListener”, it add the most recent callback to the list and the new data created will be changed by “notifyListeners”, resulting them to loop over all the listeners and emit them.</p><p>But if you look closely, you can see that <strong>setState</strong> is being used here (weird :/)</p><p><strong>FutureBuilder Vs StreamBuilder:</strong></p><p>Before digging into these components, let’s provide a theoretical explanation. For example, have you ever heard about observable pattern?! What is observable?!After reading many descriptions on google, stack-overflow, and more, I struggled to find any satisfactory explanation for it.So, let’s start by keeping it simple.</p><blockquote>Observable simply describes a machine that emits events directly to the subscribers (observers)</blockquote><p>If you want, I can write an additional article about it, so let me know in the comments</p><p>So, how does this relate to flutter?</p><p>Flutter, the “native” approach, is reactive, or in other words, observable, and can be divided in two:</p><p><strong>Cold observable:</strong></p><p>Let’s start with an example.</p><pre>Future&lt;User&gt; getUser() async{<br>  final user = await OurApi.getUser();<br>  return user;<br>}</pre><p>You may read this and think to yourself, “This is just ‘Future’, what do you want from us?”</p><p>You are correct, this is an async function, but how is cold observable relevant here? What does it mean?</p><p>Essentially it just gives me the data that I need all at once, and that’s it.</p><p>“Cold” observable is the “default”.</p><p><strong>Hot observable:</strong></p><p>Example of Hot Observable:</p><pre>class HotObservableSample {<br>  final _streamController = StreamController&lt;String&gt;.broadcast();<br>  <br>  void start(){<br>    _streamController.stream.listen((event) { <br>      //new value will receive from the event<br>    });<br>  }<br>  <br>  void changeValue(String value){<br>    _streamController.add(value);<br>  }<br>}</pre><p>Hot works differently. There is the “streamController”, the machine emitting the events, in addition to the observer, subscriber, and listener (no callbacks!!!).</p><p>As opposed to cold, this “machine” can emit states without any observers for each state.</p><p>In addition, if we observe this machine later, we will only see the newest values, excluding the values from the beginning of the list.</p><p>Let’s look at an analogy to summarize the differences:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ynonv7ypi78UHuGPdyPVBQ.png" /></figure><p>After describing the differences between these 2 observables , let’s see how this relates to state management.</p><p><strong>FutureBuilder</strong>: (Cold)</p><p>Example:</p><pre>class FutureBuilderSample extends StatefulWidget {<br>  const FutureBuilderSample({Key? key}) : super(key: key);</pre><pre>@override<br>  State&lt;FutureBuilderSample&gt; createState() =&gt; _FutureBuilderSampleState();<br>}</pre><pre>class _FutureBuilderSampleState extends State&lt;FutureBuilderSample&gt; {<br> <br> Future&lt;User&gt; getUser() async {<br>    final user = await OurApi.getUser();<br>    return user;<br>  }</pre><pre>@override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(<br>        title: const Text(&quot;My app bar&quot;),<br>      ),<br>      body: Center(<br>        child: FutureBuilder&lt;User&gt;(<br>            future: getUser(),<br>            builder: (context, snapshot) {<br>              if (snapshot.hasError) {<br>                return Text(&quot;has error: ${snapshot.error}&quot;);<br>              } else if (snapshot.hasData) {<br>                final user = snapshot.data!;<br>                return ListTile(<br>                  title: Text(user.name),<br>                  subtitle: Text(&quot;Age: ${user.age}&quot;),<br>                );<br>              } else {<br>                return const CircularProgressIndicator();<br>              }<br>            }),<br>      ),<br>    );<br>  }</pre><p>It will render the widget twice, so how is it that earlier you said cold emits once?! First time, it emits an event saying that it has “started”, the second time will be data or error. But how does this work behind the scenes?!</p><p>This is interesting, let’s dig inside the code::</p><pre>void _subscribe() {<br>  if (widget.future != null) {<br>    final Object callbackIdentity = Object();<br>    _activeCallbackIdentity = callbackIdentity;<br>    widget.future!.then&lt;void&gt;((T data) {<br>      if (_activeCallbackIdentity == callbackIdentity) {<br>        setState(() {<br>          _snapshot = AsyncSnapshot&lt;T&gt;.withData(ConnectionState.done, data);<br>        });<br>      }<br>    }, onError: (Object error, StackTrace stackTrace) {<br>      if (_activeCallbackIdentity == callbackIdentity) {<br>        setState(() {<br>          _snapshot = AsyncSnapshot&lt;T&gt;.withError(ConnectionState.done, error, stackTrace);<br>        });<br>      }<br>      assert(() {<br>        if(FutureBuilder.<em>debugRethrowError</em>) {<br>          Future&lt;Object&gt;.error(error, stackTrace);<br>        }<br>        return true;<br>      }());</pre><pre>});<br>    _snapshot = _snapshot.inState(ConnectionState.waiting);<br>  }<br>}</pre><p>Firstly, FutureBuilder is a S<em>tatefulWidget</em> ,it receives a parameter that is a function that returns “Future”</p><p>This whole process occurs in the “subscribe” function that is called from “<em>initState</em>” or “<em>didUpdateWIdget</em>”.</p><p>This method just processes the “future” function and for each state emitted, it will drop the state into AsyncSnapshot.</p><p>AsyncSnapshot is simply a callback function that alerts for each state of the future</p><p>Waiting declaration:</p><pre>const AsyncSnapshot.waiting() : this._(ConnectionState.waiting, null, null, null);</pre><p>Has data success declaration:</p><pre>const AsyncSnapshot.withData(ConnectionState state, T data): this._(state, data, null, null);</pre><p>This is what happens when an error occurs</p><pre>const AsyncSnapshot.withError(<br>  ConnectionState state,<br>  Object error, [<br>  StackTrace stackTrace = StackTrace.<em>empty</em>,<br>]) : this._(state, null, error, stackTrace);</pre><p>But if we look closely again, it uses setState again (weird…again :/)</p><p><strong>StreamBuilder:</strong></p><p>StreamBuilder is also a <em>StatfullWidget</em>.</p><p><em>StreamBuilder</em> receives a parameter that is a function that returns “stream” (i.e. StreamController, which we will discuss later)</p><p>StreamBuilder is a hot observable, so if compared to the radio station analogy, the stream builder is the listener and streamController is the radio station that emitting states.</p><p>It looks like this:</p><pre>class HomeTest extends StatefulWidget {<br>  const HomeTest({Key? key}) : super(key: key);</pre><pre>  @override<br>  State&lt;HomeTest&gt; createState() =&gt; _HomeTestState();<br>}</pre><pre>class _HomeTestState extends State&lt;HomeTest&gt; {<br>  final _countStreamController = StreamController&lt;int&gt;.broadcast();<br>  var count = 0;</pre><pre>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(<br>        title: const Text(&quot;counter&quot;),<br>      ),<br>      body: Center(<br>        child: Column(<br>          mainAxisSize: MainAxisSize.min,<br>          children: [<br>            StreamBuilder&lt;int&gt;(<br>                stream: _countStreamController.stream,<br>                builder: (context, snapshot) {<br>                  final state = snapshot.data ?? 0;<br>                  return Text(&quot;$state&quot;);<br>                }),<br>            OutlinedButton(<br>                child: const Text(&quot;count&quot;),<br>                onPressed: () {<br>                  _countStreamController.add(count++);<br>                }),<br>          ],<br>        ),<br>      ),<br>    );<br>  }<br>}</pre><p>But why do we need all this boilerplate code?!</p><p>Although we can simply use set state, this normally the incorrect way.</p><p>If we have several variables (states), we can harm the other states that are not related this specific state. In addition, if the screen is complicated with many widgets depending on multiple states, it can lower the performance.</p><p>For these situations, my moto is:</p><blockquote>“If you don’t need to render, don’t”</blockquote><p>What does this look like behind the scenes:</p><pre>StreamSubscription&lt;T&gt;? _subscription; <br>late S _summary;</pre><pre>@override<br>void initState() {<br>  super.initState();<br>  _summary = widget.initial();<br>  _subscribe();<br>}</pre><pre>@override<br>void didUpdateWidget(StreamBuilderBase&lt;T, S&gt; oldWidget) {<br>  super.didUpdateWidget(oldWidget);<br>  if (oldWidget.stream != widget.stream) {<br>    if (_subscription != null) {<br>      _unsubscribe();<br>      _summary = widget.afterDisconnected(_summary);<br>    }<br>    _subscribe();<br>  }<br>}</pre><pre>@override<br>Widget build(BuildContext context) =&gt; widget.build(context, _summary);</pre><pre>@override<br>void dispose() {<br>  _unsubscribe();<br>  super.dispose();<br>}</pre><pre>void _subscribe() {<br>  if (widget.stream != null) {<br>    _subscription = widget.stream!.listen((T data) {<br>      setState(() {<br>        _summary = widget.afterData(_summary, data);<br>      });<br>    }, onError: (Object error, StackTrace stackTrace) {<br>      setState(() {<br>        _summary = widget.afterError(_summary, error, stackTrace);<br>      });<br>    }, onDone: () {<br>      setState(() {<br>        _summary = widget.afterDone(_summary);<br>      });<br>    });<br>    _summary = widget.afterConnected(_summary);<br>  }<br>}</pre><p>The stream variable is incorporated in the “statefulWidget”.</p><p>Looking at the “<strong>subscribe”</strong> function, it listens consistently to the stream and for each state, it calls for setState (again setState why?!?!?!).</p><p>With this information, you might ask me, how is this harmful?</p><p>Let me show you 2 examples, one is wrong, and the other is correct.</p><p>Example A:</p><pre>class WrongPage extends StatefulWidget {<br>  const WrongPage({Key? key}) : super(key: key);</pre><pre>  @override<br>  State&lt;WrongPage&gt; createState() =&gt; _WrongPageState();<br>}</pre><pre>class _WrongPageState extends State&lt;WrongPage&gt; {<br>  var count = 0;<br>  var name = &quot;sahar&quot;;</pre><pre>  @override<br>  void didUpdateWidget(covariant WrongPage oldWidget) {<br>    super.didUpdateWidget(oldWidget);<br>    name = &quot;&quot;;<br>  }</pre><pre>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(<br>        title: const Text(&quot;counter&quot;),<br>      ),<br>      body: Center(<br>        child: Column(<br>          mainAxisSize: MainAxisSize.min,<br>          children: [<br>            Text(&quot;$count&quot;),<br>            Text(name),<br>            TextField(<br>              onChanged: (input) {<br>                setState(() {<br>                  name = input;<br>                });<br>              },<br>            ),<br>            OutlinedButton(<br>                child: const Text(&quot;count&quot;),<br>                onPressed: () {<br>                  setState(() {<br>                    count++;<br>                  });<br>                }),<br>          ],<br>        ),<br>      ),<br>    );<br>  }<br>}</pre><p>Example B</p><pre>class CorrectWayPage extends StatefulWidget {<br>  const CorrectWayPage({Key? key}) : super(key: key);</pre><pre>  @override<br>  State&lt;CorrectWayPage&gt; createState() =&gt; _CorrectWayPageState();<br>}</pre><pre>class _CorrectWayPageState extends State&lt;CorrectWayPage&gt; {<br>  var count = 0;<br>  var name = &quot;sahar&quot;;<br>  final _countStreamController = StreamController&lt;int&gt;.broadcast();<br>  final _nameStreamController = StreamController&lt;String&gt;.broadcast();</pre><pre>  @override<br>  void didUpdateWidget(covariant CorrectWayPage oldWidget) {<br>    super.didUpdateWidget(oldWidget);<br>    name = &quot;&quot;;<br>  }</pre><pre>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(<br>        title: const Text(&quot;counter&quot;),<br>      ),<br>      body: Center(<br>        child: Column(<br>          mainAxisSize: MainAxisSize.min,<br>          children: [<br>            StreamBuilder&lt;int&gt;(<br>                stream: _countStreamController.stream,<br>                builder: (context, snapshot) {<br>                  final state = snapshot.data ?? 0;<br>                  return Text(&quot;$state&quot;);<br>                }<br>            ),<br>            StreamBuilder&lt;String&gt;(<br>                stream: _nameStreamController.stream,<br>                builder: (context, snapshot) {<br>                  final state = snapshot.data ?? &quot;&quot;;<br>                  return Text(state);<br>                }<br>            ),<br>            TextField(<br>              onChanged: (input) {<br>                setState(() {<br>                  name = input;<br>                });<br>              },<br>            ),<br>            OutlinedButton(<br>                child: const Text(&quot;count&quot;),<br>                onPressed: () {<br>                  setState(() {<br>                    count++;<br>                  });<br>                }),<br>          ],<br>        ),<br>      ),<br>    );<br>  }<br>}</pre><p>Now please take a minute to think about which example will work correctly.</p><p>Let’s first talk about the functionality. We have a button that increases count variable, and our textfield changes the name by the input.</p><p>In our example, for each setState, the “count” variable will work fine.</p><p>Each time we want to change the “name” variable and call setState, nothing will happen because didUpdateWidget will be called directly after setState and reset it (wrong!!). If we want to put some logic in our “lifecycles” functions, setState can cause many issues.</p><p>On the other hand, streambuilder will not call to this parent lifecycle for each additional state.</p><p>Fix the bug :)</p><p><strong>SetState</strong></p><p>This is the only way to really render the screen, From the docs “<em>Notify the framework that the internal state of this object has changed.</em>” This is maybe one of the only functions that communicates with the “skia” engine to render the screen.</p><p>But what really happens is that it goes to next frame. All “gui” are images running on frames one after another, and if our fps (frames per second) is high, each render will look smoother.</p><p>Now we need to understand when to use it, so let’s look at the documentation from flutter for best practice:</p><p><a href="https://docs.flutter.dev/perf/best-practices">https://docs.flutter.dev/perf/best-practices</a></p><p>“When setState() is called on a State object, all descendent widgets rebuild. Therefore, localize the setState() call to the part of the subtree whose UI actually needs to change. Avoid calling setState() high up in the tree if the change is contained to a small part of the tree.”</p><p>What’s going on here?!</p><p>To put it more simply, setState can be used when we want to render a child that is part of the screen or part of a complex widget. For example, if we have a button that changes colors on each click, we can create a dependent widget for it that replaces the color for each click with setState, which is the correct way. FutureBuilder and streamBuilder are implements it but with wrapping.</p><p><strong>Solution sample:</strong></p><pre>class ComplexScreen extends StatefulWidget {<br>  const ComplexScreen({Key? key}) : super(key: key);</pre><pre>  @override<br>  State&lt;ComplexScreen&gt; createState() =&gt; _ComplexScreenState();<br>}</pre><pre>class _ComplexScreenState extends State&lt;ComplexScreen&gt; {<br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(<br>        title: const Text(&quot;my complex screen&quot;),<br>      ),<br>      body: Column(<br>        children: [<br>          //... a-lot of widgets<br>          MyButton(onClick: (){})<br>        ],<br>      ),<br>    );<br>  }<br>}</pre><pre>class MyButton extends StatefulWidget {<br>  final Function() onClick;</pre><pre>  const MyButton({Key? key, required this.onClick}) : super(key: key);</pre><pre>  @override<br>  State&lt;MyButton&gt; createState() =&gt; _MyButtonState();<br>}</pre><pre>class _MyButtonState extends State&lt;MyButton&gt; {<br>  final color1 = Colors.<em>blue</em>;<br>  final color2 = Colors.<em>yellow</em>;<br>  var first = true;</pre><pre>  @override<br>  Widget build(BuildContext context) {<br>    return ElevatedButton(<br>        child: const Text(&quot;Click&quot;),<br>        style: ElevatedButton.<em>styleFrom</em>(primary: first ? color1 : color2),<br>        onPressed: () {<br>          setState(() {<br>            first = !first;<br>          });<br>          widget.onClick();<br>        });<br>  }<br>}</pre><p>In conclusion, before using libraries for state management, first try out these components and try to understand the correct way to utilize setState instead of avoiding it. Then, once you understand all the basic components presented above, then you can go use external state management libraries.</p><p>When understanding what truly happens behind the scenes, it significantly simplifies the process of development.</p><p><a href="https://twitter.com/FlutterComm">https://twitter.com/FlutterComm</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=48a81ed7979d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/flutter-community/stop-using-state-management-libraries-48a81ed7979d">“Stop” using state management libraries</a> was originally published in <a href="https://medium.com/flutter-community">Flutter Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>