kauemurakami / getx_pattern Goto Github PK
View Code? Open in Web Editor NEWDesign pattern designed to standardize your projects with GetX on Flutter.
Home Page: https://kauemurakami.github.io/getx_pattern
Design pattern designed to standardize your projects with GetX on Flutter.
Home Page: https://kauemurakami.github.io/getx_pattern
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
......
Hey. I really like this proposed getx file structure. I only had a few questions:
Thank you in advance!
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?
can you teach me example if want using getConnect as provider? and how how to using that provider in my repository?
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
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.
I want to create dialogs as forms, does it go in the "modules" folder? or where would they go
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.
hai @kauemurakami !. can you give one simple example for animation using getx, Can we do animation with getx or should i go with statefullWidget. coz im confused how to use the package and this pattern to implement animations.
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?
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.
I have been overwhelmingly fascinated by GetX and its uses. Thank you so much:heart:
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.
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
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
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.
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!
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.
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.
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 é 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
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:
- /data
- /service
- ?.dart
- /provider
- ?.dart
- /repository
- ?.dart
- /model
- cidades.dart
- modules
- cidades
- controlador_cidade.dart
- page_cidade.dart
Muito obrigado! Parabéns pelo trabalho!
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?
app - ui - android
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!
what is the difference?
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
This article should be very helpful to me, but unfortunately there is no English version
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 rethrow
ing 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!
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
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 ?
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á.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.