<?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[suamusicatech - Medium]]></title>
        <description><![CDATA[Um espaço para compartilhar os aprendizados e conhecimentos do time de tecnologia do Sua Música - Medium]]></description>
        <link>https://medium.com/suamusicatech?source=rss----6eb20003fe19---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>suamusicatech - Medium</title>
            <link>https://medium.com/suamusicatech?source=rss----6eb20003fe19---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 15:35:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/suamusicatech" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[ Powering up your app with Firebase]]></title>
            <link>https://medium.com/suamusicatech/powering-with-firebase-5cd4fa6e2932?source=rss----6eb20003fe19---4</link>
            <guid isPermaLink="false">https://medium.com/p/5cd4fa6e2932</guid>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[product]]></category>
            <category><![CDATA[ab-testing]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[testing]]></category>
            <dc:creator><![CDATA[Felipe Sales]]></dc:creator>
            <pubDate>Wed, 17 Apr 2024 13:38:28 GMT</pubDate>
            <atom:updated>2024-04-17T17:36:26.644Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>and the possibilities to boost your business.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/954/1*TCh0DffADYxDbm9O4M4L5A.png" /></figure><h3>Table of Contents</h3><p>—<a href="#72af"> Who I Am</a><br>— <a href="#0518">What is Firebase</a><br>— <a href="#19e9">Pros and Cons</a><br>— <a href="#21cd">Concept of Feature-Flag / Feature-Toggle</a><br>— <a href="#59bf">A/B Testing at Sua Música</a><br>— <a href="#59bf">The showcase</a><br>— <a href="#067b">Remote Config and Scalability</a><br>— <a href="#30cd">Q&amp;A</a><br>— <a href="#9df6">Finals Considerations</a></p><h3>Who I Am</h3><p>I am Felipe Sales, a developer who has been actively engaged in the Flutter market for a more than 2 years. I also have experience creating courses for developers - with courses on Udemy and contents on Rocketseat.</p><p>Actually, I am a software engineer at <strong>Sua Música</strong>, the <strong>largest platform for Brazilian music content</strong>; directly involved in the application - with 10M+ downloads on the Play Store.</p><p>Addictionally, I share programming related content on my social medias, <a href="https://www.linkedin.com/in/felipecastrosales/">see here</a>.</p><h3>🤔 What is Firebase?</h3><p>Firebase is Google&#39;s cloud-based app development platform for building applications, providing resources to create better apps, enhance quality, and strengthen your growth.</p><p>And this suite of tools <strong>adds value at every stage of your development journey</strong>. Build, release and engagement; three <strong>key points for a successful project</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/1*Mad1qusoErfRbXZEY1Og7w.png" /><figcaption>Those are the three general points.</figcaption></figure><p>And principal consequence of this is the <strong>scalability</strong> that this can bring to your app. Scalability that results in a high degree of flexibility for your project, capable of make it 100% customizable and with multiple testing possibilities.</p><h3>🤔 Pros and Cons</h3><h3>✅ Pros</h3><h3>01. Setup and quick integration.</h3><p>Easy to integrate into the application, as it has materials and most documentations that explain how to do it - from Firebase itself and externals.</p><h3>02. Resources and funcionalities.</h3><p>Provide a serie of services with easy integration, configuration and with each scope (from Authentication to A/B Testings [keep this concept in mind, we will talk more about it]).</p><h3>03. Scalability and integration.</h3><p>When well optimized and used intelligently, Firebase is a great friendly for project scalability and integration of the entire ecosystem.</p><h3>04. Community, engagement and suport.</h3><p>Because it is widely used and has a large community, if you have a problem, a bug, or have a question about some functionality it provides, this doubt has certainly already been answered in some issue of GitHub, StackOverFlow topic, open communities, or others devs can help you.</p><h3>05. Versatile solution.</h3><p>Can be used in various projects and contexts, both for personal objectives and for companies with million of users. This versatility provides flexible and adapts solutions for business requirements.</p><h3>❌ Cons</h3><h3>01 | Prices and plans.</h3><p>When not optimized and/or used excessively it&#39;s possible that costs be will be high compared to others services (even more so if consider exchange rate and usage).</p><h3>02 | Support in specific cases.</h3><p>It&#39;s possible that you have a very specific case where support may not provide a considerable and helpful answer that helps you. I already needed it and did not have a good experience - but it was a very specific case.</p><h3>03 | Changes and failures in SDKs.</h3><p>Due to internal integrations that are made, it is possible that errors may come from your SDK - some may be minor, and others may even be fatal (automatically closing the application).</p><h3>04 | Vendor Lock-in.</h3><p>It&#39;s very probably to happen when using - but this is not exclusive to Firebase (however it is ideal be aware that a possible migration will be more work).</p><h3>05 | Documentation.</h3><p>You may encounter issues in the documentation or even that it is not as clear as you would like - due to the specifies of each case. A tip is to always look for examples and/or ask in the communities.</p><blockquote><em>It is important here to understand your needs and whether Firebase is suitable for them, in most of the cases that we will show below it is more than sufficient and serves very well.</em></blockquote><h3>🔎 Concept of Feature-Flag / Feature-Toggle</h3><p>An increasingly common practice in market is adoption of <strong>feature-flag / feature-toggle</strong>. This concept allows flexibility regarding the <strong>control of features</strong> without need for changes in code and/or new deployment.</p><p>For example: controlling what will be displayed, the behaviour of a feature, layout arrangements, display of messages and notifications etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/599/1*U4ILevl8YHlAEPiKEZau4A.png" /><figcaption>This image show a little in practice what the behaviour of a feature-flag might can be.</figcaption></figure><p>And this is where the concept of <strong>A/B Testing</strong> comes in, where Firebase has integration between services that can be used for this:</p><ul><li>Firebase Remote Config (<a href="https://firebase.google.com/docs/remote-config?hl=pt-br">click here to learn more</a>);</li><li>Google Analytics (<a href="https://firebase.google.com/docs/analytics?hl=pt-br">click here to learn more</a>);</li></ul><h3>📈 Behaviour in the practice</h3><p>See the image below and consider that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/639/1*ehYVWzqG3OkIM_yKH8dzhg.png" /></figure><ol><li>This is the same application;</li><li>The same things are being showed in differents ways - in other words, it&#39;s in an A/B Testing to identify which of this formats is the best and which will be used from now on.</li></ol><p>After consider this, let&#39;s move on to the keys points of an A/B Test.</p><h3>🟰 Point 1. Distribution</h3><p>An A/B test can have different distributions. You can select whichever one you want.</p><p>Let&#39;s take an example, consider that:</p><ul><li>You have 100.000 users in the base;</li><li>20% of users (20.000) are selected for the experiment mentioned above;</li><li>In practice, the value distributed within this 20% was:<br> — 10.000 users with type A (50% of the 20%);<br> — 10.000 users with type B (50% of the 20%);</li></ul><p>💡 It&#39;s worth remembering that this is the default distribution, 50/50; but it&#39;s also possible to have different distributions and Firebase handles the distribution and expected calculations.</p><h3>📊 Point 2. Statistic</h3><p>After experiment is done, there is the value of <strong>Conversion Rate</strong>. In this same test, the conversion rate for <strong>A</strong> was 40% and <strong>B</strong> was 54%.</p><p>Considering that <strong>A</strong> was the old layout and <strong>B</strong> was the new one, we see that the new one converts much more and it is acceptable for change to apply to all users, that is, 100% of 100.000.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/1*mjjglok5DXfcy30DQwkpKg.png" /><figcaption>With this, we can undertand and predict in a certain way which would have the greatest impact taking into account the statistics of this.</figcaption></figure><h3>💡 The possibilities</h3><p>Have you ever imagined that everything can be controlled through strings, numbers and booleans?</p><p>In practice, we see that:</p><ul><li>The total control of components can be 100% configurable;<br> — Positioning, the animation, order of elements as a whole.</li><li>Activation or deactivation of specific features can be controlled;</li><li>Target audiende segmentation;</li><li>Dynamic change of behaviours and dynamic values based in your preference;</li><li>In addiction to colors, texts, fonts, spacements, sizes and much more.</li></ul><p>The possibilities are infinites; and the best of all is know that your have the datas and statistics for your decisions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/1*bmC_rFR7cknp9gIcM6smPw.png" /></figure><h3>💰 Another common example - ADs Case</h3><p>Is very common for today applications to have some type of adversiting, and it&#39;s common for the Product team search to seek the best way to take advantage of them.</p><p>With this, remote configuration also flourishes, because you can experiment with different formats, frequencies and placements for them to appear.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*C8EDEJJN_V_80rhaVOPpMQ.png" /></figure><h3>🏆 The developer and the pillar of success.</h3><p>Everything depends on the goal that you want to achieve and test.</p><p>And how the developer prepares their components to be flexible enough for the tests.</p><p>And that&#39;s where the importance <strong>of ensuring that one option is superior to another; based on reliable analysis and statistics</strong> arises.</p><p>Ignoring the instinct and supositions that may not yield results for users - and consequently for the product, which can bring losses.</p><p><strong>Take advantage of the data-driven world and make these powers that are within your reach an essential part of the validation and implementation proccess.</strong></p><h3>💸 The cost of it all.</h3><p>Stop for a few seconds and guess a value that you imagine be for the use of this service…</p><h4>Forget about it! It&#39;s fully free. You won&#39;t have any cost to implement this, regardless of whether there 1 user or 1 million.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v0klIpiDVooWsaOANj-3Dg.png" /></figure><h3>🎵 A/B Testing at Sua Música</h3><p><strong>Sua Música is the largest streaming platform in Brazil</strong>, where artists can release their music to millions of people for free. Besides providing an entire ecosystem for user interaction, through apps, website and social media channels - such as <a href="https://instagram.com/suamusica">Instagram</a>.</p><p>With an app that has over than 10 millions downloads at PlayStore and 1M DAU (Daily Active Users), it&#39;s crucial that it&#39;s be remotely configurable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*l0CodcPRCINFHxGd.png" /></figure><p>In other works, being able to remotely define the behaviour of a feature, the positioning of a component, their order, as well as color, size and other details that can make a difference.</p><p>Here, we use this strategy and conduct many A/B tests to validate the formats that will retain users the most and use these statistics to make best decision (based on real data).</p><p>Since the beginning, when Firebase was starting to bring these features, we have experimented and put them into practice. The gains are notable because we can adapt the user experience based on the feedback that we receive, giving an interaction more customizable and efficient interactions.</p><p>Though data analysis, we can justify the implementation or not. And thus, we can <strong>measure the success of any feature based on data and not on assumptions</strong>.</p><h3>🌟 The showcase</h3><p>To exemplify a showcase, I develop an application from scratch to demonstrate how this can be made.</p><p>If you want to test it, you will have this repository:</p><p><a href="https://github.com/felipecastrosales/remote/tree/2c0a0f60238d3c09c39f9b6d7b23f6e81c3bd771">GitHub - felipecastrosales/remote at 2c0a0f60238d3c09c39f9b6d7b23f6e81c3bd771</a></p><p>In it, we want to conduct tests to verify if new formats and orders could make the user more engaged.</p><p>So, the Product Team suggested some variants based on current base; that is, <strong>A</strong>, <strong>B</strong> and <strong>C</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*etwAIW5pmV64r5Z0Xzm-5g.png" /></figure><p>If we stop to observe, each of this orders have a reason to be implemented, but not necessarily will be one in specific which put directly results for an business.</p><p>In other words, these 4 formats will be tested to identify the best format to follow in practice.</p><p>But we need to think the challenges that this will have, which are:</p><ol><li>How will I order these components in differents ways and distribute this?</li><li>How will I know which one was the best in the test?</li></ol><p>For both challenges, Firebase has the solutions, the Remote Config and Google Analytics (as mentioned previously).</p><ol><li><strong>Answer</strong>: Firebase Remote Config has support for string, number, boolean and json - formats that open up an infinite range of possibilities.</li><li><strong>Answer</strong>: Though sending <strong>unique events</strong> to Google Analytics, which will give to you <strong>numbers and statistics</strong> of engagement and actions performed (which we call as convertion).</li></ol><h3>🛠️ Firebase Setup</h3><blockquote>Since it&#39;s not the main focus, we let&#39;s start from the point where you have performed the Firebase setup (which you can find how to do via Firebase documentation or by searching like: &quot;[your tecnology] firebase setup”.</blockquote><p>Due didatic finally and to turn it a bit clear, I will show how my setup and all the configuration steps were done using <strong>Flutter</strong> - so you can adapt the concepts and strategies to tecnology that you use.</p><h3>⚙️ 1 Step: Remote Config.</h3><p>From a technical standpoint, the challenge is to make a static screen become remote, so we have the HomePage built in this way:</p><pre>class HomePage extends StatelessWidget {<br>  const HomePage({super.key});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return const SingleChildScrollView(<br>      child: Column(<br>        children: [<br>          HomeHeaderWidget(),<br>          MyAccount(),<br>          ServiceWidget(),<br>          OffersWidget(),<br>          MyCards(),<br>          CreditCard(),<br>          LoanWidget(),<br>          FollowWidget(),<br>          DiscoverOffersWidget(),<br>          AppDivider(),<br>        ],<br>      ),<br>    );<br>  }<br>}</pre><p>So ok! Now let&#39;s to start turning this 100% remote.</p><ol><li>In your main(), add the setup of Firebase; so that its inicialization will be done:</li></ol><pre>Future&lt;void&gt; main() async {<br>  WidgetsFlutterBinding.ensureInitialized();<br>  await AppFirebaseService().setUpInitialization(); /// setup<br><br>  runApp(<br>    const App(),<br>  );<br>}</pre><p>2. Now, for this class, add the following:</p><pre>import &#39;dart:developer&#39; as developer;<br><br>import &#39;package:firebase_core/firebase_core.dart&#39;;<br>import &#39;package:firebase_remote_config/firebase_remote_config.dart&#39;;<br>import &#39;package:remote/firebase_options.dart&#39;;<br>import &#39;package:remote/src/data/services/firebase/firebase.dart&#39;;<br><br>class AppFirebaseService {<br>  /// Initializes Firebase and Remote Config.<br>  Future&lt;void&gt; setUpInitialization() async {<br>    await Firebase.initializeApp(<br>      options: DefaultFirebaseOptions.currentPlatform,<br>    );<br>    await setUpRemoteConfig();<br>  }<br><br>  /// Sets up Remote Config, sets defaults, and fetches and activates the config.<br>  Future&lt;void&gt; setUpRemoteConfig() async {<br>    try {<br>      final remoteConfig = FirebaseRemoteConfig.instance;<br>      await remoteConfig.setDefaults(AppFirebaseDefaults.getRemoteConfigKeys);<br>      await remoteConfig.setConfigSettings(AppFirebaseSettings().config);<br>      await remoteConfig.fetchAndActivate();<br>    } catch (e, s) {<br>      developer.log(<br>        &#39;setUpRemoteConfig&#39;,<br>        name: &#39;AppFirebaseService&#39;,<br>        error: e,<br>        stackTrace: s,<br>      );<br>    }<br>  }<br>}<br><br>/// Settings for Firebase Remote Config, such as fetch timeout and minimum fetch interval.<br>class AppFirebaseSettings {<br>  final config = RemoteConfigSettings(<br>    fetchTimeout: const Duration(hours: 1),<br>    minimumFetchInterval: const Duration(hours: 1),<br>  );<br>}<br><br>/// [AppFirebaseRemoteKeys] contains the remote keys for the remote config.<br>class AppFirebaseRemoteKeys {<br>  static const homeRemoteOrder = &#39;home_remote_order&#39;;<br>}<br><br>/// Default values for Remote Config.<br>class AppFirebaseDefaults {<br>  static get getRemoteConfigKeys =&gt; {<br>        AppFirebaseRemoteKeys.homeRemoteOrder:<br>            &#39;account,services,myCards,offers,divider,creditCard,divider,loans,divider,follow,divider,searchOffers&#39;,<br>      };<br>  }<br>}<br><br>/// Get Remote Config values.<br>class AppFirebaseRemoteGet {<br>  static String get homeRemoteOrder =&gt; FirebaseRemoteConfig.instance<br>      .getString(AppFirebaseRemoteKeys.homeRemoteOrder);<br>}</pre><p>And now, do this in your HomePage - and the coolest thing about it is using the powers of <strong>Dart 3.0.0</strong> with the new switch):</p><pre>class HomePage extends StatelessWidget {<br>  const HomePage({super.key});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return SingleChildScrollView(<br>      child: Column(<br>        children: [<br>          const HomeHeaderWidget(),<br>          /// This is the part of the code that was changed to use the remote order<br>          /// instead of the default order. <br>          /// The remote order is fetched via the AppFirebaseRemoteGet class,<br>          /// that gets the remote order from the Firebase Remote Config.<br>          for (final item<br>              in AppFirebaseRemoteGet.homeRemoteOrder.trim().split(&#39;,&#39;))<br>            switch (item.trim()) {<br>              HomeABKeys.account =&gt; const MyAccount(),<br>              HomeABKeys.services =&gt; const ServiceWidget(),<br>              HomeABKeys.servicesGrid =&gt; const ServiceGridWidget(),<br>              HomeABKeys.myCards =&gt; const MyCards(),<br>              HomeABKeys.offers =&gt; const OffersWidget(),<br>              HomeABKeys.creditCard =&gt; const CreditCard(),<br>              HomeABKeys.loans =&gt; const LoanWidget(),<br>              HomeABKeys.follow =&gt; const FollowWidget(),<br>              HomeABKeys.searchOffers =&gt; const DiscoverOffersWidget(),<br>              HomeABKeys.divider =&gt; const AppDivider(),<br>              /// If want to add space remotely between widgets<br>              _ when double.tryParse(item) != null =&gt;<br>                SizedBox(height: double.parse(item)),<br>              _ =&gt; const SizedBox(),<br>            },<br>        ],<br>      ),<br>    );<br>  }<br>}</pre><p>Now, let&#39;s add the key home_remote_order in our Remote Config:</p><ol><li>Go to Engage &gt; Remote Config &gt; Create Configuration and click;</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JGMi6vVztcR3FjMA" /></figure><p>2. Create your first parameter and add value to it, in this case, we will put: account,services,myCards,offers,divider,creditCard,divider,loans,divider,follow,divider,searchOffers;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MfqkpQgDzDTB-AuDQkrZhQ.png" /></figure><p>3. After saving, publish your changes;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f2fFudrH8YYiqK60d99Hhw.png" /></figure><p>4. After publication, this will already be available to be used in your app, and the changes you make here already be reflected in your project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GqpkfudZXDTwE9qmbRBjaw.png" /></figure><ul><li>Tip: Leave fetchTimeout and minimumFetchInterval in your code low values - to always keep them updated -, such as 1 second. Add do the hot-restart so that your setup is done again (or reload the application).</li></ul><blockquote>And that&#39;s it! Your ordering is now remote, and you are already using the powers of Remote Config in your app.</blockquote><h3>🔍 2 Step: Google Analytics.</h3><p>You will need to track events for each component in question - and this is personal and specific for each test case. Here&#39;s a generic strategy that will help in most cases:</p><pre>/// The Firebase Analytics helper class, that log events to Firebase Analytics.<br>class AppFirebaseAnalytics {<br>  /// Logs an event with the given [name].<br>  static void logEvent(String name) {<br>    final event = name.replaceAll(&#39; &#39;, &#39;&#39;);<br>    try {<br>      FirebaseAnalytics.instance<br>          .logEvent(name: event)<br>          .then((value) =&gt; debugPrint(&#39;Analytics - logEvent: $event&#39;));<br>    } catch (e) {<br>      debugPrint(&#39;Analytics - logEvent: $event, error: $e&#39;);<br>    }<br>  }<br><br>  /// Logs events with the given [names].<br>  static void logEvents(List&lt;String&gt; names) {<br>    for (var name in names) {<br>      logEvent(name);<br>    }<br>  }<br><br>  /// Logs a [HomeTap] event with the given [names].<br>  static void logHomeEvent(List&lt;String&gt; names) =&gt;<br>      logEvents([&#39;HomeTap&#39;, for (var name in names) name]);<br>}</pre><p>And in your component, you can use on clicks, for example:</p><pre>onTap: () {<br>  /// This logs HomeTap and Finance events.<br>  AppFirebaseAnalytics.logHomeEvent(&#39;Finance&#39;);<br>}</pre><p><strong>Observations:</strong></p><ol><li>💡 Here comes the importance of creating <strong>reusable components</strong>, where you leave an event by default and pass differents event names defined by parameters; and with this covering 100% of your app with events. This allows you to understand user behaviour.</li><li>💡 Remember that each event <strong>should be unique</strong>. That is, it should uniquely cover a flow, a functionality and/or a component. This will ensure that your events are evenly distributed in the test and allow for precise analysis of the results.</li></ol><p>Check more about this strategy in through this commit:</p><p><a href="https://github.com/felipecastrosales/remote/commit/f231c6820637b52eda3396b725c1f81494135829">feat: application added with proposed features (firebase_core, fireba... · felipecastrosales/remote@f231c68</a></p><blockquote>And done! You have covered your app with the 2 main points before creating your A/B test; now let&#39;s move on to the most important part.👇</blockquote><h3>🧪 How to create an A/B Test | In practice</h3><p>1. Access <a href="https://console.firebase.google.com/u/0/">Firebase Console</a> and select your project;</p><p>2. Go to Engage &gt; A/B Testing &gt; Create Experiment;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WkZfIU1S1flle37e" /></figure><p>3. After that, you will see that there are 3 options for test: Notifications, Remote Config and In-App Messaging; we will focus on Remote Config.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LQ83ciOyEGSIrs0h" /></figure><p>Now let&#39;s start the creation!</p><p>4. <strong>[BASICS] </strong>(1): Give the name and description of your experiment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OF4FYREPuO-ssAlC" /></figure><p>5.<strong> [TARGETING] </strong>(2): The moment to choose specifics of your test.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lBKBAy_58hOZ6oKn" /></figure><p>6. <strong>[TARGETING]</strong> (2): Choose the desired platform - iOS / Android / Web... <br>(it is likely that you create another test to apply to all users - Firebase starts from this on the Operating System target, you can see there are 3 in my example).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pBcJeVmpNYs-WRcG" /></figure><p>7. <strong>[TARGETING]</strong> (2): Note that you already have the numbers of users who will be in the experiment, and you can choose the <strong>desired percentage</strong> though Exposure.<br>(in our case, we will make it for 100% of users)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fBI9-eKUebDH3_os" /></figure><p>8. <strong>[TARGETING]</strong> (2): You probably want to specify your test a little more and see more available options before publishing anything. <br>In this way, click on and:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZHPr6o-KBnBvCS3N" /></figure><p>9. <strong>[TARGETING]</strong> (2): Now click on the dropdown so that the segmentation options appear:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*551zFJ3A1A024yrs" /></figure><p>10. <strong>[TARGETING]</strong> (2): There are several segmentations you can choose from, it&#39;s multiple (I recommend you explore and do the desired segmentation).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hGaMYG8Kkz17p7wX" /></figure><p>11. <strong>[TARGETING]</strong> (2): See this example, we selected that:</p><ul><li>We want that the language to be in portuguese;</li><li>The build number is 10 (choose what you want to segment appropriately considering the release when the feature was launched); - it may also be interesting to add the Version.</li><li>That audience is customers;</li><li>And that the entry was after the chosen date in a specific timezone.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*g41vfKgNJbCc8Tdc" /></figure><p>12. <strong>[TARGETING]</strong> (2): It&#39;s also possible to add an activation event; this is like a starting point / condition for the user to participate in the experiment.</p><ul><li>That is, a click, a purchase, entering in specific screen… whatever you want as a start point for the test to begin.</li></ul><blockquote>I have to repeat, this is very complete!</blockquote><p>13. <strong>[Goals]</strong> (3): Now the goals - where you will select the main metrics to determine which variant of these tests will be lead. By default, these are the metrics that Firebase itself puts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7-DGF19gTRQAv9Xe" /></figure><p>14. <strong>[Goals]</strong> (3): To add different goals, click here:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fueaIBCRKyHdpCVR" /></figure><p>15. <strong>[Goals]</strong> (3): Here are more options, you can also add or search for events (considering that you can have N (multiples) events).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*dp-sYqSPAunWJ6Cp" /></figure><p>16. <strong>[Goals]</strong> (3): When you already have recent events saved, they will also appear in the list. If they don&#39;t appear, you can create them manually and Firebase should increment and use it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/530/0*FcxvBjZTiMPoaV0s" /></figure><p>17. <strong>[Goals] </strong>(3): Select all the events you want to use as metric for A/B test. The maximum is 5 (additional) + 1 (the main metric).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NLf7wkVK2vnKpqux" /></figure><h4>⚠️ <strong>IMPORTANT OBSERVATION:</strong></h4><ul><li><strong>Each event must be unique for this analysis to be given only to the scope of the test.</strong></li><li>If the event be used in another scope and/or not well distributed (in other words, it is in one variant and not in another), this tests may be invalid - because Firebase will add it to the in test.</li><li>For example: suppose that an &quot;PURCHASE” event is used as a metric for an A/B test on the new purchase screen, but it is also used in others parts of the application that are not related to the test. This would cause Firebase to count all occurrences of the event, not just those related to A/B test.</li></ul><p>18. <strong>[Variants]</strong> (4): Now is the time to choose the variants that will go into your test. Here, you will add the parameters (keys) and their respective values that will be used in each variation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hECxAjsoW46uCQuS" /></figure><ul><li>Here, it&#39;s important to note that you can have multiple variations and keys in each variation, meaning you have infinite possibilities and test cases.</li><li>As this is about remote ordering, the following orders were placed in each variation, respectively:</li><li>account,services,myCards,offers,divider,creditCard,divider,loans,divider,follow,divider,searchOffers</li><li>account,services,offers,myCards,divider,creditCard,divider,loans,divider,follow,divider,searchOffers</li><li>account,myCards,offers,services,divider,creditCard,divider,loans,divider,follow,divider,searchOffers</li><li>account,servicesGrid,myCards,offers,divider,creditCard,divider,loans,divider,follow,divider,searchOffers</li></ul><p>19.<strong> [Variants]</strong> (4): If you want, you can perform a customized distribution for each one - by default, the distribution wil be equal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5PkR8utiLDk4d44R" /></figure><p>20. <strong>[Review]</strong> (5): Upon clicking in review, you will have the draft of your test.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/366/0*QNRM1UHa7LIDU2br" /></figure><p>21. <strong>[Review]</strong> (5): You will have a preview to finalize last details, review and even share the experiment link with others before launching it to all users. You can click here to get more details about your test.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UbnAZFlNxaDpPJMq" /></figure><p>22. <strong>[Review]</strong> (5): You will have all the details about your experiment, where you can edit, view more details in the menu icon (where you can add test devices) etc. After all this, you can start the experiment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*41vufcmAqkYOHhwt" /></figure><p>23. <strong>[Review]</strong> (5): Confirm the release of the experiment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/0*aPH1qGWneWJD8zYs" /></figure><p>24. <strong>[Experiment] </strong>(6): <strong>Done!</strong> Now your test is available for the selected users; wait a few hours and the first data will be shown.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*e361CXW93GqpNdjX" /></figure><p>25. <strong>[Experiment] </strong>(6): Your test will also appear on Firebase dashboard:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*H6mLA5O3EsN88Plu" /></figure><p>26.<strong> [Experiment] </strong>(7): After a period, you can already see the first datas.</p><ul><li>Since this is a simple app for didatic purposes, the results are statistically insignificat; but certainly in a real application, this would yield more <strong>meaningful results</strong>.</li><li>Based on our defined metrics, whether it&#39;s increasing users, improving retention and/or engagement, we can decide with <strong>data-driven</strong> <strong>rather than relying on assumptions</strong>, the best alternative for the application.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8u65lvahOIBSICpG" /><figcaption>An example of results from an AB test using Remote Config.</figcaption></figure><h3>🚀 Remote Config and Scalability</h3><h4>The main idea behind all of this is to make you understand the <strong>powers that Firebase can bring to your project</strong>.</h4><p>Besides, primarily, <strong>it makes you confident in the decision to be made regarding the best formats to be used</strong>. This progressively provides scalability for configuring and managing the application without the need for a new deployment.</p><p>With all this power, you make decisions effectively, due to the grounding and analysis that have been done.</p><h3>💬 Q&amp;A</h3><p>If you have any questions I&#39;m available to help and collaborate in this aspect.</p><p>My social networks are:</p><ul><li><a href="https://felipecastrosales.com/">https://felipecastrosales.com/</a></li></ul><h3>📝 Finals Considerations</h3><p>What did you think about this article? Undoubtedly, it should be one of the most comprehensive on this topic in the community; in addiction, to being comprehensive for any area and professionals interested; from developers to product teams, this will certainly add a lot of value.</p><h4>Due this, consider giving some 👏 here, to help reach more people, strenghten these contents and support this initiative.</h4><p><strong>Thanks and lets go, aiming for the next level! <em>🏆</em></strong></p><p>If you want to see and access the complete example, see the link below:</p><p><a href="https://github.com/felipecastrosales/remote">GitHub - felipecastrosales/remote: Flutter App for &quot;Powering your app with Firebase&quot; TechTalk.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5cd4fa6e2932" width="1" height="1" alt=""><hr><p><a href="https://medium.com/suamusicatech/powering-with-firebase-5cd4fa6e2932">🪄 Powering up your app with Firebase</a> was originally published in <a href="https://medium.com/suamusicatech">suamusicatech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Context Extension]]></title>
            <link>https://medium.com/suamusicatech/context-extension-4cf4512d3db0?source=rss----6eb20003fe19---4</link>
            <guid isPermaLink="false">https://medium.com/p/4cf4512d3db0</guid>
            <category><![CDATA[flutter-brasil]]></category>
            <category><![CDATA[flutter-widget]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[extension-method]]></category>
            <dc:creator><![CDATA[Felipe Sales]]></dc:creator>
            <pubDate>Mon, 31 Oct 2022 14:01:13 GMT</pubDate>
            <atom:updated>2022-10-31T14:01:13.827Z</atom:updated>
            <content:encoded><![CDATA[<h4>Você já usou Context Extensions ou conhecia essa maneira de trabalhar com elas?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3RZITHHWH7Zz6PRPSvoW-Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RdaOndmN9C_z52aqhl3blA.png" /><figcaption>Isso representa muito o uso dessa extension que você verá no artigo! 😂</figcaption></figure><h3>Introdução</h3><p>Muitos devs buscam ter uma <strong>maior produtividade</strong> durante o tempo de desenvolvimento, e buscar trazer atalhos é sempre muito útil. Quando se trabalha em um grande projeto então, nem se fala. Quanto mais recursos e funcionalidades houverem, sabendo medir o ponto e os requisitos do projeto, melhor.</p><p>E com uso de <strong>extensions, não é diferente</strong>. Pois elas podem ajudar bastante, tornando o uso dos nossos objetos mais poderosos.</p><p>Então vamos a alguns casos de uso e exemplos práticos.</p><h3>Exemplos</h3><p>Você certamente já fez algo do tipo:</p><pre>Container(<br>  width: MediaQuery.of(context).size.width,<br>  height: MediaQuery.of(context).size.height,<br>  color: Colors.blue,<br>),</pre><p>Mas, para ficar um pouco mais limpo, criou uma variável e a utilizou.</p><pre>Widget build(BuildContext context) {<br>  final size = MediaQuery.of(context).size;</pre><pre>Container(<br>  width: size.width,<br>  height: size.height,<br>  color: Colors.blue,<br>),</pre><blockquote>Isso é muito bom, pois de certa forma traz maior clareza, além de tornar o seu código mais fácil e consiso de se ler.</blockquote><p><strong>Mas você pode ir além, utilizando extensions para isso.</strong></p><p>No caso, criar uma extension:</p><pre>import &#39;package:flutter/material.dart&#39;;</pre><pre>extension MediaQueryExt on BuildContext {<br>  double get height =&gt; MediaQuery.of(this).size.height;<br>  double get width =&gt; MediaQuery.of(this).size.width;<br>}</pre><p>E usar na aplicação — precisando somente fazer o import. <br>Usando, dessa maneira:</p><pre>import &#39;package:context_ext/extensions/context_extension.dart&#39;;</pre><pre>Container(<br>  width: context.width,<br>  height: context.height,<br>  color: Colors.blue,<br>),</pre><blockquote>Aqui, você está usando o <em>context</em> para utilizar os dois objetos criados (ou melhor, extendidos do BuildContext). <br> — Além disso, lembre-se de sempre fazer o import.</blockquote><h4>Essa técnica, não tão conhecida é realmente muito útil.</h4><p>Isso é só um pequeno exemplo, mas já imaginou utilizar <strong>extensions com várias outras implementações no <em>context</em></strong>? Isso é possível!<br>Se liga em alguns exemplos abaixo!</p><h3>Indo ao próximo nível</h3><p>Agora é hora de vermos ainda mais formas de implementá-las. <br><strong>Confira a seguir:</strong></p><h4>- Navigator</h4><ul><li>Antes</li></ul><pre>onPressed: () =&gt; Navigator.of(context).pushNamed(‘/’),</pre><ul><li>Depois</li></ul><p>— Você cria a extension</p><pre>extension NavigatorExt on BuildContext {<br>  Future&lt;T?&gt; pushNamed&lt;T&gt;(String routeName, {Object? arguments}) =&gt;<br>    Navigator.pushNamed&lt;T?&gt;(this, routeName, arguments: arguments);<br>}</pre><p>— E utiliza</p><pre>onPressed: () =&gt; context.pushNamed(&#39;/&#39;),</pre><h4>- Theme</h4><ul><li>Antes</li></ul><pre>style: Theme.of(context).textTheme.headline5,</pre><ul><li>Depois</li></ul><p>— Você cria a extension</p><pre>extension ThemeExt on BuildContext {<br>  TextTheme get textTheme =&gt; Theme.of(this).textTheme;<br>}</pre><p>— E utiliza</p><pre>style: context.textTheme.headline5,</pre><h4>- Scaffold</h4><ul><li>Antes</li></ul><pre>onPressed: () =&gt; Scaffold.of(context).openDrawer(),</pre><ul><li>Depois</li></ul><p>— Você cria a extension</p><pre>extension ScaffoldExt on BuildContext {<br>  void openDrawer() =&gt; Scaffold.of(this).openDrawer();<br>}</pre><p>— E utiliza</p><pre>onPressed: () =&gt; context.openDrawer(),</pre><h4>- FocusScope</h4><ul><li>Antes</li></ul><pre>onPressed: () =&gt;<br>    FocusScope.of(context).requestFocus(specificFocusNode);</pre><ul><li>Depois</li></ul><p>— Você cria a extension</p><pre>extension FocusScopeExt on BuildContext {<br>  FocusScopeContext get focusScope =&gt; FocusScopeContext(this);<br>}</pre><p>— E utiliza</p><pre>onPressed: () =&gt; context.focusScope.requestFocus(specificFocusNode);</pre><p>💡 Sobre as extensions</p><p>Nos casos acima, estamos dando o foco nas possibilidades com o BuildContext. Mas é importante lembrar que é possível criar extensions para qualquer tipo em Dart. Para mais informações, <a href="https://dart.dev/guides/language/extension-methods">leia mais aqui</a>.</p><p>Veja o exemplo abaixo, onde criamos criando uma extesion de int e utilizando no <strong>Duration</strong>:</p><h4>- <strong>Duration</strong></h4><ul><li>Antes</li></ul><pre>InkWell(<br>  onTap: () =&gt; Future.delayed(<br>    const Duration(milliseconds: 16),<br>    () =&gt; ...<br>  ),<br>  child: Text(&#39;&#39;),<br>),</pre><p>— Você cria a extension</p><pre>extension IntSC on int {<br>  Duration get milliseconds {<br>    return Duration(milliseconds: this);<br>  }<br>}</pre><p>— E utiliza</p><pre>InkWell(<br>  onTap: () =&gt; Future.delayed(<br>    16.milliseconds,<br>    () =&gt; ...<br>  ),<br>  child: Text(&#39;&#39;),<br>),</pre><h3>Utilizando e turbinando suas extensions</h3><p>Muito massa esse recurso né? E olha que <strong>você só experimentou uma parte</strong>.</p><p>Agora pra turbinar ainda mais, você pode dar uma olhada no projeto abaixo com várias <strong>context extensions</strong> para aplicar nos seus projetos — que estão no arquivo context_extension. <br>E assim, entender ainda melhor o funcionamento e criação na prática.</p><p><a href="https://github.com/felipecastrosales/context_extension">GitHub - felipecastrosales/context_extension</a></p><p>Hoje há no <a href="http://pub.dev/">pub.dev</a> o pacote <a href="https://pub.dev/packages/build_context">build_context</a>, que traz alguns desses exemplos, mas você pode facilmente exportar o arquivo context_extension do projeto acima - <strong>que inclusive há alguns incrementos</strong> -, copiar para o seu projeto e usá-lo. Pois concorda comigo que é mais fácil e simples você fazer isso (copiá-lo para o seu projeto), do que depender de um package para isso?</p><p>Além disso, arquiteturalmente, eu sugeriria para que você adicione em uma estrutura parecida com a abaixo:</p><pre>├── 📦 lib<br>│ ├─ 📂 commons<br>│ │ ├─ 📂 extensions<br>│ │ │ ├─ 📜 context_extension.dart</pre><blockquote>Dessa forma, você adiciona uma camada que pode ser compartilhada nas demais features e implementações do seu projeto.</blockquote><p>Mas claro, você pode adaptar com base nas suas necessidades do seu projeto e à arquitetura que o mesmo segue hoje. <br> — Afinal, uma única e simples feature não precisa mudar a forma com que você trabalha hoje no seu projeto.</p><p><strong>Lembrando que quaisquer sugestões para incrementar são e serão super bem vindas. Além de possíveis adaptações também.</strong></p><h3>Considerações Finais</h3><p><strong>E aí, curtiram conhecer esse recurso? Aposto que sim!</strong></p><p>Se tiverem alguma dúvida ou feedback a respeito do conteúdo, pode mandar nos comentários.</p><p>Além disso, se esse artigo te ajudou de alguma forma, dá o 👏 para fortalecer e garantir que esse conteúdo chegará em mais pessoas.</p><blockquote><strong><em>Valeu e vamos pra cima, em busca do próximo nível! 🏆</em></strong></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4cf4512d3db0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/suamusicatech/context-extension-4cf4512d3db0">Context Extension</a> was originally published in <a href="https://medium.com/suamusicatech">suamusicatech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Criando Federated Plugins]]></title>
            <link>https://medium.com/suamusicatech/criando-federated-plugins-17cd1daada28?source=rss----6eb20003fe19---4</link>
            <guid isPermaLink="false">https://medium.com/p/17cd1daada28</guid>
            <category><![CDATA[federated-plugin]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[plugins]]></category>
            <dc:creator><![CDATA[Maria Clara Almeida Souza]]></dc:creator>
            <pubDate>Mon, 08 Aug 2022 19:48:49 GMT</pubDate>
            <atom:updated>2022-08-24T15:18:08.837Z</atom:updated>
            <content:encoded><![CDATA[<p>Atualmente o formato padrão indicado para criar um novo plugin é o Federated Plugin, (em português Plugins federados), é uma maneira de dividir o suporte para diferentes plataformas em pacotes separados.</p><p>Um Plugin Federado requer a seguinte estrutura:</p><p><strong>1- app-facing package(interface da plataforma e especificidades da mesma):</strong></p><p>O pacote do qual os usuários do plugin dependem para usar o plugin.</p><p><strong>2- platform package(s) — especificações da plataforma</strong></p><p>Um ou mais pacotes que contêm o código de implementação específico da plataforma.</p><p><strong>3- platform interface package</strong></p><p>Este pacote declara uma interface que qualquer pacote de plataforma deve implementar para dar suporte ao pacote, e não é visível fora da implementação do plugin. Ter um pacote que define a interface garante que os platform packages implementem a mesma funcionalidade.</p><p>O diagrama abaixo, contribui para a visualização da estrutura de um plugin Federado.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iF0_EKx8aq5x5rmknAOlEA.png" /><figcaption>Estrutura Federated Plugin. Fonte: Flutter lessons for federated plugin development.</figcaption></figure><p>Mas qual a importância acerca do Federated Plugin?! Quando queremos estar presente em ’n’ dispositivos, sejam eles, mobile, desktop, telas de TV e todos os lugares em que nossos usuários possam vir a instalar nossa aplicação, desejamos que essa aplicação mantenha seu funcionamento independente da plataforma, com a necessidade de evitar distorções, fica evidente a importância do Federated Plugin, além disso, essa abordagem permite que um especialista estenda um plug-in existente para funcionar na plataforma que ele conhece melhor.</p><h3>Exemplo</h3><p>Para o nosso exemplo, um simples plugin que para a leitura do nível da bateria que irá funcionar tanto para o sistema operacional Android como para o iOS, para isso, no local em que o plugin será desenvolvido é necessário:</p><p>1- Crie e implemente o pacote:</p><pre>flutter create — template=package battery</pre><p>2- Platform Interface</p><pre>flutter create -t package battery_platform_interface</pre><p>3- Android:</p><pre>flutter create --template=plugin --platforms=android -a kotlin battery_android</pre><p>4- iOS</p><pre>flutter create --template=plugin --platforms=ios -i swift battery_ios</pre><p>Obtendo a seguinte estrutura:</p><pre>📦battery<br> ┣ 📂battery<br> ┣ 📂battery_android<br> ┣ 📂battery_ios<br> ┣ 📂battery_platform_interface<br> </pre><p>De forma mais detalhada como ficará a interface para as plataformas:</p><pre>📦battery_platform_interface<br> ┣ 📂lib<br> ┃ ┣ 📂src<br> ┃ ┃ ┣ 📂chanel_methods<br> ┃ ┃ ┃ ┗ 📜battery_method_channel.dart<br> ┃ ┃ ┗ 📜battery_platform_interface.dart<br> ┃ ┗ 📜battery_platform_interface.dart<br> ┣</pre><p><strong>battery_platform_interface:</strong></p><p>Neste packge é adicionado o <strong>plugin_platform_interface </strong>seu papel é fornecer uma classe base para interfaces de plataforma de plugins de flutter federados.</p><p>Então a classe <strong>BatteryPlatform</strong> herda os recursos da <strong>PlatformInterface</strong>, como podemos ver abaixo.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%3Fbg%3Drgba%2528171%252C%2B184%252C%2B195%252C%2B1%2529%26t%3Dseti%26wt%3Dnone%26l%3Ddart%26width%3D680%26ds%3Dtrue%26dsyoff%3D0px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D6px%26ph%3D2px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D11px%26lh%3D133%2525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Dabstract%252520class%252520BatteryPlatform%252520extends%252520PlatformInterface%252520%25257B%25250A%252520%252520%25252F%25252F%25252F%252520Constructs%252520a%252520BatteryAndroidPlatform.%25250A%252520%252520BatteryPlatform%2528%2529%252520%25253A%252520super%2528token%25253A%252520_token%2529%25253B%25250A%25250A%252520%252520static%252520final%252520Object%252520_token%252520%25253D%252520Object%2528%2529%25253B%25250A%25250A%252520%252520static%252520BatteryPlatform%252520_instance%252520%25253D%252520MethodChannelBattery%2528%2529%25253B%25250A%25250A%252520%252520%25252F%25252F%25252F%252520The%252520default%252520instance%252520of%252520%25255BBatteryPlatform%25255D%252520to%252520use.%25250A%252520%252520%25252F%25252F%25252F%25250A%252520%252520%25252F%25252F%25252F%252520Defaults%252520to%252520%25255BMethodChannelBattery%25255D.%25250A%252520%252520static%252520BatteryPlatform%252520get%252520instance%252520%25253D%25253E%252520_instance%25253B%25250A%25250A%252520%252520%25252F%25252F%25252F%252520Platform-specific%252520implementations%252520should%252520set%252520this%252520with%252520their%252520own%25250A%252520%252520%25252F%25252F%25252F%252520platform-specific%252520class%252520that%252520extends%252520%25255BBatteryPlatform%25255D%252520when%25250A%252520%252520%25252F%25252F%25252F%252520they%252520register%252520themselves.%25250A%252520%252520static%252520set%252520instance%2528BatteryPlatform%252520instance%2529%252520%25257B%25250A%252520%252520%252520%252520PlatformInterface.verifyToken%2528instance%25252C%252520_token%2529%25253B%25250A%252520%252520%252520%252520_instance%252520%25253D%252520instance%25253B%25250A%252520%252520%25257D%25250A%25250A%252520%252520Future%25253Cint%25253F%25253E%252520getBatteryLevel%2528%2529%252520%25257B%25250A%252520%252520%252520%252520throw%252520UnimplementedError%2528%2527getBatteryLevel%2528%2529%252520has%252520not%252520been%252520implemented.%2527%2529%25253B%25250A%252520%252520%25257D%25250A%25257D%25250A%25250A%25250A%25250A%25250A%25250A%25250A%25250A%25250A%25250A%25250A%25250A%25250A&amp;display_name=Carbon&amp;url=https%3A%2F%2Fcarbon.now.sh%2F%3Fbg%3Drgba%252528171%25252C%2B184%25252C%2B195%25252C%2B1%252529%26t%3Dseti%26wt%3Dnone%26l%3Ddart%26width%3D680%26ds%3Dtrue%26dsyoff%3D0px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D6px%26ph%3D2px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D11px%26lh%3D133%252525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Dabstract%25252520class%25252520BatteryPlatform%25252520extends%25252520PlatformInterface%25252520%2525257B%2525250A%25252520%25252520%2525252F%2525252F%2525252F%25252520Constructs%25252520a%25252520BatteryAndroidPlatform.%2525250A%25252520%25252520BatteryPlatform%252528%252529%25252520%2525253A%25252520super%252528token%2525253A%25252520_token%252529%2525253B%2525250A%2525250A%25252520%25252520static%25252520final%25252520Object%25252520_token%25252520%2525253D%25252520Object%252528%252529%2525253B%2525250A%2525250A%25252520%25252520static%25252520BatteryPlatform%25252520_instance%25252520%2525253D%25252520MethodChannelBattery%252528%252529%2525253B%2525250A%2525250A%25252520%25252520%2525252F%2525252F%2525252F%25252520The%25252520default%25252520instance%25252520of%25252520%2525255BBatteryPlatform%2525255D%25252520to%25252520use.%2525250A%25252520%25252520%2525252F%2525252F%2525252F%2525250A%25252520%25252520%2525252F%2525252F%2525252F%25252520Defaults%25252520to%25252520%2525255BMethodChannelBattery%2525255D.%2525250A%25252520%25252520static%25252520BatteryPlatform%25252520get%25252520instance%25252520%2525253D%2525253E%25252520_instance%2525253B%2525250A%2525250A%25252520%25252520%2525252F%2525252F%2525252F%25252520Platform-specific%25252520implementations%25252520should%25252520set%25252520this%25252520with%25252520their%25252520own%2525250A%25252520%25252520%2525252F%2525252F%2525252F%25252520platform-specific%25252520class%25252520that%25252520extends%25252520%2525255BBatteryPlatform%2525255D%25252520when%2525250A%25252520%25252520%2525252F%2525252F%2525252F%25252520they%25252520register%25252520themselves.%2525250A%25252520%25252520static%25252520set%25252520instance%252528BatteryPlatform%25252520instance%252529%25252520%2525257B%2525250A%25252520%25252520%25252520%25252520PlatformInterface.verifyToken%252528instance%2525252C%25252520_token%252529%2525253B%2525250A%25252520%25252520%25252520%25252520_instance%25252520%2525253D%25252520instance%2525253B%2525250A%25252520%25252520%2525257D%2525250A%2525250A%25252520%25252520Future%2525253Cint%2525253F%2525253E%25252520getBatteryLevel%252528%252529%25252520%2525257B%2525250A%25252520%25252520%25252520%25252520throw%25252520UnimplementedError%252528%252527getBatteryLevel%252528%252529%25252520has%25252520not%25252520been%25252520implemented.%252527%252529%2525253B%2525250A%25252520%25252520%2525257D%2525250A%2525257D%2525250A%2525250A%2525250A%2525250A%2525250A%2525250A%2525250A%2525250A%2525250A%2525250A%2525250A%2525250A%2525250A&amp;image=https%3A%2F%2Fcarbon.now.sh%2Fstatic%2Fbrand%2Fbanner.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=carbon" width="1024" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/731aff2dcb0ef7dccdc45c0d435ce310/href">https://medium.com/media/731aff2dcb0ef7dccdc45c0d435ce310/href</a></iframe><p>Esta classe abstrata (BatteryPlatform) servirá de base para as implementações de cada plataforma, sendo suas funções as ações que o plugin deverá executar em cada uma.</p><p><strong>battery_method_channel:</strong></p><p><strong>MethodChannelBattery</strong> herda <strong>BatteryPlatform</strong> e implementa suas funções através do <strong>MethodChanel</strong> invocado. Resumindo, é onde é colocado o nome do channel que será utilizado para a troca de mensagens com o nativo e o resultado esperado, como podemos ver abaixo.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%3Fbg%3Drgba%2528171%252C%2B184%252C%2B195%252C%2B1%2529%26t%3Dseti%26wt%3Dnone%26l%3Ddart%26width%3D680%26ds%3Dtrue%26dsyoff%3D0px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D6px%26ph%3D2px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D11px%26lh%3D133%2525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3D%25252F%25252F%25252F%252520An%252520implementation%252520of%252520%25255BBatteryPlatform%25255D%252520that%252520uses%252520method%252520channels.%25250Aclass%252520MethodChannelBattery%252520extends%252520BatteryPlatform%252520%25257B%25250A%252520%252520%25252F%25252F%25252F%252520The%252520method%252520channel%252520used%252520to%252520interact%252520with%252520the%252520native%252520platform.%25250A%252520%252520%252540visibleForTesting%25250A%252520%252520final%252520methodChannel%252520%25253D%25250A%252520%252520%252520%252520%252520%252520const%252520MethodChannel%2528%2527plugins.federatedpluginexample%25252Fbattery%2527%2529%25253B%25250A%25250A%252520%252520%252540override%25250A%252520%252520Future%25253Cint%25253F%25253E%252520getBatteryLevel%2528%2529%252520async%252520%25257B%25250A%252520%252520%252520%252520final%252520battery%252520%25253D%252520await%252520methodChannel.invokeMethod%2528%2527getBatteryLevel%2527%2529%25253B%25250A%252520%252520%252520%252520return%252520battery%25253B%25250A%252520%252520%25257D%25250A%25257D%25250A%25250A%25250A%25250A%25250A%25250A%25250A&amp;display_name=Carbon&amp;url=https%3A%2F%2Fcarbon.now.sh%2F%3Fbg%3Drgba%252528171%25252C%2B184%25252C%2B195%25252C%2B1%252529%26t%3Dseti%26wt%3Dnone%26l%3Ddart%26width%3D680%26ds%3Dtrue%26dsyoff%3D0px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D6px%26ph%3D2px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D11px%26lh%3D133%252525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3D%2525252F%2525252F%2525252F%25252520An%25252520implementation%25252520of%25252520%2525255BBatteryPlatform%2525255D%25252520that%25252520uses%25252520method%25252520channels.%2525250Aclass%25252520MethodChannelBattery%25252520extends%25252520BatteryPlatform%25252520%2525257B%2525250A%25252520%25252520%2525252F%2525252F%2525252F%25252520The%25252520method%25252520channel%25252520used%25252520to%25252520interact%25252520with%25252520the%25252520native%25252520platform.%2525250A%25252520%25252520%25252540visibleForTesting%2525250A%25252520%25252520final%25252520methodChannel%25252520%2525253D%2525250A%25252520%25252520%25252520%25252520%25252520%25252520const%25252520MethodChannel%252528%252527plugins.federatedpluginexample%2525252Fbattery%252527%252529%2525253B%2525250A%2525250A%25252520%25252520%25252540override%2525250A%25252520%25252520Future%2525253Cint%2525253F%2525253E%25252520getBatteryLevel%252528%252529%25252520async%25252520%2525257B%2525250A%25252520%25252520%25252520%25252520final%25252520battery%25252520%2525253D%25252520await%25252520methodChannel.invokeMethod%252528%252527getBatteryLevel%252527%252529%2525253B%2525250A%25252520%25252520%25252520%25252520return%25252520battery%2525253B%2525250A%25252520%25252520%2525257D%2525250A%2525257D%2525250A%2525250A%2525250A%2525250A%2525250A%2525250A%2525250A&amp;image=https%3A%2F%2Fcarbon.now.sh%2Fstatic%2Fbrand%2Fbanner.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=carbon" width="1024" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/24f24ea849588b6785524f2dd428f08d/href">https://medium.com/media/24f24ea849588b6785524f2dd428f08d/href</a></iframe><p>Toda a plataforma criada precisa adicionar como dependência a interface criada acima, para que seus comportamentos sejam similares idependente da plataforma, como podemos ver abaixo para android (demais plataformas são feitas de forma análoga):</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%3Fbg%3Drgba%2528171%252C%2B184%252C%2B195%252C%2B1%2529%26t%3Dseti%26wt%3Dnone%26l%3Dyaml%26width%3D680%26ds%3Dtrue%26dsyoff%3D0px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D6px%26ph%3D2px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D11px%26lh%3D133%2525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Dname%25253A%252520battery_android%25250Adescription%25253A%252520A%252520new%252520Flutter%252520plugin%252520project.%25250Aversion%25253A%2525200.0.1%25250Ahomepage%25253A%25250Apublish_to%25253A%252520none%25250A%25250Aenvironment%25253A%25250A%252520%252520sdk%25253A%252520%252522%25253E%25253D2.17.6%252520%25253C3.0.0%252522%25250A%252520%252520flutter%25253A%252520%252522%25253E%25253D2.5.0%252522%25250A%25250Adependencies%25253A%25250A%252520%252520flutter%25253A%25250A%252520%252520%252520%252520sdk%25253A%252520flutter%25250A%25250A%252520%252520battery_platform_interface%25253A%25250A%252520%252520%252520%252520path%25253A%252520..%25252Fbattery_platform_interface%25250A%25250A%25250Adev_dependencies%25253A%25250A%252520%252520flutter_test%25253A%25250A%252520%252520%252520%252520sdk%25253A%252520flutter%25250A%252520%252520flutter_lints%25253A%252520%25255E2.0.0%25250A%252520%252520plugin_platform_interface%25253A%252520%25255E2.0.2%25250A%25250Aflutter%25253A%25250A%25250A%252520%252520plugin%25253A%25250A%252520%252520%252520%252520platforms%25253A%25250A%252520%252520%252520%252520%252520%252520android%25253A%25250A%252520%252520%252520%252520%252520%252520%252520%252520package%25253A%252520com.example.battery_android%25250A%252520%252520%252520%252520%252520%252520%252520%252520pluginClass%25253A%252520BatteryAndroidPlugin%25250A%25250A%25250A%25250A%25250A%25250A&amp;display_name=Carbon&amp;url=https%3A%2F%2Fcarbon.now.sh%2F%3Fbg%3Drgba%252528171%25252C%2B184%25252C%2B195%25252C%2B1%252529%26t%3Dseti%26wt%3Dnone%26l%3Dyaml%26width%3D680%26ds%3Dtrue%26dsyoff%3D0px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D6px%26ph%3D2px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D11px%26lh%3D133%252525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Dname%2525253A%25252520battery_android%2525250Adescription%2525253A%25252520A%25252520new%25252520Flutter%25252520plugin%25252520project.%2525250Aversion%2525253A%252525200.0.1%2525250Ahomepage%2525253A%2525250Apublish_to%2525253A%25252520none%2525250A%2525250Aenvironment%2525253A%2525250A%25252520%25252520sdk%2525253A%25252520%25252522%2525253E%2525253D2.17.6%25252520%2525253C3.0.0%25252522%2525250A%25252520%25252520flutter%2525253A%25252520%25252522%2525253E%2525253D2.5.0%25252522%2525250A%2525250Adependencies%2525253A%2525250A%25252520%25252520flutter%2525253A%2525250A%25252520%25252520%25252520%25252520sdk%2525253A%25252520flutter%2525250A%2525250A%25252520%25252520battery_platform_interface%2525253A%2525250A%25252520%25252520%25252520%25252520path%2525253A%25252520..%2525252Fbattery_platform_interface%2525250A%2525250A%2525250Adev_dependencies%2525253A%2525250A%25252520%25252520flutter_test%2525253A%2525250A%25252520%25252520%25252520%25252520sdk%2525253A%25252520flutter%2525250A%25252520%25252520flutter_lints%2525253A%25252520%2525255E2.0.0%2525250A%25252520%25252520plugin_platform_interface%2525253A%25252520%2525255E2.0.2%2525250A%2525250Aflutter%2525253A%2525250A%2525250A%25252520%25252520plugin%2525253A%2525250A%25252520%25252520%25252520%25252520platforms%2525253A%2525250A%25252520%25252520%25252520%25252520%25252520%25252520android%2525253A%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520package%2525253A%25252520com.example.battery_android%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520pluginClass%2525253A%25252520BatteryAndroidPlugin%2525250A%2525250A%2525250A%2525250A%2525250A%2525250A&amp;image=https%3A%2F%2Fcarbon.now.sh%2Fstatic%2Fbrand%2Fbanner.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=carbon" width="1024" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/3e9255e10f4c707f43ad037c26426ce5/href">https://medium.com/media/3e9255e10f4c707f43ad037c26426ce5/href</a></iframe><p><strong>battery_android:</strong></p><p>Aqui a plataforma é implementada, neste caso, o Android. O MethodChanel precisa ser igual para todas as plataformas.</p><p>Esta classe irá se registrar através da função <strong>registerWith</strong> e implentar os métodos da interface.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%3Fbg%3Drgba%2528171%252C%2B184%252C%2B195%252C%2B1%2529%26t%3Dseti%26wt%3Dnone%26l%3Ddart%26width%3D680%26ds%3Dtrue%26dsyoff%3D0px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D6px%26ph%3D2px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D11px%26lh%3D133%2525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Dconst%252520MethodChannel%252520_channel%252520%25253D%25250A%252520%252520%252520%252520MethodChannel%2528%2527plugins.federatedpluginexample%25252Fbattery%2527%2529%25253B%25250A%25250A%25252F%25252F%25252F%252520An%252520implementation%252520of%252520%25255BBatteryPlatform%25255D%252520for%252520Android.%25250Aclass%252520BatteryAndroid%252520extends%252520BatteryPlatform%252520%25257B%25250A%252520%252520%25252F%25252F%25252F%252520Registers%252520this%252520class%252520as%252520the%252520default%252520instance%252520of%252520%25255BBatteryPlatform%25255D.%25250A%252520%252520static%252520void%252520registerWith%2528%2529%252520%25257B%25250A%252520%252520%252520%252520BatteryPlatform.instance%252520%25253D%252520BatteryAndroid%2528%2529%25253B%25250A%252520%252520%25257D%25250A%25250A%252520%252520%252540override%25250A%252520%252520Future%25253Cint%25253F%25253E%252520getBatteryLevel%2528%2529%252520async%252520%25257B%25250A%252520%252520%252520%252520try%252520%25257B%25250A%252520%252520%252520%252520%252520%252520final%252520batterylevel%252520%25253D%252520await%252520_channel.invokeMethod%2528%2527getBatteryLevel%2527%2529%25253B%25250A%252520%252520%252520%252520%252520%252520return%252520batterylevel%25253B%25250A%252520%252520%252520%252520%25257D%252520on%252520PlatformException%252520catch%252520%2528e%2529%252520%25257B%25250A%252520%252520%252520%252520%252520%252520debugPrint%2528e.message%2529%25253B%25250A%252520%252520%252520%252520%252520%252520return%252520null%25253B%25250A%252520%252520%252520%252520%25257D%25250A%252520%252520%25257D%25250A%25257D%25250A%25250A%25250A%25250A&amp;display_name=Carbon&amp;url=https%3A%2F%2Fcarbon.now.sh%2F%3Fbg%3Drgba%252528171%25252C%2B184%25252C%2B195%25252C%2B1%252529%26t%3Dseti%26wt%3Dnone%26l%3Ddart%26width%3D680%26ds%3Dtrue%26dsyoff%3D0px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D6px%26ph%3D2px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D11px%26lh%3D133%252525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Dconst%25252520MethodChannel%25252520_channel%25252520%2525253D%2525250A%25252520%25252520%25252520%25252520MethodChannel%252528%252527plugins.federatedpluginexample%2525252Fbattery%252527%252529%2525253B%2525250A%2525250A%2525252F%2525252F%2525252F%25252520An%25252520implementation%25252520of%25252520%2525255BBatteryPlatform%2525255D%25252520for%25252520Android.%2525250Aclass%25252520BatteryAndroid%25252520extends%25252520BatteryPlatform%25252520%2525257B%2525250A%25252520%25252520%2525252F%2525252F%2525252F%25252520Registers%25252520this%25252520class%25252520as%25252520the%25252520default%25252520instance%25252520of%25252520%2525255BBatteryPlatform%2525255D.%2525250A%25252520%25252520static%25252520void%25252520registerWith%252528%252529%25252520%2525257B%2525250A%25252520%25252520%25252520%25252520BatteryPlatform.instance%25252520%2525253D%25252520BatteryAndroid%252528%252529%2525253B%2525250A%25252520%25252520%2525257D%2525250A%2525250A%25252520%25252520%25252540override%2525250A%25252520%25252520Future%2525253Cint%2525253F%2525253E%25252520getBatteryLevel%252528%252529%25252520async%25252520%2525257B%2525250A%25252520%25252520%25252520%25252520try%25252520%2525257B%2525250A%25252520%25252520%25252520%25252520%25252520%25252520final%25252520batterylevel%25252520%2525253D%25252520await%25252520_channel.invokeMethod%252528%252527getBatteryLevel%252527%252529%2525253B%2525250A%25252520%25252520%25252520%25252520%25252520%25252520return%25252520batterylevel%2525253B%2525250A%25252520%25252520%25252520%25252520%2525257D%25252520on%25252520PlatformException%25252520catch%25252520%252528e%252529%25252520%2525257B%2525250A%25252520%25252520%25252520%25252520%25252520%25252520debugPrint%252528e.message%252529%2525253B%2525250A%25252520%25252520%25252520%25252520%25252520%25252520return%25252520null%2525253B%2525250A%25252520%25252520%25252520%25252520%2525257D%2525250A%25252520%25252520%2525257D%2525250A%2525257D%2525250A%2525250A%2525250A%2525250A&amp;image=https%3A%2F%2Fcarbon.now.sh%2Fstatic%2Fbrand%2Fbanner.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=carbon" width="1024" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/bcb7a0a5fd12f08086fa4ce43f7840b8/href">https://medium.com/media/bcb7a0a5fd12f08086fa4ce43f7840b8/href</a></iframe><p>Agora é preciso implementar esse método dentro da plataforma, nesse caso como a plataforma detalhada é Android, será detalhado o arquivo <strong>BatteryAndroidPlugin</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aAMpBaTBKPjuGYqnD-WJCw.png" /></figure><p>Pode-se notar novamente o chanel com o mesmo valor do que foi mostrado anteriormente.</p><p>Na função <strong>onMethodCall</strong> é onde iremos implementar cada método necessário, no nosso caso o método chamado <strong>getBatteryLevel</strong>, que chamará a funcão também chamada <strong>getBatteryLevel</strong> que nos retorna o valor desejado, que é retornado para o código dart através do <strong>result</strong>.</p><p>Esse padrão é seguido para todas as plataformas (iOS, windows…etc).</p><p><strong>battery</strong>:</p><p>o battery representa o plugin como um todo. Podemos ver que nesse caso temos as plataformas Android e iOS implementadas. Caso for necessário implementar para outras plataformas, como o windows, seria necessário criar o plugin <strong>battery_windows</strong> e adicionar no <strong>pubspec</strong> abaixo.</p><p>Ou seja, esse é o arquivo que será lido por uma aplicação como será mostrado mais abaixo.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%3Fbg%3Drgba%2528171%252C%2B184%252C%2B195%252C%2B1%2529%26t%3Dseti%26wt%3Dnone%26l%3Dtext%252Fx-kotlin%26width%3D680%26ds%3Dtrue%26dsyoff%3D0px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D6px%26ph%3D2px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D11px%26lh%3D133%2525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Dname%25253A%252520battery%25250Adescription%25253A%252520A%252520new%252520Flutter%252520package%252520project.%25250Aversion%25253A%2525200.0.1%25250Ahomepage%25253A%25250Apublish_to%25253A%252520%252522none%252522%25250A%25250Aenvironment%25253A%25250A%252520%252520sdk%25253A%252520%252522%25253E%25253D2.17.6%252520%25253C3.0.0%252522%25250A%252520%252520flutter%25253A%252520%252522%25253E%25253D1.17.0%252522%25250A%25250Aflutter%25253A%25250A%252520%252520plugin%25253A%25250A%252520%252520%252520%252520platforms%25253A%25250A%252520%252520%252520%252520%252520%252520android%25253A%25250A%252520%252520%252520%252520%252520%252520%252520%252520default_package%25253A%252520battery_android%25250A%252520%252520%252520%252520%252520%252520ios%25253A%25250A%252520%252520%252520%252520%252520%252520%252520%252520default_package%25253A%252520battery_ios%25250A%25250Adependencies%25253A%25250A%252520%252520flutter%25253A%25250A%252520%252520%252520%252520sdk%25253A%252520flutter%25250A%25250A%252520%252520battery_platform_interface%25253A%25250A%252520%252520%252520%252520path%25253A%252520..%25252Fbattery_platform_interface%25250A%252520%252520battery_android%25253A%25250A%252520%252520%252520%252520path%25253A%252520..%25252Fbattery_android%25250A%252520%252520battery_ios%25253A%25250A%252520%252520%252520%252520path%25253A%252520..%25252Fbattery_ios%25250A%25250A%25250Adev_dependencies%25253A%25250A%252520%252520flutter_test%25253A%25250A%252520%252520%252520%252520sdk%25253A%252520flutter%25250A%252520%252520flutter_lints%25253A%252520%25255E2.0.0%25250A%252520%252520plugin_platform_interface%25253A%252520%25255E2.1.2%25250A%25250A%252520%252520%252520%252520%25250A%25250A&amp;display_name=Carbon&amp;url=https%3A%2F%2Fcarbon.now.sh%2F%3Fbg%3Drgba%252528171%25252C%2B184%25252C%2B195%25252C%2B1%252529%26t%3Dseti%26wt%3Dnone%26l%3Dtext%25252Fx-kotlin%26width%3D680%26ds%3Dtrue%26dsyoff%3D0px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D6px%26ph%3D2px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D11px%26lh%3D133%252525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Dname%2525253A%25252520battery%2525250Adescription%2525253A%25252520A%25252520new%25252520Flutter%25252520package%25252520project.%2525250Aversion%2525253A%252525200.0.1%2525250Ahomepage%2525253A%2525250Apublish_to%2525253A%25252520%25252522none%25252522%2525250A%2525250Aenvironment%2525253A%2525250A%25252520%25252520sdk%2525253A%25252520%25252522%2525253E%2525253D2.17.6%25252520%2525253C3.0.0%25252522%2525250A%25252520%25252520flutter%2525253A%25252520%25252522%2525253E%2525253D1.17.0%25252522%2525250A%2525250Aflutter%2525253A%2525250A%25252520%25252520plugin%2525253A%2525250A%25252520%25252520%25252520%25252520platforms%2525253A%2525250A%25252520%25252520%25252520%25252520%25252520%25252520android%2525253A%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520default_package%2525253A%25252520battery_android%2525250A%25252520%25252520%25252520%25252520%25252520%25252520ios%2525253A%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520default_package%2525253A%25252520battery_ios%2525250A%2525250Adependencies%2525253A%2525250A%25252520%25252520flutter%2525253A%2525250A%25252520%25252520%25252520%25252520sdk%2525253A%25252520flutter%2525250A%2525250A%25252520%25252520battery_platform_interface%2525253A%2525250A%25252520%25252520%25252520%25252520path%2525253A%25252520..%2525252Fbattery_platform_interface%2525250A%25252520%25252520battery_android%2525253A%2525250A%25252520%25252520%25252520%25252520path%2525253A%25252520..%2525252Fbattery_android%2525250A%25252520%25252520battery_ios%2525253A%2525250A%25252520%25252520%25252520%25252520path%2525253A%25252520..%2525252Fbattery_ios%2525250A%2525250A%2525250Adev_dependencies%2525253A%2525250A%25252520%25252520flutter_test%2525253A%2525250A%25252520%25252520%25252520%25252520sdk%2525253A%25252520flutter%2525250A%25252520%25252520flutter_lints%2525253A%25252520%2525255E2.0.0%2525250A%25252520%25252520plugin_platform_interface%2525253A%25252520%2525255E2.1.2%2525250A%2525250A%25252520%25252520%25252520%25252520%2525250A%2525250A&amp;image=https%3A%2F%2Fcarbon.now.sh%2Fstatic%2Fbrand%2Fbanner.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=carbon" width="1024" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/150c91dd196c1acd1f0b67823adcba77/href">https://medium.com/media/150c91dd196c1acd1f0b67823adcba77/href</a></iframe><p>Essa é, nesse caso, a única classe que fica visível para o uso das aplicações, então basicamente, o app vai através de suas funções para retornar o recurso desejado e disponível.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%3Fbg%3Drgba%2528171%252C%2B184%252C%2B195%252C%2B1%2529%26t%3Dseti%26wt%3Dnone%26l%3Ddart%26width%3D680%26ds%3Dtrue%26dsyoff%3D0px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D6px%26ph%3D2px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D11px%26lh%3D133%2525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3D%25250Aclass%252520Battery%252520%25257B%25250A%252520%252520static%252520Future%25253Cint%25253F%25253E%252520getBatteryLevel%2528%2529%252520%25253D%25253E%25250A%252520%252520%252520%252520%252520%252520BatteryPlatform.instance.getBatteryLevel%2528%2529%25253B%25250A%25257D%25250A%25250A%25250A%252520%252520%252520%252520%25250A%25250A&amp;display_name=Carbon&amp;url=https%3A%2F%2Fcarbon.now.sh%2F%3Fbg%3Drgba%252528171%25252C%2B184%25252C%2B195%25252C%2B1%252529%26t%3Dseti%26wt%3Dnone%26l%3Ddart%26width%3D680%26ds%3Dtrue%26dsyoff%3D0px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D6px%26ph%3D2px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D11px%26lh%3D133%252525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3D%2525250Aclass%25252520Battery%25252520%2525257B%2525250A%25252520%25252520static%25252520Future%2525253Cint%2525253F%2525253E%25252520getBatteryLevel%252528%252529%25252520%2525253D%2525253E%2525250A%25252520%25252520%25252520%25252520%25252520%25252520BatteryPlatform.instance.getBatteryLevel%252528%252529%2525253B%2525250A%2525257D%2525250A%2525250A%2525250A%25252520%25252520%25252520%25252520%2525250A%2525250A&amp;image=https%3A%2F%2Fcarbon.now.sh%2Fstatic%2Fbrand%2Fbanner.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=carbon" width="1024" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/807f3d770478dd874abfa61936c6fd97/href">https://medium.com/media/807f3d770478dd874abfa61936c6fd97/href</a></iframe><p><strong>example</strong>:</p><p>Em nosso projeto exemplo do plugin, pode-se observar que apenas foi adicionado a dependência <strong>battery</strong>, que é o que o código Flutter precisa ter acesso.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%3Fbg%3Drgba%2528171%252C%2B184%252C%2B195%252C%2B1%2529%26t%3Dseti%26wt%3Dnone%26l%3Dyaml%26width%3D680%26ds%3Dtrue%26dsyoff%3D0px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D6px%26ph%3D2px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D11px%26lh%3D133%2525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Dname%25253A%252520example%25250Adescription%25253A%252520A%252520new%252520Flutter%252520project.%25250A%25250Apublish_to%25253A%252520%252522none%252522%252520%252523%252520Remove%252520this%252520line%252520if%252520you%252520wish%252520to%252520publish%252520to%252520pub.dev%25250A%25250Aversion%25253A%2525201.0.0%25252B1%25250A%25250Aenvironment%25253A%25250A%252520%252520sdk%25253A%252520%252522%25253E%25253D2.17.6%252520%25253C3.0.0%252522%25250A%25250Adependencies%25253A%25250A%252520%252520flutter%25253A%25250A%252520%252520%252520%252520sdk%25253A%252520flutter%25250A%252520%252520battery%25253A%25250A%252520%252520%252520%252520path%25253A%252520..%25252F%25250A%25250A%252520%252520cupertino_icons%25253A%252520%25255E1.0.2%25250A%25250Adev_dependencies%25253A%25250A%252520%252520flutter_test%25253A%25250A%252520%252520%252520%252520sdk%25253A%252520flutter%25250A%25250A&amp;display_name=Carbon&amp;url=https%3A%2F%2Fcarbon.now.sh%2F%3Fbg%3Drgba%252528171%25252C%2B184%25252C%2B195%25252C%2B1%252529%26t%3Dseti%26wt%3Dnone%26l%3Dyaml%26width%3D680%26ds%3Dtrue%26dsyoff%3D0px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D6px%26ph%3D2px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D11px%26lh%3D133%252525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Dname%2525253A%25252520example%2525250Adescription%2525253A%25252520A%25252520new%25252520Flutter%25252520project.%2525250A%2525250Apublish_to%2525253A%25252520%25252522none%25252522%25252520%25252523%25252520Remove%25252520this%25252520line%25252520if%25252520you%25252520wish%25252520to%25252520publish%25252520to%25252520pub.dev%2525250A%2525250Aversion%2525253A%252525201.0.0%2525252B1%2525250A%2525250Aenvironment%2525253A%2525250A%25252520%25252520sdk%2525253A%25252520%25252522%2525253E%2525253D2.17.6%25252520%2525253C3.0.0%25252522%2525250A%2525250Adependencies%2525253A%2525250A%25252520%25252520flutter%2525253A%2525250A%25252520%25252520%25252520%25252520sdk%2525253A%25252520flutter%2525250A%25252520%25252520battery%2525253A%2525250A%25252520%25252520%25252520%25252520path%2525253A%25252520..%2525252F%2525250A%2525250A%25252520%25252520cupertino_icons%2525253A%25252520%2525255E1.0.2%2525250A%2525250Adev_dependencies%2525253A%2525250A%25252520%25252520flutter_test%2525253A%2525250A%25252520%25252520%25252520%25252520sdk%2525253A%25252520flutter%2525250A%2525250A&amp;image=https%3A%2F%2Fcarbon.now.sh%2Fstatic%2Fbrand%2Fbanner.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=carbon" width="1024" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/7e66487155ad467cab9e8bf732a51b87/href">https://medium.com/media/7e66487155ad467cab9e8bf732a51b87/href</a></iframe><p><strong>main</strong>:</p><p>Olhando para a função <strong>initBattery</strong> é possível ver como a aplicação utiliza o recurso do plugin de forma simples.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*e9tH4NrIxiY3mmfZkb4Qdw.png" /></figure><p>Resultado:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*MNWLPgYI7B0sv7qn4j1NxA.jpeg" /></figure><p><strong>Conclusão</strong></p><p>Esta estrutura permite que a partir da necessidade sejam adicionadas suporte a novas plataformas ao plugin, de uma forma menos acoplada, possibilitando um melhor trabalho compartilhado, e claro, obedecendo as regras da interface.</p><p>Segue o github do código mostrado acima: <a href="https://github.com/Claraalmeida09/battery">https://github.com/Claraalmeida09/battery</a></p><p>Para mais informações:</p><p><a href="https://docs.flutter.dev/development/packages-and-plugins/developing-packages">Developing packages &amp; plugins</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FGAnSNplNpCA%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DGAnSNplNpCA&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FGAnSNplNpCA%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/c13c0c76889dc37b8dd7362c313b6093/href">https://medium.com/media/c13c0c76889dc37b8dd7362c313b6093/href</a></iframe><p>Encontrou algum erro no artigo ou tem alguma dúvida? Comenta aí!</p><p>@<a href="#">suamusicatech</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=17cd1daada28" width="1" height="1" alt=""><hr><p><a href="https://medium.com/suamusicatech/criando-federated-plugins-17cd1daada28">Criando Federated Plugins</a> was originally published in <a href="https://medium.com/suamusicatech">suamusicatech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Classificando áudios com I.A. em seu app Flutter (TensorFlow e Teachable Machine)]]></title>
            <link>https://medium.com/suamusicatech/classificando-%C3%A1udios-com-i-a-em-seu-app-flutter-tensorflow-e-teachable-machine-9bee97cfd16e?source=rss----6eb20003fe19---4</link>
            <guid isPermaLink="false">https://medium.com/p/9bee97cfd16e</guid>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[audio]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Gustavo Duregger]]></dc:creator>
            <pubDate>Fri, 04 Mar 2022 19:34:51 GMT</pubDate>
            <atom:updated>2022-03-06T16:34:44.021Z</atom:updated>
            <content:encoded><![CDATA[<h4>Utilizando Aprendizado de Máquina para distinguir músicas de podcasts</h4><h4>O que faremos</h4><p>Construir modelos assertivos de Machine Learning pode ser algo bastante complexo para iniciantes e até para aqueles que já mexeram com sistemas baseados em I.A. Motivado nessa premissa, a ferramenta <strong>Teachable Machine</strong> foi criada para <strong>elaborar esses modelos de uma forma bastante didática e rápida</strong>, abstraindo muitos passos que você faria se construísse a I.A. de um jeito mais tradicional. No fim a ferramenta nos dará um <strong>arquivo gerado do TensorFlow prontinho para gente implementar no Flutter</strong> e é isso que faremos hoje nesse artigo.</p><p>O Projeto que a gente irá criar aqui tem o objetivo de classificar se um áudio é uma música ou uma fala de uma pessoa, como por exemplo em um podcast.</p><h4>Sobre o tutorial</h4><p>Nesse artigo, quero te mostrar como criei um classificador de músicas e podcasts no Flutter e o potencial do TensorFlow em fazer isto. Talvez esse artigo possa te ajudar a criar um classificador entre diferentes tipos de áudios (e não somente entre as classes aqui abordadas), se esse é seu objetivo, acredito que esse artigo será bastante útil para você. 😁</p><p>Abaixo você encontra o repositório GitHub com tudo que será feito aqui.</p><p><a href="https://github.com/GustavoDuregger/flutter_tensorflow_audio_image">GitHub - GustavoDuregger/flutter_tensorflow_audio_image: Classificação de imagens e áudios no flutter utilizando TensorFlow</a></p><p>Nesse tutorial eu suponho que você já esteja familiarizado com o básico do Flutter, coisas como criar um projeto, configurar permissões, trabalhar com pacotes externos e construir telas simples.</p><p><strong>No final teremos algo parecido com isso</strong></p><ol><li>Um botão que grava o áudio do microfone do dispositivo</li><li>Cards apresentando o resultado da classificação do áudio pelo TensorFlow</li></ol><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FHvnFLDYkE7meY4DP4J%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FHvnFLDYkE7meY4DP4J%2Fgiphy-downsized.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FHvnFLDYkE7meY4DP4J%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="424" frameborder="0" scrolling="no"><a href="https://medium.com/media/4a701ce07a3cf1696a8f8ca3f61dddc4/href">https://medium.com/media/4a701ce07a3cf1696a8f8ca3f61dddc4/href</a></iframe><h4>O que é o TensorFlow e o Teachable Machine</h4><p><strong>TensorFlow</strong> é uma biblioteca para <strong>construção de modelos baseados em Machine Learning</strong>, com ele você consegue criar e treinar redes neurais artificiais para encontrar padrões e correlações em objetos (imagens, números, sons, etc). O <strong>Teachable Machine</strong> é uma ferramenta que <strong>abstrai essa criação e treinamento de modelos</strong>, tornando isso muito mais rápido e fácil de se fazer.</p><p>Se você não faz idéia de como funciona esses modelos, recomendo a leitura do artigo <a href="https://medium.com/@randylaosat/a-beginners-guide-to-machine-learning-dfadc19f6caf"><strong>&quot;A Beginner’s Guide to Machine Learning&quot;</strong></a> do Randy Lao, onde ele explica de uma forma bem didática como funciona, mas apesar de ser algo legal de saber, esse conhecimento <strong>não é um pré-requisito</strong> para a construção do nosso projeto aqui, pois como mencionei, o Teachable Machine abstrai muito desses processos para gente.</p><h4>Criando Modelo no Teachable Machine</h4><p>Colocado as expectativas e as tecnologias na mesa, é hora da gente por mão na massa!. Vamos começar <strong>criando nosso modelo</strong> no <a href="https://teachablemachine.withgoogle.com/train">Teachable Machine</a>. Entrando na plataforma você poderá escolher entre três tipos de projetos, você conseguirá classificar imagens, áudios ou poses. Aqui a gente irá escolher um projeto de áudio, mas o processo de ensinar a máquina é bem parecido nos três.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JYduvLak3bT9tH8B" /><figcaption>Figura 2. Página de criação de projeto do Teachable Machine.</figcaption></figure><p>Inclusive caso queira explorar os outros modelos de projeto do Teachable Machine, no repositório que disponibilizei no GitHub, você irá encontrar tanto a implementação da classificação de áudio quanto uma implementação de classificação de imagens.</p><p>Ao selecionar um projeto de áudio, você cairá nessa tela (Figura 3), aqui é onde a mágica acontece. Na primeira etapa você criará as classes na qual você quer classificar, ou seja, se você quer distinguir, na sua classificação, um miado de um gato e um latido de cachorro por exemplo, você pode criar uma classe chamada miado (onde está Class 2) e uma outra classe chamada latido.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*udoFn9bkFvPRbwCRhWuwwQ.png" /><figcaption>Figura 3. Página de criação de modelo no Teachable Machine</figcaption></figure><p>No nosso caso a ideia é classificar músicas e podcasts, então irei criar uma classe chamada <strong>Music</strong> e outra chamada <strong>Speech</strong>. Perceba que temos uma classe padrão na ferramenta chamada <strong>Background Noise</strong>, nela a gente vai alimentar com áudios de ruído (ambiente), assim nosso modelo não irá se confundir quando algum tipo de ruído estiver em uma das nossas classes.</p><p>Criada as classes, chegou a hora de alimenta-las com muitos dados, isto é, na classe de músicas enviar vários <em>samples </em>de músicas e na classe de podcast enviar vários <em>samples </em>de podcasts.</p><p>Uma limitação que encontrei neste momento foi o fato de eu não conseguir fazer um upload de um arquivo MP3 nas classes, o que dificultou bastante a criação do <em>dataset</em>, pois desta forma, precisei <strong>regravar cada sample pelo microfone</strong> do Teachable Machine para que o arquivo fosse compatível com a plataforma. Essa limitação teve um impacto real no desenvolvimento visto que, não seria tão viável criar um <em>dataset</em> com muitos exemplos para serem treinados, impactando no resultado da aplicação.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*7IvHDDEzidFR2VEu" /><figcaption>Figura 4. Erro apresentado pela ferramenta ao tentar enviar arquivos MP3.</figcaption></figure><p>Quando criei o <strong>modelo de imagens</strong> eu não tive esse tipo de limitação, o que facilitou bastante, pois bastou baixar um <em>dataset</em> pronto no <a href="https://www.kaggle.com/datasets">Kaggle</a> e enviar para cada uma das classes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Jmr3UYNL8ErBn8Ee" /><figcaption>Figura 5. Classes de objeto alimentadas e modelo treinado.</figcaption></figure><p>Depois de enviar todos os áudios, chegou a hora de treinar nosso modelo, aqui eu posso determinar quantas <em>Epochs</em> eu quero fazer para treinar meu modelo, esse número irá determinar quantas vezes o algoritmo de aprendizado vai rodar em todo conjunto de dados.</p><p>Por baixo dos panos, basicamente a ferramenta está <strong>procurando padrões e semelhanças nos áudios</strong> que a gente enviou para ela, dessa forma, nosso modelo está aprendendo o que é uma música e o que é um podcast.</p><p>Um erro que cometi aqui é achar que quanto mais e<em>pochs </em>tiver no nosso modelo, melhor treinado ele será e, consequentemente, teremos uma melhor acurácia.</p><p>De fato, quanto mais e<em>pochs </em>você rodar, melhor seu modelo irá predizer e classificar um novo objeto. Mas um ponto muito importante é que essa melhora <strong>não é linear,</strong> geralmente o maior <strong>aprendizado ocorre nas primeiras épocas</strong> e esse aprendizado vai decaindo conforme o tempo passa, ou seja, se você utilizar um número muito alto de épocas, você acabará <strong>desperdiçando tempo e processamento.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/501/1*VnMPeODdvDh5ksFnvwhifg.png" /><figcaption>Figura 6. Gráfico da acurácia em relação as épocas.</figcaption></figure><p>Veja no gráfico que depois que o algoritmo rodou mais de 80 épocas, ele não aprendeu mais nada nas épocas seguintes. Acredito que um bom número no nosso caso de uso seria 50, onde teríamos praticamente os mesmos resultados com a melhor otimização entre tempo e processamento.</p><p>Modelo treinado, agora é só exportar. Na aba preview, além de você conseguir já testar seu modelo para ver se está tudo ok, você consegue exportar o modelo em um arquivo TensorFlow Lite.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/0*82NW-wFDPr1gjyZf" /><figcaption>Figura 7. Exportando modelo do Teachable Machine.</figcaption></figure><p>Você terá duas opções, a nossa é o TensorFlow Lite, no qual usaremos para aplicá-lo ao Flutter, portanto, basta selecionar e clicar em “<em>download my model</em>”, a ferramenta irá nos gerar um arquivo zip com dois arquivos, uma com as <em>labels</em> das nossas classes e outra que é nosso modelo de fato (.tflite).</p><h4>Implementação no Flutter</h4><p>Legal, com o modelo em mãos, temos tudo para começar a classificar nossas classes no Flutter. O primeiro passo é criar um projeto e uma pasta na mesma altura da <strong>lib</strong> chamada de <strong><em>assets</em></strong>. Aqui eu coloquei os arquivos gerados pelo Teachable Machine dentro de uma pasta chamada <strong><em>audio</em></strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/311/0*nVdb0AWmqWmd0Itq" /><figcaption>Figura 8. Pasta assets no projeto.</figcaption></figure><p>Além disso precisamos adicionar a rota desses arquivos e adicionar nossas dependências no projeto. Para isso, a gente vai até o arquivo <strong>pubspec.yaml</strong> e colocamos o pacote <strong>tflite_audio: ^0.2.2+4</strong>, além disso, vamos aproveitar para já colocar as rotas dos arquivos.</p><pre>dependencies:<em><br>  </em>tflite_audio: ^0.2.2+4<br><br>flutter:<br>  assets:<br>    - assets/audio/labels.txt<br>    - assets/audio/soundclassifier_with_metadata.tflite</pre><p>Para instalar o pacote basta escrever o comando no terminal.</p><pre>flutter pub get</pre><p>Além disso precisaremos configurar algumas coisas nos arquivos nativos do Android para que tudo ocorra como estamos esperando. Primeiro temos que adicionar as permissões necessárias. Então você vai até o <strong>AndroidManifest.xml</strong> e adiciona as seguintes permissões.</p><pre>&lt;uses-permission android:name=&quot;android.permission.INTERNET&quot;/&gt;<br>&lt;uses-permission android:name=&quot;android.permission.RECORD_AUDIO&quot; /&gt;<br>&lt;uses-permission android:name=&quot;android.permission.WRITE_EXTERNAL_STORAGE&quot; /&gt;</pre><p>O próximo passo é adicionar o <strong>tflite no aaptOtions</strong>, você irá encontrar ele em android/app/build.gradle</p><pre>android {</pre><pre> aaptOptions <strong>{<br>    </strong>noCompress &#39;tflite&#39;<br>    noCompress &#39;lite&#39;<br> <strong>}<br> </strong>lintOptions <strong>{<br>    </strong>disable &#39;InvalidPackage&#39;<br> <strong>}</strong></pre><pre>}</pre><p>Ainda no <strong>build.gradle,</strong> precisamos mudar o <strong>targetSdkVersion</strong> e o <strong>compileSdkVersion</strong> para 31. Alterei também o <strong>minSdkVersion</strong> para 21. E ativei o <strong>select-ops</strong> nas dependências.</p><pre>dependencies {<br>implementation &quot;org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version&quot;<br>implementation &quot;org.tensorflow:tensorflow-lite-select-tf-ops:+&quot;<br>}</pre><p>E é isso ai, se alguma coisa falhar nessa parte, recomendo você dar uma olhada na documentação do pacote do tflite_auldio (<a href="https://pub.dev/packages/tflite_audio">https://pub.dev/packages/tflite_audio</a>), lá tem uma seção que entra em mais detalhes de como configurar essa parte, ou se preferir, pode ver meus arquivos no GitHub, são eles o <a href="https://github.com/GustavoDuregger/flutter_tensorflow_audio_image/blob/main/android/app/src/debug/AndroidManifest.xml">AndroidManifest (debug)</a>, <a href="https://github.com/GustavoDuregger/flutter_tensorflow_audio_image/blob/main/android/app/src/profile/AndroidManifest.xml">AndroidManifest (profile)</a> e o <a href="https://github.com/GustavoDuregger/flutter_tensorflow_audio_image/blob/main/android/app/build.gradle">build.gradle</a>.</p><p>Projeto configurado agora começa a parte legal, vamos implementar de fato nosso modelo. Gosto de começar já <strong>estruturando todo o meu projeto</strong>, mas se preferir ir construindo ele no passo a passo fica a seu critério.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/275/0*EujLBJiBhvV07H0k" /><figcaption>Figura 9. Estrutura de arquivos e pastas do projeto.</figcaption></figure><p>Eu separei desta forma, mas você pode fazer da maneira que for mais adequado ao seu contexto. Na pasta <strong><em>common</em></strong> eu colocarei os <strong><em>widgets</em></strong> que serão compartilhados entre as <strong><em>features</em></strong>, fiz desta maneira logo que estarei fazendo tanto a classificação por áudio quanto a de imagem, ou seja, <em>features</em> diferentes,<strong> mas se este não for seu caso, você pode alocar tudo isso dentro da sua <em>feature</em></strong>, que no meu caso é a <strong>audio.mic</strong>. Dentro da minha feature de reconhecimento de áudio eu terei uma camada <strong><em>presentation</em></strong> onde estará a <strong>pagina</strong> e os <strong><em>widgets</em></strong>.</p><p>Agora vou construir os <strong><em>widgets</em></strong> que irão compor nossa tela, eles serão três, como mostro na imagem abaixo.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/428/0*LalM1vVBsK4S6AsX" /><figcaption>Figura 10. Composição da tela.</figcaption></figure><p>Primeiro vamos começar pelo <strong>inference_time</strong>, ele vai ser responsável por nos informar o tempo de inferência que está ocorrendo no momento da gravação do áudio, ele pode ajudar você a calibrar melhor a sua detecção, falarei sobre isso logo mais.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cc315cfe19dd4e1bc4190968da38ccd7/href">https://medium.com/media/cc315cfe19dd4e1bc4190968da38ccd7/href</a></iframe><p>Agora o <strong>card_detector</strong>, ele vai ser responsável por mostrar a <strong><em>label</em></strong> em que esta sendo reconhecido.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ec8ee80f975e3df28feb41db01aa4eae/href">https://medium.com/media/ec8ee80f975e3df28feb41db01aa4eae/href</a></iframe><p>Para construir a lista de cards com as <em>labels</em>, precisamos criar o <strong>label_list</strong>, que vai passar os objetos para o card_detector e construir o que vimos na tela anteriormente.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/455f8e90693b696fd1bb1a836b599c2a/href">https://medium.com/media/455f8e90693b696fd1bb1a836b599c2a/href</a></iframe><p>Perceba que ele faz uma verificação no nome da <em>label</em> para apresentar de uma forma mais bonita para o usuário.</p><p>Componentes criados, hora de juntar tudo e fazer nossa página. Criei um pagina chamada <strong>AudioMicPage</strong> (StatefulWidget) e nela irei criar um Scaffold, onde será construído um StreamBuilder, que vai receber os eventos do usuário e se comunicar com o tflite_audio.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6c5ff9d299d38fdd96610b811de833d3/href">https://medium.com/media/6c5ff9d299d38fdd96610b811de833d3/href</a></iframe><p>Perceba que nossa tela está chamando métodos que ainda não existem, como o <strong>getResult</strong> no FloatActionButton, o que a gente vai fazer agora é criar esses métodos que serão responsáveis de fato em gravar o áudio e se comunicar com o tflite_audio para assim classificar esse áudio. Vamos começar inicializando as variáveis.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/75b2d37dec04b18efabcae0ca4185057/href">https://medium.com/media/75b2d37dec04b18efabcae0ca4185057/href</a></iframe><p>Aqui definimos a <strong>rota</strong> daqueles arquivos que estão nos nossos <em>assets</em> que foram gerados no Teachable Machine e carregamos nosso modelo com o package.</p><p>Agora vamos criar o <strong>getResult</strong>, ele vai chamar o um outro método do <strong>TfliteAudio</strong> que <strong>inicia o reconhecimento de áudio</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b84d193b2f3658a7b60ab4c996db7e87/href">https://medium.com/media/b84d193b2f3658a7b60ab4c996db7e87/href</a></iframe><p>A ideia aqui é você ajustar esse valores até conseguir o melhor resultado da sua classificação. Caso esteja enfrentando dificuldades com sua classificação, tente alterar os valores de:</p><ul><li><strong>numThreads - </strong>Quanto mais threads, menor o tempo de inferência, porém aumenta o uso de CPU.</li><li><strong>detectThreshold - </strong>Útil caso em seu contexto, você capture sons não intencionais, como ruídos externos. Caso o desempenho do modelo estiver indo mal é recomendado diminuir este valor.</li><li><strong>bufferSize</strong> - O Valor desse parâmetro deve ser igual ou inferior à duração da gravação.</li><li><strong>sampleRate - </strong>Uma taxa de amostragem mais alta pode melhorar a precisão. Os valores recomendados são 16000, 22050, 44100.</li></ul><p>Agora vamos fazer o método <strong>fetchLabelList</strong> que será responsável por fazer o <em>match</em> das <em>labels</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f5970bd6a408cebaf21dc91ef02c4282/href">https://medium.com/media/f5970bd6a408cebaf21dc91ef02c4282/href</a></iframe><p>E por fim, um método para mostrar o resultado da classificação.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/df417a101e78a742e74e491702b72d28/href">https://medium.com/media/df417a101e78a742e74e491702b72d28/href</a></iframe><p>Nesse ponto você já deve ter percebido que defini constantes como cores e textos numa camada externa, elas não são necessárias mas deixam o código mais limpo e organizado.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d80cc7cf43db7a7fe99cb36e991a1ee4/href">https://medium.com/media/d80cc7cf43db7a7fe99cb36e991a1ee4/href</a></iframe><p>Depois de juntar tudo, nossa classe referente a página do classificador ficará assim.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ffb2dcaab459635236f87e9080b303b4/href">https://medium.com/media/ffb2dcaab459635236f87e9080b303b4/href</a></iframe><p>Por fim, é chamar a página na <strong>main.</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9a87f8f5a2b8120a63a66668e93cc96b/href">https://medium.com/media/9a87f8f5a2b8120a63a66668e93cc96b/href</a></iframe><p>Agora é testar e correr pro abraço 😁. O Resultado da tela será algo assim:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/362/1*1KLW9Qx2qM57MJz8EUJloQ.png" /><figcaption>Figura 11. Resultado final da aplicação.</figcaption></figure><h4>Considerações finais</h4><p><strong>Por fim conseguimos criar um classificador de músicas e podcasts de uma maneira simples e que nos trouxe resultados bem bacanas.</strong></p><p>Apesar disso o Teachable Machine trouxe algumas limitações em relação ao envio de arquivos para o treinamento do modelo. Inicialmente a ideia era criar um classificador de Gêneros Musicais, que até funcionou bem em alguns casos como ao comparar o Piseiro com Rock, mas que falhou ao comparar, por exemplo, Piseiro e Forró. Acredito que estes problemas ocorreram por dois fatores, uma delas justamente pela impossibilidade de enviar um pacote de arquivos MP3 (o que torna inviável fazer um <em>dataset</em> grande para o aprendizado) e pelo fato da própria abstração criada pelo Teachable Machine, logo que não é possível ajustar parâmetros mais específicos do nosso contexto, algo que seria trivial se estivéssemos criando um modelo diretamente no TensorFlow.</p><p>Todavia as ferramentas apresentadas mostrou um enorme potencial tendo em vista a tamanha facilidade e velocidade em criar os modelos, principalmente quando aplicamos em outros tipos de projetos disponíveis no Teachable Machine, como o de reconhecimento de imagens, que não possui a limitação de upload apresentada ou em arquivos de áudios mais simples.</p><p>E ai gostaram? se tiverem alguma dúvida, se esse artigo te ajudou de alguma forma ou se apenas quiser dar um feedback, pode mandar um comentário aqui. Abaixo estarei colocando algumas referências que me ajudaram a elaborar o artigo, caso queira aprofundar um pouco mais no assunto, pode ser bastante útil para ti. Valeu!</p><h4>Repositório no GitHub</h4><p><a href="https://github.com/GustavoDuregger/flutter_tensorflow_audio_image">GitHub - GustavoDuregger/flutter_tensorflow_audio_image: Classificação de imagens e áudios no flutter utilizando TensorFlow</a></p><h4>Referências</h4><p>Pub.dev — <a href="https://pub.dev/packages/tflite_audio"><strong>TFlite Audio Plugin for Flutter</strong></a>. (Acesso: 4 de março de 2022).</p><p>Randy Lao — <a href="https://medium.com/@randylaosat/a-beginners-guide-to-machine-learning-dfadc19f6caf"><strong>A Beginner’s Guide to Machine Learning</strong></a>. (Acesso: 4 de março de 2022).</p><p>Teachable Machine —<a href="https://teachablemachine.withgoogle.com/"><strong> Train a computer to recognize your own images, sounds, &amp; poses.</strong> </a>(Acesso: 4 de março de 2022).</p><p>TensorFlow —<a href="https://www.tensorflow.org/lite/?hl=pt_br"> <strong>Implante modelos de machine learning em dispositivos móveis e Internet das Coisas.</strong></a> (Acesso: 4 de março de 2022).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9bee97cfd16e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/suamusicatech/classificando-%C3%A1udios-com-i-a-em-seu-app-flutter-tensorflow-e-teachable-machine-9bee97cfd16e">Classificando áudios com I.A. em seu app Flutter (TensorFlow e Teachable Machine)</a> was originally published in <a href="https://medium.com/suamusicatech">suamusicatech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Teste de unidade no Flutter usando o Mocktail]]></title>
            <link>https://medium.com/suamusicatech/teste-de-unidade-no-flutter-usando-o-mocktail-86e1fd1a891d?source=rss----6eb20003fe19---4</link>
            <guid isPermaLink="false">https://medium.com/p/86e1fd1a891d</guid>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[mockito]]></category>
            <category><![CDATA[test]]></category>
            <category><![CDATA[mocktail]]></category>
            <dc:creator><![CDATA[Arthur Monteiro Alves Melo]]></dc:creator>
            <pubDate>Mon, 07 Feb 2022 20:36:23 GMT</pubDate>
            <atom:updated>2022-02-07T20:36:23.512Z</atom:updated>
            <content:encoded><![CDATA[<p>Pré-requisitos:</p><ul><li>Saber o básico de Flutter;</li><li>Noções básicas de testes unitários (Mock, Stub &amp; etc);</li></ul><h3>Visão geral do Mocktail</h3><p><a href="https://pub.dev/packages/mocktail">Mocktail</a> é uma biblioteca em feita em dart inspirada no <a href="https://pub.dev/packages/mockito">Mockito</a>. Seu foco principal é prover uma API simples para a criação de mocks em Dart (com null-safety) sem a necessidade de mocks manuais ou geração de código.</p><p>Então, se ele é inspirado no Mockito, por qual razão não utilizá-lo?</p><p>Se formos na página principal do Mockito, teremos a seguinte informação:</p><blockquote>Mockito 5.0.0 supports Dart’s new null safety language feature in Dart 2.12, primarily with code generation.</blockquote><blockquote>To use Mockito’s generated mock classes, add a build_runner dependency in your package&#39;s pubspec.yaml file, under dev_dependencies; something like build_runner: ^1.11.0.</blockquote><p>Ou seja, para usar o Mockito com o null-safety ativado precisamos ou gerar os códigos, ou fazer isso manualmente.</p><p>Considerando que sempre vamos gerar os códigos (ninguém merece fazer manualmente), isso pode causar alguns incômodos ao longo do tempo, como por exemplo:</p><ul><li>Quando você tem muitos testes com mocks, toda vez que você atualizar algo você tera que rodar o <a href="https://pub.dev/packages/build_runner">build_runner</a> e assim ele atualizará muitos arquivos e acaba assustando o seu time na hora de fazer aquele Code Review;</li><li>No meu time, já tivemos problemas, como <a href="https://github.com/felangel/bloc/issues/2803">este</a>, com o código gerado do Mockito, então comentamos alguns trechos para o CI não reclamar como paleativo.</li></ul><blockquote><strong>Opinião</strong>:</blockquote><blockquote>Mockito é tão bom quanto, mas o Mocktail gera menos código e é mais fácil de usar. Uma evolução do Mockito para o Flutter/Dart null safety.</blockquote><h3>Hands On!</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Fc5eqVJN7oNLTq%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2Fc5eqVJN7oNLTq%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2Fc5eqVJN7oNLTq%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="337" frameborder="0" scrolling="no"><a href="https://medium.com/media/146496118efc6926736a40773133002a/href">https://medium.com/media/146496118efc6926736a40773133002a/href</a></iframe><p>Para demonstrar o uso do mocktail, temos um projeto que utiliza a api <a href="https://viacep.com.br/">ViaCep</a>, um <a href="https://pt.wikipedia.org/wiki/Web_service">webservice</a> gratuito e de alto desempenho para consultar Códigos de Endereçamento Postal (CEP) do Brasil.</p><blockquote>Obs: Como o foco desse artigo é o Mocktail, não entrarei em mais detalhes de arquitetura ou boas práticas usadas no projeto. Vamos apenas ver o mocktail em ação!</blockquote><p>No projeto temos uma feature chamada Address, que é onde nos vamos testar a chamada da API. Resumidamente nós enviamos um CEP e a API retorna mais informações sobre ele. Em caso de erro, ela retorna 400 (Bad Request).</p><p><strong>Link do repositório: </strong><a href="https://github.com/4rthurmonteiro/cep_tdd"><strong>https://github.com/4rthurmonteiro/cep_tdd</strong></a></p><p>Primeiro passo temos que fazer é sempre adicionar o mocktail no <strong><em>pubspec.yaml</em></strong>:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%3Fbg%3Drgba%2528171%252C%2B184%252C%2B195%252C%2B1%2529%26t%3Dseti%26wt%3Dnone%26l%3Dauto%26width%3D680%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%2525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Dname%25253A%252520cep_tdd%25250Adescription%25253A%252520A%252520new%252520Flutter%252520project.%25250Apublish_to%25253A%252520%2527none%2527%25250A%25250Aversion%25253A%2525201.0.0%25252B1%25250A%25250Aenvironment%25253A%25250A%252520%252520sdk%25253A%252520%252522%25253E%25253D2.15.1%252520%25253C3.0.0%252522%25250A%25250Adependencies%25253A%25250A%252520%252520dartz%25253A%252520%25255E0.10.1%25250A%252520%252520dio%25253A%252520%25255E4.0.4%25250A%252520%252520equatable%25253A%252520%25255E2.0.3%25250A%252520%252520flutter%25253A%25250A%252520%252520%252520%252520sdk%25253A%252520flutter%25250A%252520%252520json_annotation%25253A%252520%25255E4.4.0%25250A%252520%252520json_serializable%25253A%252520%25255E6.1.3%25250A%252520%252520cupertino_icons%25253A%252520%25255E1.0.2%25250A%25250Adev_dependencies%25253A%25250A%252520%252520build_runner%25253A%252520%25255E2.1.7%25250A%252520%252520flutter_test%25253A%25250A%252520%252520%252520%252520sdk%25253A%252520flutter%25250A%252520%252520mocktail%25253A%252520%25255E0.2.0%252520%252520%25250A%252520%252520flutter_lints%25253A%252520%25255E1.0.0%25250A%25250Aflutter%25253A%25250A%25250A%252520%252520uses-material-design%25253A%252520true%25250A&amp;display_name=Carbon&amp;url=https%3A%2F%2Fcarbon.now.sh%2F%3Fbg%3Drgba%252528171%25252C%2B184%25252C%2B195%25252C%2B1%252529%26t%3Dseti%26wt%3Dnone%26l%3Dauto%26width%3D680%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%252525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Dname%2525253A%25252520cep_tdd%2525250Adescription%2525253A%25252520A%25252520new%25252520Flutter%25252520project.%2525250Apublish_to%2525253A%25252520%252527none%252527%2525250A%2525250Aversion%2525253A%252525201.0.0%2525252B1%2525250A%2525250Aenvironment%2525253A%2525250A%25252520%25252520sdk%2525253A%25252520%25252522%2525253E%2525253D2.15.1%25252520%2525253C3.0.0%25252522%2525250A%2525250Adependencies%2525253A%2525250A%25252520%25252520dartz%2525253A%25252520%2525255E0.10.1%2525250A%25252520%25252520dio%2525253A%25252520%2525255E4.0.4%2525250A%25252520%25252520equatable%2525253A%25252520%2525255E2.0.3%2525250A%25252520%25252520flutter%2525253A%2525250A%25252520%25252520%25252520%25252520sdk%2525253A%25252520flutter%2525250A%25252520%25252520json_annotation%2525253A%25252520%2525255E4.4.0%2525250A%25252520%25252520json_serializable%2525253A%25252520%2525255E6.1.3%2525250A%25252520%25252520cupertino_icons%2525253A%25252520%2525255E1.0.2%2525250A%2525250Adev_dependencies%2525253A%2525250A%25252520%25252520build_runner%2525253A%25252520%2525255E2.1.7%2525250A%25252520%25252520flutter_test%2525253A%2525250A%25252520%25252520%25252520%25252520sdk%2525253A%25252520flutter%2525250A%25252520%25252520mocktail%2525253A%25252520%2525255E0.2.0%25252520%25252520%2525250A%25252520%25252520flutter_lints%2525253A%25252520%2525255E1.0.0%2525250A%2525250Aflutter%2525253A%2525250A%2525250A%25252520%25252520uses-material-design%2525253A%25252520true%2525250A&amp;image=https%3A%2F%2Fcarbon.now.sh%2Fstatic%2Fbrand%2Fbanner.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=carbon" width="1024" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/1316e836a26bf3f5f73fbe2962f5368d/href">https://medium.com/media/1316e836a26bf3f5f73fbe2962f5368d/href</a></iframe><p>O segundo passo é criar um arquivo na pasta <strong><em>test</em></strong>, de preferência com o mesmo caminho do arquivo original, chamado <strong><em>address_remote_datasource_test.dart</em></strong>. É neste arquivo onde vamos usar o mocktail para mockar nossas dependências.</p><p>Se formos olhar o arquivo original <strong><em>address_remote_datasource.dart</em></strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A73cxrg8HgCJ91cVJRCudg.png" /><figcaption>address_remote_datasource.dart</figcaption></figure><p>Conseguimos reparar que essa classe precisa da injeção do <a href="https://pub.dev/packages/dio"><strong><em>Dio</em></strong></a>, um cliente http para o dart. Sendo assim será esse cara que vamos precisar mockar em nosso teste. Por fim, temos uma função assíncrona que recebe um cep e retorna ou AddressModel, ou uma exception.</p><p>Então quando formos criar o arquivo de teste, a primeira parte será criar a classe de mock:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%3Fbg%3Drgba%2528171%252C%2B184%252C%2B195%252C%2B1%2529%26t%3Dseti%26wt%3Dnone%26l%3Ddart%26width%3D680%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%2525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Dclass%252520MockDio%252520extends%252520Mock%252520implements%252520Dio%252520%25257B%25257D&amp;display_name=Carbon&amp;url=https%3A%2F%2Fcarbon.now.sh%2F%3Fbg%3Drgba%252528171%25252C%2B184%25252C%2B195%25252C%2B1%252529%26t%3Dseti%26wt%3Dnone%26l%3Ddart%26width%3D680%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%252525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Dclass%25252520MockDio%25252520extends%25252520Mock%25252520implements%25252520Dio%25252520%2525257B%2525257D&amp;image=https%3A%2F%2Fcarbon.now.sh%2Fstatic%2Fbrand%2Fbanner.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=carbon" width="1024" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/e36d32ec1c1a15aad4616a2ab5088673/href">https://medium.com/media/e36d32ec1c1a15aad4616a2ab5088673/href</a></iframe><p>Para criá-la ela precisa herdar a classe <strong><em>Mock</em></strong> do mocktail e implementar a nossa dependência alvo, que nesse caso é o <strong><em>Dio</em></strong>. O nome pode ser qualquer um, mas um padrão é sempre colocar o Mock no começo e repetir o nome da classe original no final.</p><p>Após criada a classe, vamos instância-la dentro do teste e chamá-la na classe de <strong><em>AddressRemoteDataSourceImpl</em></strong> :</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%3Fbg%3Drgba%2528171%252C%2B184%252C%2B195%252C%2B1%2529%26t%3Dseti%26wt%3Dnone%26l%3Ddart%26width%3D680%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%2525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Dvoid%252520main%2528%2529%252520%25257B%25250A%252520%252520late%252520AddressRemoteDataSource%252520addressRemoteDataSource%25253B%25250A%252520%252520late%252520MockDio%252520mockDio%25253B%25250A%252520%252520setUp%2528%25250A%252520%252520%252520%252520%2528%2529%252520%25257B%25250A%252520%252520%252520%252520%252520%252520mockDio%252520%25253D%252520MockDio%2528%2529%25253B%25250A%252520%252520%252520%252520%252520%252520addressRemoteDataSource%252520%25253D%252520AddressRemoteDataSourceImpl%2528%25250A%252520%252520%252520%252520%252520%252520%252520%252520httpClient%25253A%252520mockDio%25252C%25250A%252520%252520%252520%252520%252520%252520%2529%25253B%25250A%252520%252520%252520%252520%25257D%25252C%25250A%252520%252520%2529%25253B%25250A%25257D&amp;display_name=Carbon&amp;url=https%3A%2F%2Fcarbon.now.sh%2F%3Fbg%3Drgba%252528171%25252C%2B184%25252C%2B195%25252C%2B1%252529%26t%3Dseti%26wt%3Dnone%26l%3Ddart%26width%3D680%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%252525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Dvoid%25252520main%252528%252529%25252520%2525257B%2525250A%25252520%25252520late%25252520AddressRemoteDataSource%25252520addressRemoteDataSource%2525253B%2525250A%25252520%25252520late%25252520MockDio%25252520mockDio%2525253B%2525250A%25252520%25252520setUp%252528%2525250A%25252520%25252520%25252520%25252520%252528%252529%25252520%2525257B%2525250A%25252520%25252520%25252520%25252520%25252520%25252520mockDio%25252520%2525253D%25252520MockDio%252528%252529%2525253B%2525250A%25252520%25252520%25252520%25252520%25252520%25252520addressRemoteDataSource%25252520%2525253D%25252520AddressRemoteDataSourceImpl%252528%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520httpClient%2525253A%25252520mockDio%2525252C%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%252529%2525253B%2525250A%25252520%25252520%25252520%25252520%2525257D%2525252C%2525250A%25252520%25252520%252529%2525253B%2525250A%2525257D&amp;image=https%3A%2F%2Fcarbon.now.sh%2Fstatic%2Fbrand%2Fbanner.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=carbon" width="1024" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/5832dbaf67e52f4b4ba8ea007f929772/href">https://medium.com/media/5832dbaf67e52f4b4ba8ea007f929772/href</a></iframe><p>Agora vamos testar a função <strong><em>getAddress</em></strong> quando sucesso:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MtCBz21jlPeJSVE4R45dWA.png" /><figcaption>Caso de teste de sucesso.</figcaption></figure><p>Como nossa função original utiliza o <strong><em>get</em></strong> do <strong><em>Dio</em></strong>, nós precisamos fazer o Stub dessa chamada para testarmos ela. Após isso é apenas agir e verificar se tudo ocorreu bem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*3Gce0r7T_uiarWa5PKK9lg.png" /><figcaption>Top!</figcaption></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FpE9cYgVJkAkVinFBz2%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FpE9cYgVJkAkVinFBz2%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FpE9cYgVJkAkVinFBz2%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="543" frameborder="0" scrolling="no"><a href="https://medium.com/media/bf473ac914e1bca03004032667b0278f/href">https://medium.com/media/bf473ac914e1bca03004032667b0278f/href</a></iframe><p>E para testarmos quando houver error:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YOyGTgQMuEIho9r3SOk2ww.png" /><figcaption>Caso de error por bad request.</figcaption></figure><p>Mesma ideia anterior, mas vamos forçar uma exception para cair no erro da função.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/1*vlgQlXOVxImpOAI8l2qAfg.png" /><figcaption>Errado com sucesso :)</figcaption></figure><h3>Conclusão</h3><p>Teste limpo sem necessidade de geração de código para mockar a dependência. Apenas precisamos fazer o stub e correr pro abraço!</p><p>Encontrou algum erro no artigo ou tem alguma dúvida? Comenta aí!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FIhO6ksgdk31JxbbFLA%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FIhO6ksgdk31JxbbFLA%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FIhO6ksgdk31JxbbFLA%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="326" frameborder="0" scrolling="no"><a href="https://medium.com/media/0d40bd431015647aed735aca76f98399/href">https://medium.com/media/0d40bd431015647aed735aca76f98399/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=86e1fd1a891d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/suamusicatech/teste-de-unidade-no-flutter-usando-o-mocktail-86e1fd1a891d">Teste de unidade no Flutter usando o Mocktail</a> was originally published in <a href="https://medium.com/suamusicatech">suamusicatech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>