Giter Site home page Giter Site logo

kauemurakami / getx_pattern Goto Github PK

View Code? Open in Web Editor NEW
977.0 29.0 233.0 122.76 MB

Design pattern designed to standardize your projects with GetX on Flutter.

Home Page: https://kauemurakami.github.io/getx_pattern

HTML 22.91% CSS 0.76% Java 35.99% Shell 0.36% Objective-C 0.38% Makefile 39.60%
flutter flutter-apps flutter-examples pattern design-patterns getx get dart architectural-patterns state-management

getx_pattern's Introduction

getx_pattern

Star on GitHub Buy Me A Coffee

A proposal to standardize your development with GetX.

Objective

  • Facilitate the learning of the package.
  • Have a solid, standard structure for developing applications with GetX.
  • Facilitate the use of GetX in an organized, simple and scalable way.
  • Facilitate the search for information and dissemination of knowledge.

Note: This README and it's examples are more updated than the website's. We are currently working in an english and multi-language version.

About

Article in pt-BR: Um pouco sobre o GetX Pattern! 🚀

Documentation in pt-BR at GitHub Pages

Also try our extension for VSCode: GetX Snippets! Made to work with getx_pattern and to greatly speed up your development process with GetX.

New website under construction to improve everyone's learning and follow-up!

How does it work?

Structure in modules

GetX_Structure

- /lib/app  
# This is where all the application's directories will be contained  
    - /data
    # Directory responsible for containing everything related to our data
        - /enums 
        - /services
             # This is where we store our Services
             # Here our repositories are just classes that will mediate the communication between our controller and our data.
             # Our controllers won't need to know where the data comes from, and you can use more than one repository on a controller if you need to.
             # The repositories must be separated by entities, and can almost always be based on their database tables.
             # And inside it will contain all its functions that will request data from a local api or database.
             # That is, if we have a user table that we will persist as, edit, add, update and delete, all these functions are requested 
             # from an api, we will have a repository with this object of the api where we will call all the respective 
             # functions to the user. So the controller does not need to know where it comes from, the repository being a 
             # mandatory attribute for the controllers in this model, you should always initialize the controller with at - /repository
            - /example_service.dart
                - service.dart
                - repository.dart
        - /provider
        # Our data provider, can be an api, local database or firebase for example.
            - api_provider.dart
            - db_provider.dart
            - storage_provider.dart
        # Here, our asynchronous data request, http, local database functions must remain ...
        - /model
        # Our classes, or data models responsible for abstracting our objects.
            - model.dart
    - /modules
    # Each module consists of a page, its respective GetXController and its dependencies or Bindings.
    # We treat each screen as an independent module, as it has its only controller, and can also contain its dependencies.
    # If you use reusable widgets in this, and only in this module, you can choose to add a folder for them.
        - /my_module
            - page.dart
            - controller.dart
            - binding.dart
            - repository.dart
            - /local_widgets
    # The Binding class is a class that decouples dependency injection, while "binding" routes to the state manager and the dependency manager.
    # This lets you know which screen is being displayed when a specific controller is used and knows where and how to dispose of it.
    # In addition, the Binding class allows you to have SmartManager configuration control.
    # You can configure how dependencies are to be organized and remove a route from the stack, or when the widget used for disposition, or none of them.
    #The decision to transfer the repositories "globally" to internal modes within each module is that we can use a function in different modules, but the problem was due to having to import more than one repository in the controller, so we can repeat the same calls functions, internal repositories, thus maintaining faster maintenance, making everything that gives life to the module reachable through the module itself.
    #Repositories then become just a class to point to the controllers of our module, which and which provider we are going to consume, the same goes for services, services that have integration with some provider, must have its own repository

    - /global_widgets 
    # Widgets that can be reused by multiple **modules**.  

    - /routes
    # In this repository we will deposit our routes and pages.  
    # We chose to separate into two files, and two classes, one being routes.dart, containing its constant routes and the other for routing.  
        - routes.dart
        # class Routes {
        # This file will contain your constants ex:  
        # class Routes { const HOME = '/ home'; }  
        - pages.dart
        # This file will contain your array routing ex :  
        # class AppPages { static final pages = [  
        #  GetPage(name: Routes.HOME, page:()=> HomePage()) 
        # ]};  
    - /core
        - /errors
        # error handling and classes
        - /values
            - strings.dart
            # globally reusable strings
            # example : enter > "Enter" on several buttons
            - colors.dart
            # colors that can be reused throughout the application
            - /languages
            # for applications that use internationalization, they can deposit their translation files here
                - /from
                    - pt-br.dart
                    - en-au.dart
        - /theme
        #Here we can create themes for our widgets, texts and colors
            - text_theme.dart  
            # inside ex: final textTitle = TextStyle(fontSize: 30)  
            - color_theme.dart  
            # inside ex: final colorCard = Color(0xffEDEDEE)  
            - app_theme.dart  
            # inside ex: final textTheme = TextTheme(headline1: TextStyle(color: colorCard))  
        - /utils
        #Here you can insert utilities for your application, such as masks, form keys or widgets
            - /extensions
                # are a way to add functionality to existing libraries
                - example_remove_underlines.dart
                # https://dart.dev/guides/language/extension-methods
                
            - /functions
            # functions that can be reused globally in the app
                - get_percent_size.dart
                # example: a function that returns the percentage of a parent widget
                
            - /helpers
            # abstract classes or helper classes like key masks etc
                - masks.dart  
                # inside ex: static final maskCPF = MaskTextInputFormatter(mask: "###.###.###-##", filter: {"#": RegExp(r'[0-9]')});  
                - keys.dart  
                # inside ex: static final GlobalKey formKey = GlobalKey<FormState>();
