<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Cassia Barbosa on Medium]]></title>
        <description><![CDATA[Stories by Cassia Barbosa on Medium]]></description>
        <link>https://medium.com/@cassiabarbosa?source=rss-d49bbd1ef374------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*c9Mo2udF-RMqYEPnwueruA.jpeg</url>
            <title>Stories by Cassia Barbosa on Medium</title>
            <link>https://medium.com/@cassiabarbosa?source=rss-d49bbd1ef374------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 02:51:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@cassiabarbosa/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Requests in Flutter]]></title>
            <link>https://medium.com/@cassiabarbosa/requests-in-flutter-984281790865?source=rss-d49bbd1ef374------2</link>
            <guid isPermaLink="false">https://medium.com/p/984281790865</guid>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Cassia Barbosa]]></dc:creator>
            <pubDate>Thu, 11 May 2023 23:31:05 GMT</pubDate>
            <atom:updated>2023-05-11T23:31:05.525Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sGEBI-bkY99Q6oO_" /><figcaption>Photo by <a href="https://unsplash.com/@tonypepe?utm_source=medium&amp;utm_medium=referral">Tony Pepe</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>99,99% of applications needs data, and there is a need to load that data from somewhere. Here in Flutter there is no difference: we need to fetch the data to will be presented. Is this article, we are gonna create a single-view application to show a random user, and learning how to handle with requests in Flutter.</p><h4>1. Creating project</h4><pre>$ flutter create name_of_app</pre><h4>2. Creating Model</h4><p>We are gonna request the data from this url: <a href="https://randomuser.me/api">https://randomuser.me/api</a>/<br>So, if you add it on browser, you&#39;ll see a example of what you&#39;ll receive:</p><pre>{&quot;results&quot;:[{&quot;gender&quot;:&quot;female&quot;,&quot;name&quot;:{&quot;title&quot;:&quot;Mrs&quot;,&quot;first&quot;:&quot;Akshatha&quot;,&quot;last&quot;:&quot;Nayak&quot;},&quot;location&quot;:{&quot;street&quot;:{&quot;number&quot;:2632,&quot;name&quot;:&quot;China Bazaar Rd&quot;},&quot;city&quot;:&quot;Darbhanga&quot;,&quot;state&quot;:&quot;Himachal Pradesh&quot;,&quot;country&quot;:&quot;India&quot;,&quot;postcode&quot;:56063,&quot;coordinates&quot;:{&quot;latitude&quot;:&quot;10.5413&quot;,&quot;longitude&quot;:&quot;157.8801&quot;},&quot;timezone&quot;:{&quot;offset&quot;:&quot;-8:00&quot;,&quot;description&quot;:&quot;Pacific Time (US &amp; Canada)&quot;}},&quot;email&quot;:&quot;akshatha.nayak@example.com&quot;,&quot;login&quot;:{&quot;uuid&quot;:&quot;09824236-87ef-42ab-9564-b2b0ade32215&quot;,&quot;username&quot;:&quot;crazypeacock217&quot;,&quot;password&quot;:&quot;gabriela&quot;,&quot;salt&quot;:&quot;E39kOQLv&quot;,&quot;md5&quot;:&quot;a6a3a9ea2c87a533f2f87e4331453aea&quot;,&quot;sha1&quot;:&quot;354b05652f00f39d8ca9073af714a7b138e5069b&quot;,&quot;sha256&quot;:&quot;0171c3f5e75e87d5663e4429165bda90c337815d52e79ec3515fc295ad59da14&quot;},&quot;dob&quot;:{&quot;date&quot;:&quot;1987-01-23T15:50:09.833Z&quot;,&quot;age&quot;:36},&quot;registered&quot;:{&quot;date&quot;:&quot;2003-03-29T09:45:16.315Z&quot;,&quot;age&quot;:20},&quot;phone&quot;:&quot;9821103209&quot;,&quot;cell&quot;:&quot;7198249861&quot;,&quot;id&quot;:{&quot;name&quot;:&quot;UIDAI&quot;,&quot;value&quot;:&quot;254364009755&quot;},&quot;picture&quot;:{&quot;large&quot;:&quot;https://randomuser.me/api/portraits/women/64.jpg&quot;,&quot;medium&quot;:&quot;https://randomuser.me/api/portraits/med/women/64.jpg&quot;,&quot;thumbnail&quot;:&quot;https://randomuser.me/api/portraits/thumb/women/64.jpg&quot;},&quot;nat&quot;:&quot;IN&quot;}],&quot;info&quot;:{&quot;seed&quot;:&quot;2c00cc8eee3ff3ef&quot;,&quot;results&quot;:1,&quot;page&quot;:1,&quot;version&quot;:&quot;1.4&quot;}}</pre><p>To facilitate the creation of model, copy that and add to an online JSON to Dart converter, like this one: <a href="https://javiercbk.github.io/json_to_dart/">https://javiercbk.github.io/json_to_dart/</a><br>Copy the models and create a dart file on our project called <em>model</em>. Paste the copied content.</p><h4>3. Creating Network helper</h4><p>It&#39;s good to create a primary class to help us to handle with API exceptions and data:</p><pre>import &#39;model.dart&#39;;<br><br>class NetworkingResponse {}<br><br>class NetworkingException extends NetworkingResponse {<br>  String message;<br>  NetworkingException(this.message);<br>}<br><br>class NetworkingResponseData extends NetworkingResponse {<br>  Model apiResponseModel;<br>  NetworkingResponseData(this.apiResponseModel);<br>}</pre><h4>4. Creating Repository</h4><p>It&#39;s where we&#39;re gonna call the API and receive the data.</p><pre>import &#39;dart:ui&#39;;<br>import &#39;networking_response.dart&#39;;<br>import &#39;dart:convert&#39;;<br>import &#39;package:http/http.dart&#39; as http;<br>import &#39;model.dart&#39;;<br><br>class Repository {<br>  Future&lt;NetworkingResponse&gt; getLatestStatsData() {<br>    return _NetworkRepo().getLatestDataFromAPI();<br>  }<br>}<br><br>class _NetworkRepo {<br>  static const String API_END_POINT_URL = &quot;https://randomuser.me/api/&quot;;<br><br>  Future&lt;NetworkingResponse&gt; getLatestDataFromAPI() async {<br>    try {<br>      var response = await http.get(Uri.parse(API_END_POINT_URL));<br>      var parsedJson = await json.decode(response.body);<br>      Model apiResponseModel = Model.fromJson(parsedJson);<br>      return NetworkingResponseData(apiResponseModel);<br>    } catch (exception) {<br>      return NetworkingException(exception.toString());<br>    }<br>  }<br>}</pre><p><a href="https://api.flutter.dev/flutter/dart-async/Future-class.html">Observe we use the </a><a href="https://api.flutter.dev/flutter/dart-async/Future-class.html">Future type to indicate it&#39;s result of an asynchronous computation.</a></p><p>Also, we are calling a private class that will effectively download the data from given url.</p><h4>7. Creating the View Model</h4><p>Taking advantage of <a href="https://medium.com/flutterworld/flutter-mvvm-architecture-f8bed2521958">MWWM</a> pattern, we&#39;ll create a view model that will hold states and it will help to build the view.</p><pre>import &#39;package:flutter/cupertino.dart&#39;;<br>import &#39;/networking_response.dart&#39;;<br>import &#39;repository.dart&#39;;<br>import &#39;model.dart&#39;;<br><br>class HomeScreenViewModel extends ChangeNotifier {<br>  Model? apiResponseModel;<br>  String messageToShow = &quot;&quot;;<br>  bool isLoading = false;<br><br>  HomeScreenViewModel() {<br>    getDataFromAPI();<br>  }<br><br>  void getDataFromAPI() async {<br>    isLoading = true;<br>    notifyListeners();<br><br>    NetworkingResponse networkingResponse = await Repository().getLatestStatsData();<br><br>    if (networkingResponse is NetworkingResponseData) {<br>      apiResponseModel = networkingResponse.apiResponseModel;<br>    } else if (networkingResponse is NetworkingException) {<br>      messageToShow = networkingResponse.message;<br>    }<br><br>    isLoading = false;<br>    notifyListeners();<br>  }<br>}</pre><p>When we call a function withFuturereturn type, we need to call it using async</p><h4>6. Creating Screen</h4><p>Let&#39;s create our the only one screen in the application, which will show us the data. Create a dart file called <em>home_screen_view.dart</em></p><pre>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:networking/model.dart&#39;;<br>import &#39;package:provider_architecture/provider_architecture.dart&#39;;<br>import &#39;home_screen_view_model.dart&#39;;<br><br>class HomeScreen extends StatelessWidget {<br>  @override<br>  Widget build(BuildContext context) {<br>    return ViewModelProvider&lt;HomeScreenViewModel&gt;.withConsumer(<br>        builder: (context, viewModel, child) {<br>          return Container(<br>              color: Colors.white,<br>              child: SafeArea(<br>                  child: Scaffold(<br>                appBar: buildAppBar(),<br>                body: buildBody(viewModel),<br>                floatingActionButton: buildFloatingActionButton(viewModel),<br>              )));<br>        },<br>        viewModelBuilder: () =&gt; HomeScreenViewModel());<br>  }<br><br>  AppBar buildAppBar() {<br>    return AppBar(<br>      title: const Text(&quot;Member&quot;),<br>    );<br>  }<br><br>  Widget buildBody(viewModel) {<br>    return Center(child: buildDataWidget(viewModel));<br>  }<br><br>  FloatingActionButton buildFloatingActionButton(viewModel) {<br>    return FloatingActionButton(<br>      tooltip: &quot;Get Data from API&quot;,<br>      onPressed: () =&gt; viewModel.getDataFromAPI(),<br>      child: viewModel.isLoading<br>          ? const CircularProgressIndicator(<br>              backgroundColor: Colors.white,<br>            )<br>          : const Icon(Icons.cloud_download),<br>    );<br>  }<br><br>  buildDataWidget(viewModel) {<br>    Model? apiResponseModel = viewModel.apiResponseModel;<br><br>    if (apiResponseModel == null) {<br>      return const Padding(<br>        padding: EdgeInsets.all(16.0),<br>        child: Text(<br>          &quot;Loading&quot;,<br>          style: TextStyle(fontSize: 24),<br>          textAlign: TextAlign.center,<br>        ),<br>      );<br>    } else {<br>      return Text(<br>        &quot;Title: ${apiResponseModel.results?[0].name?.title}\n&quot;<br>        &quot;Gender: ${apiResponseModel.results?[0].gender}\n&quot;<br>        &quot;First Name : ${apiResponseModel.results?[0].name?.first}\n&quot;<br>        &quot;Last Name : ${apiResponseModel.results?[0].name?.last}\n&quot;<br>        &quot;Email: ${apiResponseModel.results?[0].email}\n&quot;<br>        &quot;Country: ${apiResponseModel.results?[0].location?.country}\n&quot;<br>        &quot;City: ${apiResponseModel.results?[0].location?.city}\n&quot;<br>        &quot;Street: ${apiResponseModel.results?[0].location?.street?.name}\n&quot;<br>        &quot;Number: ${apiResponseModel.results?[0].location?.street?.number}\n&quot;,<br>        style: const TextStyle(fontSize: 18),<br>      );<br>    }<br>  }<br>}</pre><p>That should be our application:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*-BDDt45zCve2WM4x4Cgneg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=984281790865" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter State Management: Part 3— MobX]]></title>
            <link>https://medium.com/@cassiabarbosa/flutter-state-management-part-3-mobx-c2d6f794f4b2?source=rss-d49bbd1ef374------2</link>
            <guid isPermaLink="false">https://medium.com/p/c2d6f794f4b2</guid>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Cassia Barbosa]]></dc:creator>
            <pubDate>Wed, 15 Mar 2023 15:48:01 GMT</pubDate>
            <atom:updated>2023-03-15T15:49:13.933Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*W86unq45w5IXiK6_" /><figcaption>Photo by <a href="https://unsplash.com/@tonypepe?utm_source=medium&amp;utm_medium=referral">Tony Pepe</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote>MobX is a state-management library that makes it simple to connect the reactive data of your application with the UI. This wiring is completely automatic and feels very natural. As the application-developer, you focus purely on what reactive-data needs to be consumed in the UI (and elsewhere) without worrying about keeping the two in sync.</blockquote><p><a href="https://pub.dev/packages/mobx">mobx | Dart package</a></p><ol><li>Create a new Flutter project with code below:</li></ol><pre>flutter create mobx_example</pre><p>2. In order to have access to MobX, let&#39;s add <strong><em>mobx</em></strong> and<strong> <em>flutter_mobx</em></strong> as dependencies and <strong><em>build_runner</em></strong> and <strong><em>mobx_codegen</em></strong> as dev_dependencies inside .yaml file. The dev_dependencies is to generate files that allows reactiveness on code:</p><pre>dependencies:<br>  flutter:<br>    sdk: flutter<br>  mobx: ^2.1.3<br>  flutter_mobx: ^2.0.6+5<br><br>  # The following adds the Cupertino Icons font to your application.<br>  # Use with the CupertinoIcons class for iOS style icons.<br>  cupertino_icons: ^1.0.2<br><br>dev_dependencies:<br>  flutter_test:<br>    sdk: flutter<br>  build_runner: ^2.3.2<br>  mobx_codegen: ^2.1.1</pre><p>Now, run this code to get dependencies:</p><pre>flutter pub get</pre><p>3. Now, create class where it will contain code to change UI:</p><pre>import &#39;package:mobx/mobx.dart&#39;;<br><br>abstract class _CounterStore with Store {<br>  int count = 0;<br><br>  void increment() {<br>    count++;<br>  }<br>}</pre><p>It&#39;s abstract and private because it&#39;s not a complete class, since depends on other class to effectively works, and, have a <em>mixin</em> from <strong>Store</strong>. With that being said, we can&#39;t instantiate it, we need to create a new one which we can use. <br>So, in the same file, create a <em>CounterStore</em> class that contains the abstract one and a class that have autogenerated reactive code.</p><pre>class CounterStore = _CounterStore with _$CounterStore;</pre><p>4. Now, to really autogenerate the _$ContadorStore, add on same file:</p><pre>part &#39;counter_store.g.dart&#39;;</pre><p>and, run on terminal:</p><pre>flutter pub run build_runner</pre><p>5. Add &quot;<strong><em>@observable</em></strong>&quot; above variable count; and &quot;<strong><em>@action</em></strong>&quot; above function increment</p><pre>import &#39;package:mobx/mobx.dart&#39;;<br>part &#39;counter_store.g.dart&#39;;<br><br>class CounterStore = _CounterStore with _$CounterStore;<br><br>abstract class _CounterStore with Store {<br>  @observable<br>  int count = 0;<br><br>  @action<br>  void increment() {<br>    count++;<br>  }<br>}</pre><p>That change allows out code to be &quot;observed&quot;.</p><p>6. Finally, go to main.dart and wrap the <strong>Text</strong> widget with <strong>Observer</strong> widget, to register it to observable, and pass data from store to text:</p><pre>            Observer(<br>              builder: (_) =&gt; Text(<br>                &#39;${store.count}&#39;,<br>                style: Theme.of(context).textTheme.headlineMedium,<br>              ),<br>            ),</pre><p>If you run your app, you&#39;’ll be able to use increment the button count using MobX :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c2d6f794f4b2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter State Management: Part 2— Provider]]></title>
            <link>https://medium.com/@cassiabarbosa/flutter-state-management-part-2-provider-ad10dcafef13?source=rss-d49bbd1ef374------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad10dcafef13</guid>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Cassia Barbosa]]></dc:creator>
            <pubDate>Mon, 13 Mar 2023 23:35:49 GMT</pubDate>
            <atom:updated>2023-03-15T15:52:18.448Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uDUjpXt7euFK5CqJ" /><figcaption>Photo by <a href="https://unsplash.com/@tonypepe?utm_source=medium&amp;utm_medium=referral">Tony Pepe</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>We have talked about <strong>Inherited Widget </strong>some days ago. Now, I bring to you a very common dependency used to pass data between classes not using constructors: Provider.</p><p>First things first, we are gonna use a previous project where we worked with deep links ok? You can find it here:</p><p><a href="https://medium.com/@cassiabarbosa/getting-started-on-flutter-world-part-5-navigation-bb20da22bf98">Getting Started on Flutter World: Part 5 — Navigation</a></p><ol><li>Create a model called Breed that extends from Change Notifier, that class will hold all data we are gonna use and it will contain a function to toggle if a breed is favorite:</li></ol><pre>import &#39;package:flutter/material.dart&#39;;<br><br>class Breed extends ChangeNotifier {<br>  String name;<br>  String randomImage;<br>  List&lt;String&gt; images;<br>  bool isFavorite = false;<br><br>  Breed({<br>    required this.name,<br>    required this.randomImage,<br>    required this.images<br>  });<br><br>    toogleFavorite() {<br>      isFavorite = !isFavorite;<br>      notifyListeners();<br>    }<br>  }</pre><p>2. Now, create a Provider that extends from Change Notifier too. That class will hold our entire collection:</p><pre>import &#39;package:flutter/material.dart&#39;;<br>import &#39;breed.dart&#39;;<br><br>class CustomProvider extends ChangeNotifier {<br><br>    List&lt;Breed&gt; breeds = [];<br><br>  CustomProvider();<br>}</pre><p>3. Go to main.dart and wrap the apps with ChangeNotifierProvider. It will hold the data on top of widget tree.</p><pre>@override<br>Widget build(BuildContext context) {<br>  if (Platform.isIOS) {<br>    return ChangeNotifierProvider(<br>      create: (context) =&gt; CustomProvider() ,<br>      child: CupertinoApp.router(title: &quot;Breeds&quot;,<br>        routerConfig: _router,<br>      ),<br>    );<br>  } else {<br>    return ChangeNotifierProvider(create: (context) =&gt; CustomProvider(),<br>      child: MaterialApp.router(title: &quot;Breeds&quot;,<br>        routerConfig: _router,<br>      ),<br>    );<br>  }<br>}</pre><p>4. We are gonna change a little our BreedsListViewModel in order to create Breeds instances:</p><pre>import &#39;package:dogs_breeds/models/breed.dart&#39;;<br>import &#39;package:flutter/widgets.dart&#39;;<br><br>import &#39;../../utils/breedys_service.dart&#39;;<br><br>class BreedsListViewModel extends ChangeNotifier {<br>  List&lt;Breed&gt; breeds = [];<br><br>  BreedsListViewModel();<br><br>  void loadData(BuildContext context) async {<br>    var randomImages = [];<br><br>    List&lt;String&gt; newBreeds = await BreedysService.shared.fetchBreeds();<br><br>    for (int breed = 0; breed &lt; newBreeds.length; breed++) {<br>      String newImage = await BreedysService.shared.fetchRandomImages(newBreeds[breed]);<br>      randomImages.add(newImage);<br><br>      List&lt;String&gt; breedImages = await BreedysService.shared.fetchImages(newBreeds[breed]);<br><br>      breeds.add(Breed(name: newBreeds[breed], randomImage: randomImages[breed], images: breedImages));<br>      notifyListeners();<br>    }<br>  }<br>}</pre><p>5. Now, on BreedsListView.dart, let&#39;s return a ChangeNotifierProvider.value that contains BreedItemView(). We are using .value because we already create one of it on main.dart.<br>Note we deleted all parameters on constructor here:</p><pre>  GridView _createGridView(ScrollController controller) {<br>    final provider = Provider.of&lt;CustomProvider&gt;(context);<br>    final List&lt;Breed&gt; breeds = provider.breeds;<br><br>    return GridView.count(<br>      primary: false,<br>      padding: const EdgeInsets.all(10),<br>      crossAxisSpacing: 10,<br>      mainAxisSpacing: 10,<br>      crossAxisCount: 2,<br>      controller: controller,<br>      children: List.generate(breeds.length, (index) {<br>        return ChangeNotifierProvider.value(value: breeds[index], child: BreedItemView());<br>      }),<br>    );<br>  }</pre><p>6. Let&#39;s catch the data we want from provider and add a filled star to mark as favorite:</p><pre>import &#39;dart:io&#39;;<br>import &#39;package:dogs_breeds/utils/routes.dart&#39;;<br>import &#39;package:flutter/cupertino.dart&#39;;<br>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:go_router/go_router.dart&#39;;<br>import &#39;package:provider/provider.dart&#39;;<br><br>import &#39;../models/breed.dart&#39;;<br><br>class BreedItemView extends StatelessWidget {<br><br>  BreedItemView();<br><br>  @override<br>  Widget build(BuildContext context) {<br>    final breed = Provider.of&lt;Breed&gt;(context);<br><br>    return Platform.isIOS<br>        ? _createiOSTappableView(context, breed)<br>        : _createAndroidTappableView(context, breed);<br>  }<br><br>  GestureDetector _createiOSTappableView(BuildContext context, Breed breed) {<br>    return GestureDetector(<br>      onTap: () =&gt; _selectCategory(context, breed.name),<br>      child: _createCellView(breed),<br>    );<br>  }<br><br>  InkWell _createAndroidTappableView(BuildContext context, Breed breed) {<br>    return InkWell(<br>      onTap: () =&gt; _selectCategory(context, breed.name),<br>      child: _createCellView( breed),<br>    );<br>  }<br><br>  Container _createCellView(Breed breed) {<br>    return Container(<br>      decoration: BoxDecoration(<br>        borderRadius: BorderRadius.circular(10),<br>        border: Border.all(color: Colors.brown.shade800, width: 3),<br>      ),<br>      child: Container(<br>        child: ClipRRect(<br>          borderRadius: BorderRadius.circular(7.0),<br>          child: GridTile(<br>            footer: Container(<br>              height: 40,<br>              color: Colors.amber.withOpacity(.5),<br>              child: Row(<br>                children: [<br>                  CupertinoButton(<br>                    child: breed.isFavorite<br>                        ? Icon(<br>                            CupertinoIcons.star_fill,<br>                            color: Colors.white,<br>                          )<br>                        : Icon(<br>                            CupertinoIcons.star,<br>                            color: Colors.white,<br>                          ),<br>                    onPressed: () {<br>                      breed.toogleFavorite();<br>                    },<br>                    padding: EdgeInsets.zero,<br>                  ),<br>                  SizedBox(<br>                    width: 90,<br>                    child: Text(<br>                      breed.name.toUpperCase(),<br>                      maxLines: 1,<br>                      textAlign: TextAlign.center,<br>                      softWrap: true,<br>                      style: const TextStyle(<br>                        fontWeight: FontWeight.bold,<br>                        color: Colors.white,<br>                        fontSize: 16,<br>                      ),<br>                    ),<br>                  ),<br>                ],<br>              ),<br>            ),<br>            child: ClipRRect(<br>              borderRadius: BorderRadius.circular(7.0),<br>              child: Image.network(<br>                breed.randomImage,<br>                fit: BoxFit.cover,<br>              ),<br>            ),<br>          ),<br>        ),<br>      ),<br>    );<br>  }<br><br>  void _selectCategory(BuildContext context, String name) {<br>    context.goNamed(<br>      AppRoutes.specifBreed,<br>      params: {&quot;name&quot;: name.toString()},<br>    );<br>  }<br>}</pre><p>7. Run the app and you will be able to interact with ⭐</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad10dcafef13" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter State Management: Part 1— Inherited Widget]]></title>
            <link>https://medium.com/@cassiabarbosa/flutter-state-management-part-1-inherited-widget-e3f141df4389?source=rss-d49bbd1ef374------2</link>
            <guid isPermaLink="false">https://medium.com/p/e3f141df4389</guid>
            <category><![CDATA[inheritedwidget]]></category>
            <category><![CDATA[flutter-widget]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Cassia Barbosa]]></dc:creator>
            <pubDate>Wed, 08 Mar 2023 20:03:57 GMT</pubDate>
            <atom:updated>2023-03-08T20:03:57.902Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PNCkEjUcq_NH9wnT" /><figcaption>Photo by <a href="https://unsplash.com/@tonypepe?utm_source=medium&amp;utm_medium=referral">Tony Pepe</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>We already know how to handle with deep-links and navigation; we know also how to pass directly objects to classes in the tree, using constructors, but, Flutter has a good other way to pass data between classes not using constructor: <strong>Inherited Widget</strong>. That approach is very very useful when we have a lot of widgets in a tree and we want a specific data on leaf and we don’t wanna go through all components.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/205/1*EC0Y6dbPVf-jBYGYDAt2tg.jpeg" /></figure><p>Let&#39;s create a simple counter application to understand how it works</p><ol><li>Create a new flutter project: go to terminal and run</li></ol><pre>flutter create inherited_widget_app</pre><p>2. Open the created project on Android Studio and create a new file called <em>counter_page_screen.dart </em>and let&#39;s create a Stateful Widget, it must be a stateful because we are gonna change it.</p><pre>import &#39;package:flutter/material.dart&#39;;<br><br>class CounterPageScreen extends StatefulWidget {<br><br>  @override<br>  State&lt;CounterPage&gt; createState() =&gt; _CounterPageState();<br>}<br><br>class _CounterPageScreenState {<br>  @override<br>  Widget build(BuildContext context) {<br><br>    return Scaffold(<br>      appBar: AppBar(<br>        title: const Text(&#39;Counter&#39;),<br>      ),<br>      body: Container(<br>        alignment: Alignment.center,<br><br>        child: Column(<br>          children: [<br>            IconButton(<br>              onPressed: () {},<br>              icon: const Icon(Icons.add),<br>            ),<br>            Text(&#39;0&#39;), <br>            IconButton(<br>              onPressed: () {},<br>              icon: const Icon(Icons.remove),<br>            ),<br>          ],<br>        ),<br>      ),<br>    );<br>  }<br>}</pre><p>3. Delete default content of <em>main.dart</em> file and add these lines to initialize application with CounterPageScreen as root:</p><pre>import &#39;package:flutter/material.dart&#39;;<br>import &#39;counter_page_screen.dart&#39;;<br><br>void main() {<br>  runApp(const MyApp());<br>}<br><br>class MyApp extends StatelessWidget {<br>  const MyApp({Key? key}) : super(key: key);<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return MaterialApp(<br>      theme: ThemeData(<br>        colorScheme: ColorScheme.fromSwatch().copyWith(<br>          primary: Colors.purple,<br>          secondary: Colors.deepOrange,<br>        ),<br>      ),<br>      home: CounterPage(),<br>      debugShowCheckedModeBanner: false,<br>    );<br>  }<br>}</pre><p>Great! If you run application, you&#39;ll see a screen with + and — buttons and an 0 label. If you click on any button, nothing will happen because we&#39;re calling nothing when tap on buttons, so, let&#39;s do that using <strong>Inherited Widget pattern.</strong></p><p>4. Create a new file called <em>counter_provider.dart</em> that extends an <strong>Inherited Widget</strong></p><pre>class CounterProvider extends InheritedWidget {<br><br>  CounterProvider({Key? key, required Widget child})<br>      : super(key: key, child: child);<br><br>  static CounterProvider? of(BuildContext context) {<br>    return context.dependOnInheritedWidgetOfExactType&lt;CounterProvider&gt;();<br>  }<br><br>  @override<br>  bool updateShouldNotify(covariant CounterProvider oldWidget) {<br>    return true;<br>  }<br>}</pre><p>Note we have a static func that returns the instance of InheritedWidget which is available on widget tree.</p><p>Also, note we have updateShouldNotify function, which will be called every time there are changes.</p><p>5. Now, to updates work, let&#39;s go back to main and add our Material App inside a CounterProvider, like this:</p><pre>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:inherited_widget/counter_provider.dart&#39;;<br>import &#39;counter_page_screen.dart&#39;;<br><br>void main() {<br>  runApp(const MyApp());<br>}<br><br>class MyApp extends StatelessWidget {<br>  const MyApp({Key? key}) : super(key: key);<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return CounterProvider(<br>      child: MaterialApp(<br>        theme: ThemeData(<br>          colorScheme: ColorScheme.fromSwatch().copyWith(<br>            primary: Colors.purple,<br>          ),<br>        ),<br>        home: CounterPageScreen(),<br>      ),<br>    );<br>  }<br>}</pre><p>6. Now, inside <em>counter_provider.dart</em>, let&#39;s create a new class to hold the values and methods of CounterProvider.</p><pre>class CounterState {<br>  int _value = 0;<br>  int get value =&gt; _value;<br><br>  void increment() =&gt; _value++;<br>  void decrement() =&gt; _value--;<br>}</pre><p>7. Let&#39;s add a variable in CounterProvider that will hold the reference for state, so, your <em>counter_provider.dart</em> will be like this:</p><pre>import &#39;dart:html&#39;;<br>import &#39;package:flutter/material.dart&#39;;<br><br>class CounterState {<br>  int _value = 0;<br>  int get value =&gt; _value;<br><br>  void increment() =&gt; _value++;<br>  void decrement() =&gt; _value--;<br>}<br><br>class CounterProvider extends InheritedWidget {<br>  final CounterState state = CounterState();<br><br>  CounterProvider({Key? key, required Widget child})<br>      : super(key: key, child: child);<br><br>  static CounterProvider? of(BuildContext context) {<br>    return context.dependOnInheritedWidgetOfExactType&lt;CounterProvider&gt;();<br>  }<br><br>  @override<br>  bool updateShouldNotify(covariant CounterProvider oldWidget) {<br>    return true;<br>  }<br>}</pre><p>8. Now, go back to <em>counter_page_screen.dart </em>and the provider variable inside build methods</p><pre> final provider = CounterProvider.of(context);</pre><p>9. In order to make ours buttons work, on onTap method, let&#39;s add this on &quot;+&quot; button</p><pre>setState(() {<br>    provider?.state.increment();<br>  });<br>}</pre><p>10. And this on &quot;-&quot; button</p><pre>setState(() {<br>    provider?.state.decrement();<br>  });<br>}</pre><p>11. On Text element, replace current code for this:</p><pre>Text(provider?.state.value.toString() ?? &#39;0&#39;),</pre><p>Run your application, and boom! It will work with passing any data on constructor of CounterPageScreen!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e3f141df4389" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Started on Flutter World: Part 5 — Navigation]]></title>
            <link>https://medium.com/@cassiabarbosa/getting-started-on-flutter-world-part-5-navigation-bb20da22bf98?source=rss-d49bbd1ef374------2</link>
            <guid isPermaLink="false">https://medium.com/p/bb20da22bf98</guid>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Cassia Barbosa]]></dc:creator>
            <pubDate>Mon, 06 Mar 2023 23:30:09 GMT</pubDate>
            <atom:updated>2023-03-13T17:50:57.095Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7F8NBhDGcMpAu13_" /><figcaption>Photo by <a href="https://unsplash.com/@tonypepe?utm_source=medium&amp;utm_medium=referral">Tony Pepe</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Getting Started on Flutter World: Part 5 — Navigation and Deep-links</h3><p>Thank you <a href="https://medium.com/u/6137504c4ea4">Matias Silveiro</a> for your amazing article about <a href="https://medium.com/@matias.silveiro/welcome-to-flutter-1-what-exactly-are-widgets-905bb0b025b3">widgets</a>! Now that we know how to add widgets and components on UI, let&#39;s talk about navigation flow?</p><h4>What is Navigation?</h4><p>Navigation is the flow of screens that there&#39;s on application — we click or do some action and we are routed to other screen.</p><p>We have two primary ways to perform navigation at Flutter: <a href="https://api.flutter.dev/flutter/widgets/Navigator-class.html">Navigator</a>and <a href="https://api.flutter.dev/flutter/widgets/Router-class.html">Router</a>. Let&#39;s dive in into them.</p><h3>Navigator</h3><p>is a widget displays screens as a stack using the correct transition animations for the target platform. It holds two methods, push()to call a new screen and pop()to come back to previous screen. <br>So, let&#39;s image we have a button at screen A and when we tap it, we want to go to screen B, which has another button, when tapped, it comes back to screen A. <br>Our code will look like this on screen A:</p><pre>onPressed: () {<br>  Navigator.of(context).push(<br>    MaterialPageRoute(<br>      builder: (context) =&gt; const ScreenB(song: song),<br>    ),<br>  );<br>},<br>child: Text(&quot;Touche me to go to Screen A&quot;),</pre><p>And will look like this on screen B:</p><pre>onPressed: () {<br>  Navigator.of(context).pop();<br>},<br>child: Text(&quot;Touche me to go to Screen B&quot;),</pre><p>It&#39;s pretty simple to handle with navigation using Navigator, but sometimes, we want to be deep-linked directly into a specific screen on application, and to achieve that, we can use Router.</p><h3>Router</h3><p>is a API that provides a convenient URL-based API to navigate between different screens. To add it, you need to open the <strong>pubspec.yaml</strong> and add <strong>go_router: ^6.2.0 </strong>(you can choose the version you want to). After that, click on terminal and run <strong><em>dart pub get</em></strong> to load all dependencies.</p><p>On main.dart, import<strong><em> ‘package:go_router/go_router.dart’</em></strong>; and embed the root of your application with .router and let&#39;s create the routes on application.</p><pre>MaterialApp.router(<br>  routerConfig: _router,<br>  title: &quot;Router&quot;,<br>);</pre><pre>final GoRouter _router = GoRouter(<br>  routes: [<br>    GoRoute(<br>      path: &quot;/&quot;,<br>      builder: (context, state) =&gt; const HomeScreen(),<br>      routes: [],<br>    ),<br>    GoRoute(<br>      path: &quot;/screenB&quot;,<br>      builder: (context, state) =&gt; const ScreenB(),<br>      routes: [],<br>    ),<br>  ],<br>);</pre><p>To really go to the screen B, we need to call the path, like this:</p><pre>onPressed: () =&gt; context.go(&quot;/screenB&quot;);</pre><p>And, voilà! You&#39;&#39;ll be redirected to screen you want to.</p><p>Ok, we know how to go to screens on our application, but have you ever heard about deep-links? Yeah, a lot of applications use deep-links to route the user to some specific screen when user is on Internet and click in some link, for example. And Flutter allow us to do that too!</p><h3>Deep-links</h3><p>We are gonna code using a template application you can find here to download: <a href="https://github.com/cassiabarbosand/learningFluttter/tree/main/breeds_deeplink">https://github.com/cassiabarbosand/learningFluttter/tree/main/breeds_deeplink</a></p><p>Now, go to Android Studio and open project folder; you&#39;ll note there are some commented code, there&#39;s where we handle with deep-links. Let&#39;s uncommented together and add some configurations to run.</p><h4>Creating router</h4><p>In main.dart, observe we&#39;re creating two apps, one to run when operational system is iOS and other one when it&#39;s Android, and we are using .router(), passing an configuration.</p><p>Take a look on _router variable: we are naming a route, and giving a path (I&#39;ve add it in routes.dart just to have a better organization). At build parameter, we&#39;re passing what is gonna happen when we call the route &quot;AppRoute.home&quot;, I mean, when we call AppRoute.home, we are gonna push BreedsListView screen.</p><p>Now, let&#39;s add some configurations to run it.</p><p>iOS: add this piece of code inside <em>info.plist</em> and replace with your names. When ready, run on terminal: xcrun simctl openurl booted your_shortcut_here://your_bundle_here/and app will be opened automatically on iOS.</p><pre>&lt;key&gt;FlutterDeepLinkingEnabled&lt;/key&gt;<br>&lt;true/&gt;<br>&lt;key&gt;CFBundleURLTypes&lt;/key&gt;<br>&lt;array&gt;<br>    &lt;dict&gt;<br>    &lt;key&gt;CFBundleTypeRole&lt;/key&gt;<br>    &lt;string&gt;Editor&lt;/string&gt;<br>    &lt;key&gt;CFBundleURLName&lt;/key&gt;<br>    &lt;string&gt;your_bundle_here&lt;/string&gt;<br>    &lt;key&gt;CFBundleURLSchemes&lt;/key&gt;<br>    &lt;array&gt;<br>    &lt;string&gt;your_shortcut_here&lt;/string&gt;<br>    &lt;/array&gt;<br>    &lt;/dict&gt;<br>&lt;/array&gt;</pre><p>Android: dd a metadata tag and <a href="https://developer.android.com/guide/components/intents-filters">intent filter</a> to AndroidManifest.xml inside the &lt;activity&gt; tag with the &quot;.MainActivity&quot; name: content_copy.<br>When ready, run on terminal: adb shell &#39;am start -a android.intent.action.VIEW \<br> -c android.intent.category.BROWSABLE \<br> -d &quot;http://your_bundle_here.com/&quot;&#39; \<br> com.example.myflutterapp and app will be opened automatically on Android.</p><pre>&lt;!-- Deep linking --&gt;<br>&lt;meta-data android:name=&quot;flutter_deeplinking_enabled&quot; android:value=&quot;true&quot; /&gt;<br>&lt;intent-filter android:autoVerify=&quot;true&quot;&gt;<br>    &lt;action android:name=&quot;android.intent.action.VIEW&quot; /&gt;<br>    &lt;category android:name=&quot;android.intent.category.DEFAULT&quot; /&gt;<br>    &lt;category android:name=&quot;android.intent.category.BROWSABLE&quot; /&gt;<br>    &lt;data android:scheme=&quot;http&quot; android:host=&quot;your_bundle_here.com&quot; /&gt;<br>    &lt;data android:scheme=&quot;https&quot; /&gt;<br>&lt;/intent-filter&gt;</pre><p>Ok, cool. But, let&#39;s image this scenario: user wants to open a specific breed, through deep-link. There&#39;s where we are gonna make custom ones for us.</p><p>First of all, go back to main.dart and under builder parameter, add one called routes and add this:</p><pre>        routes: [<br>          GoRoute(<br>            name:AppRoutes.specifBreed,<br>            path: &quot;${AppRoutes.specifBreed}/:name&quot;,<br>            builder: (context, state) =&gt; SingleBreedView(name: state.params[&quot;name&quot;] ?? &quot;&quot;),<br>          )<br>        ],</pre><p>There, I&#39;m adding a sub-route called <em>AppRoutes.specifBreed</em> with a path that receives a parameter <strong><em>name</em></strong><em>. </em>I&#39;m also passing to <em>SingleBreedView</em> that parameter, since my view needs it.</p><p>Now, go to your iOS terminal and run it using this path: xcrun simctl openurl booted your_shortcut_here://your_bundle_here/spacificBreed/beagle</p><p>What do you see? BEAGLES! And with that configuration, you can open whatever part of your application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V4Y7CPxojBcyn4thG-rXtQ.png" /></figure><p>By now, you have an excellent overview how to build great screens and navigations. I would like to suggest you to create a new one before next episode! See ya!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bb20da22bf98" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Started on Flutter World: Part 3—Dart Language]]></title>
            <link>https://medium.com/@cassiabarbosa/getting-started-on-flutter-world-part-3-dart-language-a8a99fffc50f?source=rss-d49bbd1ef374------2</link>
            <guid isPermaLink="false">https://medium.com/p/a8a99fffc50f</guid>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Cassia Barbosa]]></dc:creator>
            <pubDate>Wed, 01 Mar 2023 17:32:13 GMT</pubDate>
            <atom:updated>2023-03-06T20:03:20.892Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*noso-F8_83RjGF5s" /><figcaption>Photo by <a href="https://unsplash.com/@tonypepe?utm_source=medium&amp;utm_medium=referral">Tony Pepe</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Hey, folks! You&#39;re here again, welcome! Well, before we get started creating amazing apps, we need to know how to really code. Because of that, I&#39;m really gonna take a time to explain you about Dart language:</p><blockquote>a client-optimized language for developing fast apps on any platform, also forming the foundation of <a href="https://flutter.dev/">Flutter</a>. Dart provides the language and runtimes that power Flutter apps, but Dart also supports many core developer tasks like formatting, analyzing, and testing code.</blockquote><p><a href="https://dart.dev/overview">Dart overview</a></p><p>I&#39;m gonna present you some Dart&#39;s particularities building a card game. Here is the rules:</p><p><em>To simulate we have a shuffled deck of 52 cards enumerated 0 to 9, you will enter a range of value, for example, between 2 and 7, and after that, system will give you a card in that range, and it will take a card in that range also for itself. If the number of your card is greater than its, you will gain 3 points, if the system one is greater than yours, system will gain 3 points, but it the value of both cards is the same, nothing happens with pontuation. It will win who has more points after 26 frames.</em></p><h3>Object oriented</h3><p>Dart allows us to create objects that contain data and functions. They are called classes, and they create objects which contain some data and behaviors that are necessary on application. Shall we go deeper into dart&#39;s code peculiarities?</p><h4>Creating a new class:</h4><p>Go to VSCode, create a new folder, and inside of it, create a new file called player.dart:</p><pre>class Player {<br>  String _name;<br>  int _points = 0;<br><br>  get total =&gt; _points;<br>  get name =&gt; _name;<br><br>  Player({String name = &quot;Unknown&quot;}) : _name = name;<br><br>  void updatePontuation() {<br>    _points += 1;<br>  }<br>}</pre><p>There are two private variables (_ annotation is to make a variable or function private) and before to give it a name, we need (almost always, I&#39;ll explain it soon) to add the type of it. Please, don&#39;t forget to add ;annotation, we use it to finish a command.</p><p>Now that you know the private annotation, let&#39;s talk about get methods: if we have declared some variable as private inside our class and if we need to use that variable out of class, we need to create a new get variable, and with =&gt; annotation, we are gonna say, when we call the new get variable, we are actually requesting the value of the private one.</p><p>Well, to use the class we need constructors. As you can see,_points has its own initial value, so we don&#39;t need to add it on constructor, but,_name doesn&#39;t. Because of that, we are saying on constructor we want aString value, called here as name. But, we are also passing a default value on constructor, it means, if I do not pass the value, the program will assume the default value is that one the I passed on constructor.</p><p>The last part to take a look on that class is about the method updatePontuation(). It&#39;s a simple function where value of _points variable will be incremented, and nothing will be returned, because of that I use void before its name.</p><p>Perfect! Now we have a player, let&#39;s implement our Game class to play the game.</p><h4>Creating classes in different files:</h4><p>Creating a new file now called game.dart.</p><pre>import &#39;./player.dart&#39;;<br><br>class Game {<br>  int initalRange = -1;<br>  int finalRange = -1;<br>  var player = Player();<br>  Player system = Player(name: &quot;System&quot;);<br><br>  Game();<br><br>  play(int playerSortedValue, int systemSortedValue) {<br>    if (playerSortedValue &gt; systemSortedValue) {<br>      player.updatePontuation();<br>    } else {<br>      system.updatePontuation();<br>    }<br>  }<br><br>  List&lt;Player&gt; finish() {<br>    return [this.player, this.system];<br>  }<br>}</pre><p>The first thing we need to pay attention is about import: I created that class in a different file of Player one, so, to use Player here in Game class, I need to give it the path.</p><p>As variables, we have two curious ones, &#39;player&#39; and &#39;system&#39;: they are variable from my previous defined type Player, but one of it I&#39;ve added the type var before. With that, I&#39;m using the dynamic type, it means I &#39;ll let me compiler knows the type only when I create the object.</p><p>Jumping to play method, I&#39;m creating a function that will receive two int no named parameters, I mean, when I call the function, I&#39;ll not see the name of each parameter on code, but, when I add the values, I need to respect the other. After that, it will do some computation, it won&#39;t return anything, and I&#39;m not adding void before its name. YES, void can be omitted :)</p><p>Any doubts? I hope not! So, let&#39;s to take a look on our main.dart file, it will be a little bigger than the others.</p><h4>main.dart:</h4><p>Now, create a new file called main.dart.<br>Yeah, Dart needs a main file, it’s where our application runs.</p><pre>import &#39;./game.dart&#39;;<br>import &#39;dart:io&#39;;<br>import &#39;dart:math&#39;;<br><br>main() {<br>  var game = Game();<br><br>  int _numberOfFrame = 1;<br><br>  for (_numberOfFrame; _numberOfFrame &lt;= 26; _numberOfFrame++) {<br>    while (game.initalRange == -1 || game.initalRange &gt; 10) {<br>      print(&quot;Enter the inital value of range $_numberOfFrame&quot;);<br><br>      game.initalRange = int.parse(stdin.readLineSync()!);<br>    }<br><br>    while (game.finalRange == -1 || game.finalRange &gt; 10) {<br>      print(&quot;Enter the final value of range $_numberOfFrame&quot;);<br><br>      game.finalRange = int.parse(stdin.readLineSync()!);<br>    }<br><br>    var playerValue =<br>        game.initalRange + Random().nextInt(game.finalRange - game.initalRange);<br>    var systemValue =<br>        game.initalRange + Random().nextInt(game.finalRange - game.initalRange);<br>    print(<br>        &quot;The range of frame #$_numberOfFrame will be between ${game.initalRange} and ${game.finalRange}.\nYour sorted value was: $playerSortedValue\nSystem&#39;s sorted value was: $systemSortedValue&quot;);<br><br>    game.play(playerValue, systemValue);<br><br>    game.initalRange = -1;<br>    game.finalRange = -1;<br>  }<br><br>  var results = game.finish();<br><br>  if (results[0].total &gt; results[1].total) {<br>    print(&quot;${results[0].name} has won!&quot;);<br>  } else if (results[0].total &lt; results[1].total) {<br>    print(&quot;${results[1].name} has won!&quot;);<br>  } else {<br>    print(&quot;You tied!&quot;);<br>  }<br>}</pre><p>Here is where we&#39;re adding the logic of the game: for 26 times, we are asking a range and we are sorting one value for player and another one for system. Calling game.play(playerValue, systemvalue), we are updating only the points of the winner of the frame. Pay attention: I&#39;m using others variables whose names don&#39;t match with defined parameters on function, because I omitted the parameters when I created the function. To have also here the names of the parameters, I must create a function like this:</p><pre>play({required int playerSortedValue, required int systemSortedValue}) {<br>    if (playerSortedValue &gt; systemSortedValue) {<br>      player.updatePontuation();<br>    } else {<br>      system.updatePontuation();<br>    }<br>  }</pre><p>And on main, I must call like this:</p><pre>game.play(playerSortedValue: playerValue, systemSortedValue: systemValue);</pre><pre>The range of frame #$_numberOfFrame</pre><h4>Interpolation:</h4><p>On an application without any interface, we need to show what is happening on it, and users must understand it. That being said, a great way is to print variables and actions that is being taken. So, to use some variable inside a string, we can do in two ways: or we use $ annotation before the variable, like in &quot;The range of frame #$_numberOfFrame&quot;, or we can use &quot;The range of frame #{$_numberOfFrame}&quot; with #${variableName} annotation.</p><p>Ok, now, we can go to terminal inside VSCode and run this command:</p><pre>dart main.dart</pre><p>and, play our funny game!</p><p>Well, guys, that&#39;s all for today! I tried to present you the basic of basics to create a good code on Dart. See you later, when <a href="https://medium.com/u/6137504c4ea4">Matias Silveiro</a> is gonna focus on FLUTTER and he is gonna talk about WIDGETS ❤.</p><p><a href="https://medium.com/@matias.silveiro/welcome-to-flutter-1-what-exactly-are-widgets-905bb0b025b3">Welcome to Flutter! 1 — What exactly are Widgets?</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a8a99fffc50f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Started on Flutter World: Part 2— Basic Structure and Running a Project]]></title>
            <link>https://medium.com/@cassiabarbosa/getting-started-on-flutter-world-part-2-basic-structure-and-running-a-project-e236264ad3b?source=rss-d49bbd1ef374------2</link>
            <guid isPermaLink="false">https://medium.com/p/e236264ad3b</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[dart]]></category>
            <dc:creator><![CDATA[Cassia Barbosa]]></dc:creator>
            <pubDate>Mon, 27 Feb 2023 17:26:27 GMT</pubDate>
            <atom:updated>2023-03-07T13:59:06.317Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*foCv4gY3dMRy02lH" /><figcaption>Photo by <a href="https://unsplash.com/@tonypepe?utm_source=medium&amp;utm_medium=referral">Tony Pepe</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Since you have your environment done, it&#39;s time to starting code.</p><h4>Creating your project:</h4><p>Go to terminal , choose a folder to create the project and add this code and replace <em>app_name</em> with the name you want for your project.</p><pre>flutter create app_name</pre><p>With your project created, you can close the terminal and open VSCode in the specific project folder. Yes, I&#39;m gonna use VSCode, since I&#39;m more familiar with and I can use Dev Tools in an easier way — I &#39;ll talk later what Dev Tools is.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5jCf6iboXx4GZth7s0ChUw.png" /></figure><h4>Folder Structure</h4><p>Now you have a basic application, let&#39;s take a look on folders: we have one for iOS, one for Android, one for MacOs… well, we have a lot of folders, but 95% of time, we are gonna use only the <strong>lib</strong> one, since it&#39;s there we we have the main.dart file, the front door of our application. The others folders holding the specifications from each platform, for example, in iOS folder, we have the <em>info.plist</em>, file where we can change the name of application, and add others configurations.</p><p>Other thing that you must be aware is about naming convention: in Dart and Flutter, we use the snake case with lower case to name your files and folders. But, when we create the name of the classes, we often use the camel case with the first letter of class in upper case.</p><h4>Running the App</h4><p>As you know, when we crate applications using Flutter, our goal is to write one code that can be interpreted on multi-platforms. In the mobile development, we are talking about iOS and Android. That being said, let&#39;s run it on both platforms:</p><p>Click on devices, on bottom-left and it will appear all simulators/emulators you have access.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZEbX8w3yEJ4wkamsBZ6D3Q.png" /></figure><p>If you click on “Start iOS Simulator” you will start the iOS simulator, you only will se the &quot;Start Pixel 2 API 33&quot; if you have an Android emulator set. If you don&#39;t have one, tap on &quot;Create Android Emulator&quot;. After that, you can click on “Start Pixel 2 API 33” and your application will be built on Android.</p><p>To really run the application, you need to go to Run -&gt; Run Without Debugging, that will make you only run the application, so, if you have break points, it won&#39;t be hit. Since your build id built, you are gonna see the default application running.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R3WWhp1LHa4qX9r4XsxN7w.png" /></figure><p>And here the magic of VSCode happens: when your app is built, you&#39;ll se the Widget Inspector or Dev Tools automatically. It&#39;s a cool tool to take a look on our widget tree or fix some constraints issues, for example.</p><p>Ok folks, now that we already have our environment done and we already know how to run our app, let’s create a new one from scratch? See you soon on next chapter <a href="https://medium.com/@cassiabarbosa/getting-started-on-flutter-world-part-3-dart-language-a8a99fffc50f">https://medium.com/@cassiabarbosa/getting-started-on-flutter-world-part-3-dart-language-a8a99fffc50f</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e236264ad3b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Started on Flutter World: Part 1 — Environment Configuration]]></title>
            <link>https://medium.com/@cassiabarbosa/getting-started-on-flutter-world-part-1-environment-configuration-ffe5b3476251?source=rss-d49bbd1ef374------2</link>
            <guid isPermaLink="false">https://medium.com/p/ffe5b3476251</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Cassia Barbosa]]></dc:creator>
            <pubDate>Mon, 27 Feb 2023 16:41:01 GMT</pubDate>
            <atom:updated>2023-02-27T18:23:23.489Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wXl29SrXHoQBwMpN" /><figcaption>Photo by <a href="https://unsplash.com/@tonypepe?utm_source=medium&amp;utm_medium=referral">Tony Pepe</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Getting Started on Flutter World: Part 1 — Environment Configuration</h3><p>It’s been a while since I appeared here, but it’s because I was experiencing to Flutter world, yeah, now I&#39;m almost Julius, I have two jobs :0</p><p>I&#39;ll write a series of Introduction to Flutter, from beginning, until be able to code an real application, adding analytics, push notifications, database and more!</p><p>The first step is to configure your environment to support Flutter coding. <em>Just a reminder, I&#39;ll add steps to configure on MacBook, since, to run on iOS, we need Xcode, and we only can install XCode on MacBook. </em><br>So, let&#39;s do that:</p><h3>Configuring the Enviroment</h3><h4>Install Brew on terminal using this command line:</h4><pre>/bin/bash -c &quot;$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)&quot;</pre><h4>After installing Brew, install Git using this command:</h4><pre>brew install git</pre><h4>Install OpenJDK:</h4><p>MacBook with Intel:</p><pre>brew install openjdk@8</pre><p>MacBook with Apple Silicon:</p><pre>brew install openjdk@11</pre><h4>Installing VSCode</h4><pre>brew install --cask visual-studio-code</pre><h4>Installing extensions on VSCode:</h4><p>Go to extension icon, or press shift+command+X, search and install:<br><a href="https://marketplace.visualstudio.com/items?itemName=Dart-Code.dart-code">Dart-Code.dart-code</a> (Dart)<br><a href="https://marketplace.visualstudio.com/items?itemName=Dart-Code.flutter">Dart-Code.flutter</a> (Flutter)</p><h4>Install Android Studio:</h4><pre>brew install --cask android-studio</pre><p>After installing, open Android Studio, go to Plugins tab, search and install:<br>Dart<br>Flutter</p><h4>Installing Flutter on your machine:</h4><pre>brew install --cask flutter</pre><p>After installed, run flutter doctor to make sure everything is ok with configurations</p><h4>Installing Dart Language on your machine:</h4><pre>brew install dart-sdk</pre><h4>In order to run your applications on Android and iOS, we need to create emulators/simulators.</h4><p>Android Studio:<br>Go to More Actions -&gt; Virtual Device Manager -&gt; Create Device -&gt; Choose a screen -&gt; Next -&gt; Choose the OS (I recommend to choose Android 12.0 for now) -&gt; Next -&gt; Give a name for your device -&gt; Finish</p><p>XCode:<br>Go to App Store -&gt; search for XCode -&gt; Click on Install.</p><p>Well, now you have all steps to start Flutter coding… See you in the next one,</p><p><a href="https://medium.com/@cassiabarbosa/getting-started-on-flutter-world-part-2-basic-structure-and-running-a-project-e236264ad3b">Getting Started on Flutter World: Part 2— Basic Structure and Running a Project</a></p><p>where we are gonna learn how to run the code :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ffe5b3476251" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Protocol Delegate em Swift]]></title>
            <link>https://medium.com/mackmobile/protocol-delegate-em-swift-5f521e19ca56?source=rss-d49bbd1ef374------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f521e19ca56</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[protocol]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[delegate]]></category>
            <dc:creator><![CDATA[Cassia Barbosa]]></dc:creator>
            <pubDate>Fri, 24 Sep 2021 18:09:10 GMT</pubDate>
            <atom:updated>2021-09-24T18:09:10.348Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RPgoeV7dX_OALwTa2_BjCA.png" /></figure><p>Imagine um aplicativo em que você tenha que passar informações entre Views. Imaginou? Bom, quase todos os apps precisam disso, certo? Agora imagine que você tenha uma View Controller que contenha uma Table View Controller, como você faria para que table faça algo na view principal? Bom, pra isso que vamos aprender hoje a usar Protocol Delegate.</p><h4>Passo 0: Projeto</h4><p>Para melhor acompanhar o tutorial, sugiro que você acesse o projeto neste link e então siga os próximos passos.<br><a href="https://github.com/cassiaabarbosa/ProtocolDelegate/">https://github.com/cassiaabarbosa/ProtocolDelegate</a></p><h4>Passo 0,5 : No Storyboard</h4><p>Nos meus projetos eu não uso Storyboard, portanto, se você ainda não conhece como colocar elementos de UI programaticamente, sugiro que acesse <a href="https://medium.com/@cassiabarbosa/view-code-em-swift-6026f42bf780">esse</a> outro tutorial meu para entender melhor.</p><h4>Passo 1: View A e View B</h4><p>Vamos trabalhar com dois tipos de views, uma será a ViewController, que conterá uma UITableView e a outra view será a própria UITableView. Observe que são duas views distintas A (ViewController) e B (UITableView)<br> que têm relação entre sim, porém a view B consegue mandar dados para a view A ou fazer com que a view A executa alguma ação quando o usuário pressionar a view B. Para que o Protocol Delegate não fique confuso, tenha isso em sua mente.</p><h4>Passo 2: Protocol</h4><p>A definição do Protocol sempre estará na View B, isso quer dizer que no início do arquivo que a view que quer passar uma informação, eu deverei fazer:</p><pre>protocol Nome_do_Delegate: AnyObject {</pre><pre>    func nome_da_Funcao_Implementada_pelo_Delegate()</pre><pre>}</pre><p>Ainda na view B eu deverei fazer o código abaixo; <em>weak</em> aqui serve para que eu possa usar depois o delegate sem reter estados indesejados.</p><pre>weak var delegate: nome_do_Delegate?</pre><h4>Passo 3: Delegate</h4><p>Quem implementa a função do delegate é a view A, portanto, no final dessa view eu crio uma extension, como no código a seguir:</p><pre>extension Nome_View_Controller_A: Nome_do_Delegate {</pre><pre>   func nome_da_Funcao_Implementada_pelo_Delegate() {</pre><pre>//   passo informações, ajustes, o que eu quiser fazer no função</pre><pre>   }</pre><pre>}</pre><p>Ainda na view A, onde eu crio a view B, eu devo dizer que: <strong>viewB.delegate = self,</strong> isso faz com que aquela variável <em>delegate </em>da view B crie uma referência na view A.</p><h4>Passo 4: Chamando o Delegate</h4><p>Agora, para finalizar, devemos chamar a função na view B que foi criada no Protocol e implementada pelo Delegate dessa maneira:</p><pre>delegate?.nome_da_Funcao_Implementada_pelo_Delegate()</pre><p>Assim, quando algo acontecer na view B, principalmente por interação com o usuário, algo poderá ser atualizado na view A.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f521e19ca56" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mackmobile/protocol-delegate-em-swift-5f521e19ca56">Protocol Delegate em Swift</a> was originally published in <a href="https://medium.com/mackmobile">Apple Developer Academy | Mackenzie</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Local notifications - Swift 5.0]]></title>
            <link>https://medium.com/mackmobile/local-notifications-swift-5-0-422b8f1b77a0?source=rss-d49bbd1ef374------2</link>
            <guid isPermaLink="false">https://medium.com/p/422b8f1b77a0</guid>
            <category><![CDATA[programação]]></category>
            <category><![CDATA[local-notifications]]></category>
            <category><![CDATA[apple]]></category>
            <category><![CDATA[desenvolvimento]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Cassia Barbosa]]></dc:creator>
            <pubDate>Fri, 29 Jan 2021 14:03:21 GMT</pubDate>
            <atom:updated>2021-01-29T14:03:21.991Z</atom:updated>
            <content:encoded><![CDATA[<h3>Local Notifications — Swift 5.0</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/294/1*S5VjRYuRskmmc5ZnbPzIsA.png" /></figure><p>Esse tutorial é para você que está querendo deixar seu aplicativo mais profissional. Você vai aprender a configurar o envio de notificações para que o usuário possa manipular o app apenas por ações.</p><ol><li>O primeiro passo é abrir o Xcode e criar um novo projeto em branco mesmo, e nomeá-lo como desejar.</li><li>Abra o storyboard e coloque os elementos necessários para a interface do seu aplicativo e resolva as constraints; no meu caso, o aplicativo deve mandar a notificação de acordo com os dados que o usuário coloca. Além disso, ele deve configurar se haverá som e badge (o famoso numerozinho em cima do ícone).</li></ol><p>3. Abra o Delegate e coloque o seguinte código:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bb55f8abec431da7cbfc541f948d6069/href">https://medium.com/media/bb55f8abec431da7cbfc541f948d6069/href</a></iframe><p>Essa função serve para que o usuário permita, logo na primeira vez que o app for aberto, que as notificações sejam mandadas.</p><p>4. Na classe da sua View Controller, faça o seguinte:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/900b2590bc671659e808695cc00c6e5f/href">https://medium.com/media/900b2590bc671659e808695cc00c6e5f/href</a></iframe><p>Na linha 7, nós estamos dizendo que essa view é seu próprio delegate.</p><p>5. No meu app, a notificação só será enviada quando um botão for clicado, para tanto, eu coloquei o botão de criar notificação, nomeei-o no código como <strong>BotaoDeNotificacao</strong> e puxei do storyboard para a view como uma action que recebe como parâmetro<em> _ sender : Any</em>. Como eu tenho outros elementos, como switch e text fields, puxei todos do storyboard também, mas como outlets, pois o conteúdo deles serão usados mais tarde.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f89bd522c376fa56177bd6950a1aacab/href">https://medium.com/media/f89bd522c376fa56177bd6950a1aacab/href</a></iframe><ul><li>A linha 3 é para fazer o controle da notificação;</li><li>Da linha 8 até a linha 17, serve para dizer o que deve fazer caso o usuário tenha permitido ou não que o app mande notificações.</li><li>As linhas 5, 6, 7 e 8 são as &quot;actions&quot;, ou seja, o que vai aparecer dentro da notificação quando ela for puxada para baixo.</li></ul><p>Note que na linha 12 eu chamei uma função chamada <strong>mandaNotificacao()</strong>, ela é responsável por caracterizar todo o escopo da notificação, ou seja, o que vai aparecer nela.</p><p>6. Agora é o momento em que chamo a minha função.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b45ba0705ff6cfa5d9d06a8c8e9dfcad/href">https://medium.com/media/b45ba0705ff6cfa5d9d06a8c8e9dfcad/href</a></iframe><p>A variável <strong>conteudoDaNotiticacao</strong> é a notificação em si: tem o seu identificador único, título, corpo, trigger, som e bagde. Nesse ponto, a bagde é muito importante, pois se a notificação for enviada, a bagde tem que aparecer, mas quando o usuário clicar de novo para abrir o app, ela tem que sumir. Então, para configurar isso, eu devo ir até o <em>delegate</em> mais uma vez e fazer o seguinte:</p><pre>func applicationDidBecomeActive(_ application: UIApplication) {<br>     application.applicationIconBadgeNumber = 0<br>}</pre><p>7. Observe que dentro da função <strong>mandaNotificacao() </strong>há uma variável chamada &quot;trigger&quot;, ela serve para disparar a notificação e nela você deve colocar quando ou de quanto em quanto tempo ela ocorrerá.</p><p>8. A última função que eu devo implementar na classe onde estou construindo a minha view do app é essa <strong>didReceive</strong>, apresentada abaixo.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b45ba0705ff6cfa5d9d06a8c8e9dfcad/href">https://medium.com/media/b45ba0705ff6cfa5d9d06a8c8e9dfcad/href</a></iframe><p>Essa função coordenará as actions da notificação. Uma vez que o usuário clique arraste para baixo, aparecerá as actions e cada action representa uma ação. Neste caso, se apertar em <strong>&quot;Repetir&quot; </strong>a<strong> </strong>notificação será mandada novamente de acordo com o tempo estipulado, já se apertar <strong>&quot;Tela&quot;</strong> uma outra tela aparecerá e você poderá voltar à tela inicial do app pelo botão <strong>&quot;Done&quot;</strong>.</p><p>9. Essa outra tela a que me referi no passo anterior pode ser simplesmente escrita como mostra o código abaixo. Ela deverá ser uma <strong>UIViewController </strong>também, deverá ter o protocolo de <strong>UNUserNotificationCenterDelegate</strong> e ser o seu próprio delegate.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b45ba0705ff6cfa5d9d06a8c8e9dfcad/href">https://medium.com/media/b45ba0705ff6cfa5d9d06a8c8e9dfcad/href</a></iframe><p>10. Aqui você pode ver o resultado final do app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/969/1*GPypP5IX-LSYU4d1jefT7g.png" /></figure><p>Como você pode ver, aqui temos como o aplicativo ficou. Esse foi um teste simples e rápido para você aprender a usar Local Notifications!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=422b8f1b77a0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mackmobile/local-notifications-swift-5-0-422b8f1b77a0">Local notifications - Swift 5.0</a> was originally published in <a href="https://medium.com/mackmobile">Apple Developer Academy | Mackenzie</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>