Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up

A smart project structure

License

NotificationsYou must be signed in to change notification settings

toshiossada/modular

 
 

Repository files navigation

Flutter Modular


LogoLogo

Welcome to Flutter Modular! A smart project structure.

View Example ·Report Bug ·Request Feature



Table of Contents
  1. About The Project
    1. What is Modular?
    2. Ready to get started?
    3. Common questions
  2. Usage
    1. Starting a project
    2. The ModularApp
    3. Creating the Main Module
  3. Contributing
  4. Contact
  5. Contributors


📝 About The Project

Let's find out how to implement a Modular structure in your project.

What is Modular?

Modular proposes to solve two problems:

  • Modularized routes.
  • Modularized Dependency Injection.

In a monolithic architecture, where we have our entire application as a single module, we design our software in a quick andelegant way, taking advantage of all the amazing features of Flutter💙. However, producing a larger app in a "monolithic" waycan generate technical debt in both maintanance and scalability. With this in mind, developers adopted architectural strategies to better divide the code, minimizing the negative impacts on the project's maintainability and scalability..

By better dividing the scope of features, we gain:

  • Improved understanding of features.
  • Less breaking changes.
  • Add new non-conflicting features.
  • Less blind spots in the project's main business rule.
  • Improved developer turnover.

With a more readable code, we extend the life of the project. See example of a standard MVC with 3 features(Auth, Home, Product):

A typical MVC

.├── models                                  # All models      │   ├── auth_model.dart                     │   ├── home_model.dart                     │   └── product_model.dart         ├── controller                              # All controllers│   ├── auth_controller.dart                     │   ├── home_controller.dart                     │   └── product_controller.dart             ├── views                                   # All views│   ├── auth_page.dart                     │   ├── home_page.dart                     │   └── product_page.dart                   ├── core                                    # Tools and utilities├── app_widget.dart                         # Main Widget containing MaterialApp └── main.dart                               # runApp

Here we have a default structure using MVC. This is incredibly useful in almost every application.

Let's see how the structure looks when we divide by scope:

Structure divided by scope

.                  ├── features                                 # All features or Modules │   ├─ auth                                  # Auth's MVC       │   │  ├── auth_model.dart   │   │  ├── auth_controller.dart  │   │  └── auth_page.dart                      │   ├─ home                                  # Home's MVC       │   │  ├── home_model.dart   │   │  ├── home_controller.dart  │   │  └── home_page.dart                        │   └─ product                               # Product's MVC     │      ├── product_model.dart   │      ├── product_controller.dart│      └── product_page.dart                    ├── core                                     # Tools and utilities├── app_widget.dart                          # Main Widget containing MaterialApp └── main.dart                                # runApp

What we did in this structure was to continue using MVC, but this time in scope. This means thateach feature has its own MVC, and this simple approach solves many scalability and maintainability issues.We call this approach "Smart Structure". But two things were still Global and clashed with the structure itself, so we created Modular to solve this impasse.

In short: Modular is a solution to modularize the route and dependency injection system, making each scope haveits own routes and injections independent of any other factor in the structure.We create objects to group the Routes and Injections and call themModules.

Ready to get started?

Modular is not only ingenious for doing something amazing like componentizing Routes and Dependency Injections, it's amazingfor being able to do all this simply!

Go to the next topic and start your journey towards an intelligent structure.

Common questions

  • Does Modular work with any state management approach?

    • Yes, the dependency injection system is agnostic to any kind of classincluding the reactivity that makes up state management.
  • Can I use dynamic routes or Wildcards?

    • Yes! The entire route tree responds as on the Web. Therefore, you can use dynamic parameters,query, fragments or simply include a wildcard to enable a redirectto a 404 page for example.
  • Do I need to create a Module for all features?

    • No. You can create a module only when you think it's necessary or when the feature is no longer a part ofthe scope in which it is being worked on.

✨ Usage