- /repos # Use for Micro Front-End multirepo example:
    - /dependencies
    - /core
- main.dart  
# main file
# proposed by william Silva and Kauê Murakami
# We also have a version in packages to vocvê that is used to the good old MVC
New example implementation: [dev app](https://github.com/kauemurakami/example)
New GetRouterOutlet implementation: [Meditation app](https://github.com/kauemurakami/meditation-app-rewrite-getx)
todo-list with Get Storage with state manager and services: [todo-list](https://github.com/kauemurakami/todo-list-get-storage)
valorant example state manager with state mixin: [examples/valorant-brasil-module-example](https://github.com/kauemurakami/valorant-brasil)
blogging example state manager with state mixin and service: [Blogging](https://github.com/kauemurakami/blogging)  
Another: [byebnk](https://github.com/kauemurakami/teste-bye-b)

Data

Here we don't have much to discuss, it is just a repository where you will abstract/package everything related to your data: your models, your services and data providers. If you choose to use the module version, the data folder will have the same role, leaving your data available for all your modules, having only what is vital for your module in it!
This was designed so that you can keep your directory structure as small as possible when working with Flutter, and at the same time, be intuitive and didactic to speed up your learning curve.

Provider

obs: In some other structures, the term 'provider' can be approached in various ways, but here, it exists only and exclusively, to make http requests or persistence in a database. If you use both, create the respective directories and / or files within it.
If there are many requests, in a single file, you can choose to separate by entities, or keep it in the same file, this is a personal choice and it is up to each programmer.

Model

In our model class we will have our attributes and two methods, toJson and fromJson responsible for converting our object to json or a json to our object.
Generally when we work with API's, we use these methods to create objects from our api's response, or create a json to send to our api.

Repository

The repository is now responsible only for grouping the functionalities of the providers consumed by the controller of that module, in order to map the use of the providers and to group their calls.

Module

The modules will contain our respective Binding, Page, Controller.
This makes the project shorter and easier to maintain.

Controller

Controllers are the vital part of your application, in which you will create your .obs variables which will store values ​​that can be changed during the application.
Your controller is also responsible for consuming your data>, through its repositories, which in turn only perform data calls from your providers Rule: Every controller must have one, and only one, repository, which is an attribute required to initialize your controller in your GetX widget.
If you need data from two different repositories on the same page, you must use two GetX widgets. We recommend that there is at least one controller for each page.
There is only one exception so that you can use the same controller for several pages, and it is quite simple:

IMPORTANT: You can use a controller on several pages, only and exclusively, if the data on all pages, consume a single repository.

The purpose of this is to get you to use GetX and take full advantage of its power, so whenever you need to manipulate two entities, you will need two different controllers and a view.
Why? Imagine that you have a controller with two repositories, and that controller is being used with a GetX widget on a page, using data retrieved by the controller from the two repositories.
Whenever an entity is modified, the controller will update its widgets responsible for the two variables, one of which did not need to be changed. So separating a repository by controller, it can be a good practice when working with the GetX widget, having a responsible controller for each widget, which somehow shows this information from them, rendering only the widget that had its .obs variable changed.

Bindings

Ideal for your dependency management, bindings can initialize your controllers and repositories, apis and whatever you need, without having to call them directly from View with GetView!

Page

Your module interface using YourPage extends GetView.

getx_pattern's People

Contributors

adilsonjuniordev avatar jcorrego avatar kauemurakami avatar marcosfons avatar mrashidcit avatar musta-pollo avatar nosadaniel avatar pedrobuzzi avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

getx_pattern's Issues

Example code

Hello to writer ,

your article is so good but there is problem !

there is no implementation witch we can see and understand more !

for example one person like me who always use MVC doesn't know whats repository!

how to implement the repository :( please provide some code to we can read ❤️ thanks

examples _and_ exemples?

as of writing, the repo has examples and exemples, and both have stuff in them - is this intentional (for existing tutorials)?

meta (optional): do you think getx_pattern is going to make it? and has a different templating approach emerged?
I am looking to put together a set of starter patterns for various "web3" 🦍 use-cases, and came across this after get seemed like the most compatible approach to state management. If you were starting today, what would you do differently?

Where do the dialogs go?

I want to create dialogs as forms, does it go in the "modules" folder? or where would they go

What is the purpose of android folder in ui?

Hi, thx for the getx_pattern and the getx snippets.
Looking through your site and sample, I saw the ui/android and ui/ios folders.
Any reason to split this up. Is this if you want different ui for each platform?
What if you want 1 ui, regardless of platform.
Would you then just put everything directly under the ui/ folder, or use something like ui/shared ?

Dúvida no conceito de módulo

Salve @kauemurakami, tira uma dúvida, no artigo em português vc falou que cada módulo seria uma tela nossa. No caso se seu tivesse que representar um CRUD de produtos, teria que fazer 3 módulos no caso? O de listagem, adição e alteração?

A estrutura no caso ficaria assim?

Modules
  - product
  |  - list
      |  - controller.dart
      |  - page.dart
      |  - bindings.dart
  |  - create
      |  - controller.dart
      |  - page.dart
      |  - bindings.dart
  |  - edit
      |  - controller.dart
      |  - page.dart
      |  - bindings.dart

A working minimal example would be greatly appreciated

Is there an example that showcases a project with this setup in action? I have been trying to change an existing project to this project recommendation.

  1. What is the difference between provider and services in the data folder?
  2. Where and how should be a dio object created in this setup? Along with the snippets from the VSCode, it would seem that everywhere the repository object is created an httpClient is to be used. Even on the bindings page. Doesn't it seem awkward?
  3. I have a singleton class that provides user information (username, profile pic, token, etc...) to pages. Which is initialized during login. Should this be changed to GetxService? Where should it be kept in this structure?
  4. Some services (like constantly checking for connectivity and doing some action based on the connectivity status) are a good candidate for GetXService. Where should it be placed?

I have been overwhelmingly fascinated by GetX and its uses. Thank you so much:heart:

Question regarding the getx pattern

Hey. I really like this proposed getx file structure. I only had a few questions:

  • What is the difference between a service and a provider in this case?
  • What is the difference between the repositories inside the service folder and inside each module folder?

Thank you in advance!

Detect back button event in android

There is a way to handle back button event?

My class extends GetView but I don't know how to implement it when the user tap the back button on the device.

Get_Pattern Template

Do you have not considered creating something to be able to create Getx projects with Slidy for example.
It currently serves to create Bloc and Provider projects, it was great if you could create the framework for GetX as well. Or, failing that, some other way that generates that template type structure.

Where would an auth service fit in here ?

I'm looking at the project structure and I am wondering where an auth service would fit in here. I assume it's in the data directory.

I usually organise my projects with a core folder at the top

- core
   -  api
   -  controllers
   -  models
   auth_service.dart
- shared_widgets
- screens
- routing
- theming

Erro ao voltar da view de detalhes

Olá, estou estudando GetX e usei esse app como exemplo de estudos. Ao rodar o projeto e clicar em um item da lista é exibido a página de detalhes normalmente, mas ao voltar para a lista e clicar novamente em um item está ocorrendo o erro NoSuchMethodEerror: The getter 'post' was called on null. Receiver: null.

Na view de detalhes, a propriedade assignId está true. Para evitar o erro deve ficar: assignId: false.
Não encontrei nada sobre isso na documentação. Apenas na documentação do Get menciona a Api assign, que tem a propriedade de limpar um List.

Dúvida sobre arquitetura de dados.

Gostaria de saber a visão de vocês na diferença de services e providers. Estou tentando aplicar a arquitetura de vocês e me deparei com as seguintes dúvidas, creio que irá ajudar a melhorar a qualidade da arquitetura.

Discussão

Pelo que li na documentação, vocês usam Repository como uma camada de abstração da classe que faz as chamadas com a camada de dados, que chamam de Provider. Services no entanto, não está declarado na documentação.

Ao meu entender, Repository e Provider estariam trocados aqui, o correto sendo Repository como abstração básica da camada de dados com CRUD e QUERY, nada mais... e Provider como abstração do Repository contendo extras, provendo dados as views.

Services por outro lado, é muito usado em outras arquiteturas como uma camada responsável pela abstração dos dados para a view, não diretamente ligada a persistencia (Repository no meu entender, ou Provider na documentação existente).

Creio que é importante deixar muito claro os objetivos destas terminologias em questão, existem muitos conceitos diferentes espalhados por ai em diversas arquiteturas, cada um adotando sua interpretação do mesmo.

Proposta

Seria possível ogarizarem uns arquivos na arquitetura que idealizaram para mim? Creio que esse exercicio iria clarificar melhor as terminologias.

Suponha dois canais de dados de mesma natureza, para consistência:

  • Banco de dados local - Cidades
  • API externa correios - Cidades

Banco de dados local é usado quando API externa está fora do ar. Banco de dados local é atualizado com os dados de API se existirem alterações.

Modelo:
cidades.dart - modelo compatível com as duas fontes de dados

Primeira camada após dados:
crud_local_cidades.dart - fornece crud dos dados com o banco local, e um método de query genérica
api_cidades.dart - recupera os dados de uma api externa (disponível ou não), e um método de query genérica

Segunda camada:
zzz_cidades.dart

  • Decide se os dados serão recuperados da API ou da base local.
  • Fornece métodos para obter dados da primeira camada, e usa a query generica em casos diversos.
  • Ex: fornece métodos para obter cidades por estado ou pais.

Terceira camada: Controlador
controlador_cidades.dart - Obtém os dados da segunda camada e disponibiliza para view.

Quarta camada: View
page_cidades.dart - view

A ideia seria organizar os 3 arquivos responsáveis pelos dados, na estrutura documentação, que seria:

  • crud_local_cidades.dart
  • api_cidades.dart
  • zzz_cidades.dart
- /data
  - /service
    - ?.dart
  - /provider
    - ?.dart
  - /repository
    - ?.dart
  - /model
    - cidades.dart
- modules
  - cidades
    - controlador_cidade.dart
    - page_cidade.dart

Muito obrigado! Parabéns pelo trabalho!

Erros de escrita no site

Prezados, de antemão gostaria de parabenizar ao trabalho de todos vocês que desenvolvem o Getx e afins. Não sei onde exatamente reportar os errinhos de escrita, então resolvi criar uma issue e enviei uma mensagem no Facebook do Kauê. Segue um PDF dos trechos que precisa corrigir. Não corrigi os jargões e o uso "doméstico" de palavras inglesas, tornando aportuguesadas. Já que sou iniciante na programação, não consigo contribuir no código, mas na escrita do Português não sou iniciante, hehe.
getx_pattern correção.pdf

Understanding the difference between Services and Providers, along with their interaction with Repositories

Hello and thank you for providing this helpful pattern! I had a clarification question about Provider and Services and the use of Repositories for each.

Providers, from what I understand, is an entity that "gets data." You use API calls and database persistence as an example, with the snippet extension utilizing GetConnect when instantiating the class. Services seem to be a bit more confusing, perhaps because some other architectures use services as a way to pull data too. For example, what would an implementation of GetStorage use? Would it be a repository because it is still "fetching data," although just from the device itself? Or would it be a service? Is there any guideline you have to determine what to classify something as a Provider or Service?

Secondly, and relatedly to the first, is their interaction with Repositories. In this Github repo, the readme describes a repository created for "example_service" and for each module, but not for the providers. Yet in the snippets readme (https://marketplace.visualstudio.com/items?itemName=get-snippets.get-snippets), the repositories only exist for the modules. Yet again in the get_pattern_example project, posts_ repositories seems only to exist for the API provider, but there are no repositories for each module.

My question is, how many repositories should I have? Should I have one for each provider and service that abstracts methods out, and then have each module have a repository that I'd assume interfaces with the provider/service repository? Would they all just be calling the same functions or how would these repositories be laid out? For example, should it look like this?

-Data
 --Services
 ---storage_service.dart
 ----storage_service_repository.dart
 --Providers
 ---api_provider.dart
 ----api_provider_repository.dart
 -details_module
 --details_page.dart
 --details_controller.dart
 --details_repository.dart
 -home_module
 --home_page.dart
 --home_controller.dart
 --home_repository.dart

Or like this:

-Data
 --Services
 ---storage_service.dart
 ---storage_service_repository.dart
 --Providers
 ---api_provider.dart
 ---api_provider_repository.dart
 -details_module
 --details_page.dart
 --details_controller.dart
 -home_module
 --home_page.dart
 --home_controller.dart

Any guidance you can provide for this would be greatly appreciated. Thank you!

Confused about the folder structure.

I am investigating Get as the core approach to our new application. It seems there are a few different folder structure.

getx_cli init creates a folder structure - this has no UI folder

The current Getx pattern info page (https://kauemurakami.github.io/getx_pattern/#home) does refer to a ui folder

GetX snippets has another structure on its details page. It says: Proposed structure -> subsequent changes will not change the current structure. This adds a core folder with them & utils subfolders and a module's structure looks different.

There is also GitHub issue in this repository with yet another proposed layout.

The examples in this repository has another structure. This has an android folder buried in the UI folder which is a bt confusing.

I suspect it does not matter, except for the assumptions the VS plugin makes about what lives where.

flutter web problem about refresh page

getx_pattern_example Project

from ListPage to DetailPage,
And click browser's refresh button ,
Then crashed :

data != null
"A non-null String must be provided to a Text widget."

截屏2021-01-04 20 09 45

So,When User refreshed current page, the data will be lost.

Site Translations

Hi, I am a US-based developer who is getting to know Flutter and has adopted the GetX pattern. I wanted to see if you were interested in some help translating the page on https://kauemurakami.github.io/getx_pattern/ where there is room for improvement. Translating it will help me learn the pattern even better so I am glad to work on it, but I don't see it in a repo where I can make the changes and send a PR. Is there somewhere I can offer edits?

Thanks!

Global controllers

Hi!
There's a place for global controllers?
For example, I need the user to be global, for that, I use a UserController with the user in it.
Should I make a folder called global_controllers?

Modules...

There is a lot to like about this pattern, but the use of the term "modules" here is a little weird, since every other root folder also contains modules. It seems like views would be better or maybe view_modules.

I also don't really understand why you'd make the stuff in the modules folder modular while making everything else monolithic. Modular structure should be used everywhere in my opinion:

- /data
    - /my_api
        - /endpoint_a
            - /models
        - /endpoint_b
            - /models
    - /aws_api
        - /models
    - /db
        - /models
    - /storage
        - /models

For larger project

I agree with your good structures. But for larger project should be compare like

Example smaller project

Controllers
src/controllers/customer.dart
src/controllers/user.dart
src/controllers/order.dart

Repositories
src/repositories/customer.dart
src/repositories/user.dart
src/repositories/order.dart

Bindings
src/bindings/customer.dart
src/bindings/user.dart
src/bindings/order.dart
......

Larger project

src/customer/controller/customer_controller.dart
src/customer/repository/customer_repository.dart
src/customer/binding/customer_controller.dart

src/user/controller/user_controller.dart
src/user/repository/user_repository.dart
src/user/binding/user_controller.dart

src/order/controller/order_controller.dart
src/order/repository/order_repository.dart
src/order/binding/order_controller.dart
......

Dúvida: onde ficariam as interfaces que são implementadas pelos `services`, `repositories` e `providers`?

Olá, nessa estrutura existe um lugar apropriado para colocar as interfaces que serão implementadas? Como por exemplo IProductApi, para que na injeção de dependências, durante os testes, a classe IProductApiMock seja chamada.
Ou essas classes ficaram juntas às suas implementações?
Teria algum lugar apropriado para colocar as classes mockadas também? Talvez dentro ou fora de Data?

E uma classe de service, digamos CameraService, que abstrai o uso da camera do dispositivo, também ficaria dentro de Data?
E classes de validação, cujo único objetivo é receber um valor e retornar os erros, ficariam dentro de utils?

Curti bastante o projeto, parabéns!
Grato desde já.

Do we really need the repository?

Hello! I like this pattern and used it for the most of my projects. But currently, I feel like using repositories just to call the API from the provider is kinda redundant. I want to know more about this, why we should use repository and not using the provider directly from the controller? And if I want to handle errors, should I handle it in the repository, or the controller by rethrowing it like so:

class AuthRepository {
  /// The provider of this repository.
  final AuthProvider provider;

  /// The constructor of this repository.
  AuthRepository({
    required this.provider,
  });

  /// Authenticate the user using `email` and `password`.
  ///
  /// Will throw [HttpException] if the request failed.
  Future<AuthCredential> login(String email, String password) async {
    try {
      final response = await provider.login({'email': email, 'password': password});
      return AuthCredential.fromJson(response.body);
    } catch (e) {
      rethrow;
    }
  }
}

Is that implementation correct? Please let me know!

Shared controller is multiple views

I am trying to understand how I could share controllers with different views.

We have two views which use the same widgets with the same content. This content can come from the same controller as it displays the same data.

Let's assume the following structure

    - /modules
        - /news
            - page.dart
            - controller.dart
            - binding.dart
            - repository.dart
        - /prices
            - page.dart
            - controller.dart
            - binding.dart
            - repository.dart

now the news view is displaying a widget, which is also used in prices, which is defined as a global widget. My assumption is that we should avoid accessing the prices controller from the news view?

As a controller should be responsible for a view, I would assume that the global widget should not have it's own controller?

Where would I put the StreamSubscription?

Hi, I follow your architecture and have sorted out all the examples, I really like using it. But I have such a problem, I have a need to monitor the Internet connection during the entire life cycle of the application. And I do not know where I could put the Stream Subscription for this tracking. Since I need to keep track of this constantly, I thought I could do it in my authService extends GetxService, since it is not deleted from memory and lives throughout the entire cycle.

And I would not like to perform this check with every network request I have, I would like to know about the network status always. I tried to do something similar, but I didn't get the desired result:

class AuthService extends GetxService{
  Future<AuthService> init() async{
    repository = AuthRepository(MyApi());
    _subscription = Connectivity().onConnectivityChanged.listen((ConnectivityResult result) async { 
      if (result == ConnectivityResult.none){
        isOfflineMode.value = false;
        Get.snackbar('No connect','There is no internet connection');
      }
      else if(result == ConnectivityResult.mobile){
        isOfflineMode.value = await InternetConnectionChecker().hasConnection;
        if(isOfflineMode.value == true){
          Get.snackbar('Нет соединения','There is no internet connection');
        }
      }
      else if(result == ConnectivityResult.wifi){
        isOfflineMode.value = await InternetConnectionChecker().hasConnection;
        if(isOfflineMode.value == true){
          Get.snackbar('Нет соединения','There is no internet connection');
        }
      }
    });
    return this;
  }

  late StreamSubscription<ConnectivityResult> _subscription;

  final isOfflineMode = false.obs;
}

I could certainly put it in controllers, but I think there will be a lot of boilerplate :)

Could you help me with this, how I could better organize the work of such functionality, I would be very grateful

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.