Code Monkey home page Code Monkey logo

kauemurakami / getx_pattern Goto Github PK

View Code? Open in Web Editor NEW
998.0 29.0 234.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 state stateless getx-ecosystem getxpattern

getx_pattern's Issues

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
......

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!

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?

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

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.

Where do the dialogs go?

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

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.

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?

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:

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.

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

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.

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!

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.

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!

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?

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

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!

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

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!

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

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: 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á.

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.