flutter_modular was built using the engine ofmodular_core that's responsible for the dependency injection system and route management. The routing system emulates a tree of modules, just like Flutter does in it's widget trees. Therefore we can add one module inside another one by creating links to the parent module.

Starting a project

Our first goal will be the creation of a simple app with no defined structure or architecture yet, so that we can study the initial components offlutter_modular

Create a new Flutter project:

flutter create my_smart_app

Now add theflutter_modular to pubspec.yaml:

dependencies:flutter_modular:any

If that succeeded, we are ready to move on!

💡 TIP: Flutter's CLI has a tool that makes package installation easier in the project. Use the command:(flutter pub add flutter_modular)

The ModularApp

We need to add aModularApp Widget in the root of our project. MainModule and MainWidget will be created in the next steps, but for now let's change ourmain.dart file:

import'package:flutter/material.dart';voidmain(){returnrunApp(ModularApp(module:/*<MainModule>*/, child:/*<MainWidget>*/));}

ModularApp forces us to add a main Module and main Widget. What are we going to do next?This Widget does the initial setup so everything can work as expected. For more details go toModularApp doc.

💡 TIP: It's important thatModularApp is the first widget in your app!

Creating the Main Module

A module represents a set of Routes and Binds.

  • ROUTE: Page setup eligible for navigation.
  • BIND: Represents an object that will be available for injection to other dependencies.

We'll see more info about these topics further below.

We can have several modules, but for now, let's just create a main module calledAppModule:

import'package:flutter/material.dart';import'package:flutter_modular/flutter_modular.dart';voidmain(){returnrunApp(ModularApp(module:AppModule(), child:<MainWidget>));}classAppModuleextendsModule {@overrideList<Bind>get binds=> [];@overrideList<ModularRoute>get routes=> [];}

Note that the module is just a class that inherits from theModule class, overriding thebinds androutes properties.With this we have a route and injection mechanism separate from the application and can be both applied in a global context (as we are doing) or in a local context, for example, creating a module that contains only binds and routes only for a specific feature!

We've addedAppModule to ModularApp. Now we need an initial route, so let's create a StatelessWidget to serve as the home page.

import'package:flutter/material.dart';import'package:flutter_modular/flutter_modular.dart';voidmain(){returnrunApp(ModularApp(module:AppModule(), child:<MainWidget>));}classAppModuleextendsModule {@overrideList<Bind>get binds=> [];@overrideList<ModularRoute>get routes=> [ChildRoute('/', child: (context, args)=>HomePage()),  ];}classHomePageextendsStatelessWidget {Widgetbuild(BuildContext context){returnScaffold(      appBar:AppBar(title:Text('Home Page')),      body:Center(        child:Text('This is initial page'),      ),    );  }}

We've created a Widget calledHomePage and added its instances in a route calledChildRoute.

💡 TIP: There are two ModularRoute types:ChildRoute andModuleRoute.

  • ChildRoute: Serves to build a Widget.
  • ModuleRoute: Concatenates another module.

🧑‍💻 Contributing

Contributions are what make the open source community such an amazing place to learn, inspire, and create. Any contributions you make aregreatly appreciated.

If you have a suggestion that would make this better, please fork the repo and create a pull request. You can also simply open an issue with the appropriate tag.Don't forget to give the project a star! Thanks again!

  1. Fork the Project
  2. Create your Feature Branch (git checkout -b feature/AmazingFeature)
  3. Commit your Changes (git commit -m 'Add some AmazingFeature')
  4. Push to the Branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

Remember to include a tag, and to followConventional Commits andSemantic Versioning when uploading your commit and/or creating the issue.

(back to top)

💬 Contact

Flutterando Community

(back to top)


👥 Contributors

(back to top)

🛠️ Maintaned by


This fork version is maintained byFlutterando.

Releases

No releases published

Packages

No packages published

Languages

  • Dart70.0%
  • C++14.7%
  • CMake9.3%
  • HTML2.7%
  • Ruby1.2%
  • Swift1.2%
  • Other0.9%

[8]ページ先頭

©2009-2025 Movatter.jp