CI & Coverage Coverage Status

All Contributors

Flutter Modular

flutter_modular

This README is also available in Brazilian Portuguese.

What is Flutter Modular?

As an application project grows and becomes complex, it's hard to keep your code and project structure mantainable and reusable. Modular provides a bunch of Flutter-suiting solutions to deal with this problem, like dependency injection, routing system and the "disposable singleton" system (that is, Modular disposes the injected module automatically as it is out of scope).

Modular's dependency injection system has out-of-the-box support for any state management system, managing your application memory usage.

Modular Structure

Modular structure consists in decoupled and independent modules that will represent the features of the application. Each module is located in its own directory, and controls its own dependencies, routes, pages, widgets and business logic. Consequently, you can easily detach one module from your project and use it wherever you want.

Modular Pillars

These are the main aspects that Modular focus on:

  • Automatic Memory Management.
  • Dependency Injection.
  • Dynamic Routing.
  • Code Modularization.

Examples

Getting started with Modular

Installation

Open your project's pubspec.yaml and add flutter_modular as a dependency:

dependencies:
    flutter_modular: any

You can also provide the git repository as source instead, to try out the newest features and fixes:

dependencies:
    flutter_modular:
        git:
            url: https://github.com/Flutterando/modular

Using in a new project

To use Modular in a new project, you will have to make some initial setup:

  1. Create your main widget with a MaterialApp and set its initialRoute. On onGenerateroute, you will have to provide Modular's routing system (Modular.generateRoute), so it can manage your routes.
//  app_widget.dart
import 'package:flutter/material.dart';
import 'package:flutter_modular/flutter_modular.dart';

class AppWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      // set your initial route
      initialRoute: "/",
      // add Modular to manage the routing system
      onGenerateRoute: Modular.generateRoute,
    );
  }
}
  1. Create your project's main module file extending MainModule:
// app_module.dart
class AppModule extends MainModule {

  // Provide a list of dependencies to inject into your project
  @override
  List<Bind> get binds => [];

  // Provide all the routes for your module
  @override
  List<Router> get routers => [];

  // Provide the root widget associated with your module
  // In this case, it's the widget you created in the first step
  @override
  Widget get bootstrap => AppWidget();
}
  1. In your main.dart, wrap your main module in ModularApp to initialize it with Modular:
// main.dart
import 'package:flutter/material.dart';
import 'package:flutter_modular/flutter_modular.dart';

import 'app/app_module.dart';

void main() => runApp(ModularApp(module: AppModule()));
  1. Done! Your app is set and ready to work with Modular!

Adding routes

Your module's routes are provided by overriding the routers getter:

// app_module.dart
class AppModule extends MainModule {

  // Provide a list of dependencies to inject into your project
  @override
  List<Bind> get binds => [];

  // Provide all the routes for your module
  @override
  List<Router> get routers => [
      Router('/', child: (_, __) => HomePage()),
      Router('/login', child: (_, __) => LoginPage()),
  ];

  // Provide the root widget associated with your module
  @override
  Widget get bootstrap => AppWidget();
}

To push your route to your app, you can use Navigator.pushNamed:

Navigator.pushNamed(context, '/login');

Alternatively, you can use Modular.to.pushNamed, in which you don't have to provide a BuildContext:

Modular.to.pushNamed('/login');

Use Modular.to for literal paths or Modular.link for routes in current module:

// Modules Home → Product
Modular.to.pushNamed('/home/product/list');
Modular.to.pushNamed('/home/product/detail/:id');

// Inside Product module, use Modular.link and navigate between Product module routes
Modular.link.pushNamed('/list');
Modular.link.pushNamed('/detail/:id');

Dynamic routes

You can use the dynamic routing system to provide parameters to your Router:

// Use :parameter_name syntax to provide a parameter in your route.
// Route arguments will be available through `args`, and may be accessed in `params` property,
// using square brackets notation (['parameter_name']).

@override
List<Router> get routers => [
  Router(
    '/product/:id',
    child: (_, args) => Product(id: args.params['id']),
  ),
];

The parameter will, then, be pattern-matched when calling the given route. For example:

// In this case, `args.params['id']` will have the value `1`.
Modular.to.pushNamed('/product/1');

This notation, however, is only valid for simple literals. If you want to pass a complex object to your route, provide it in arguments parameter:

Modular.to.pushNamed('/product', arguments: ProductModel());

And it will be available in the args.data property instead of args.params:

@override
List<Router> get routers => [
  Router(
    '/product',
    child: (_, args) => Product(model: args.data),
  ),
];

Route guard

Route guards are middleware-like objects that allow you to control the access of a given route from other route. You can implement a route guard by making a class that implements RouteGuard.

For example, the following class will only allow a redirection from /admin route:

class MyGuard implements RouteGuard {
  @override
  bool canActivate(String url) {
    if (url != '/admin'){
      // Return `true` to allow access
      return true;
    } else {
      // Return `false` to disallow access
      return false
    }
  }
}

To use your RouteGuard in a route, pass it to the guards parameter:

@override
List<Router> get routers => [
  Router('/', module: HomeModule()),
  Router(
    '/admin',
    module: AdminModule(),
    guards: [MyGuard()],
  ),
];

If placed on a module route, RouterGuard will be global to that route.

Route transition animation

You can choose which type of animation you want to be used on your pages transition by setting the Router's transition parameter, providing a TransitionType.

Router('/product',
  module: AdminModule(),
  transition: TransitionType.fadeIn,
), //use for change transition

If you use transition in a module, all routes in that module will inherit this transition animation.

Custom transition animation route

You can also use a custom transition animation by setting the Router parameters transition and customTransition with TransitionType.custom and your CustomTransition, respectively:

Router('/product',
  module: AdminModule(),
  transition: TransitionType.custom,
  customTransition: myCustomTransition,
),

For example, this is a custom transition that could be declared in a separated file and used in the customTransition parameter:

import 'package:flutter/material.dart';
import 'package:flutter_modular/flutter_modular.dart';

CustomTransition get myCustomTransition => CustomTransition(
    transitionDuration: Duration(milliseconds: 500),
    transitionBuilder: (context, animation, secondaryAnimation, child){
      return RotationTransition(turns: animation,
        child: SlideTransition(
          position: Tween<Offset>(
            begin: const Offset(-1.0, 0.0),
            end: Offset.zero,
          ).animate(animation),
          child: ScaleTransition(
            scale: Tween<double>(
              begin: 0.0,
              end: 1.0,
            ).animate(CurvedAnimation(
              parent: animation,
              curve: Interval(
                0.00,
                0.50,
                curve: Curves.linear,
              ),
            ),
            ),
            child: child,
          ),
        ),
      )
      ;
    },
  );

Grouping routes

You can group routes that contains one or more common properties. Properties like guards, transition and customTransition can be provided both for single routes and groups of routes:

List<Router> get routers => [
  Router('/', module: HomeModule()),
  Router.group(
    guards: [MyGuard()],
    routes: [
      Router("/admin", module: AdminModule()),
      Router("/profile", module: ProfileModule()),
    ],
  ),
);

Router generic types

You can return values from navigation, just like .pop. To achieve this, pass the type you expect to return as type parameter to Router:

@override
List<Router> get routers => [
  // This router expects to receive a `String` when popped.
  Router<String>('/event', child: (_, __) => EventPage()),
]

Now, use .pop as you would with Navigator.pop:

// Push route
String name = await Modular.to.pushNamed<String>();

// And pass the value when popping 
Modular.to.pop('Jacob Moura');

The routing system can recognize what is in the URL and navigate to a specific part of the application. Dynamic routes apply here as well. The following URL, for instance, will open the Product view, with args.params['id'] set to 1.

https://flutter-website.com/#/product/1

Dependency Injection

You can inject any class into your module by overriding the binds getter of your module. Typical examples to inject are BLoCs, ChangeNotifier classes or stores.

A Bind object is responsible for configuring the object injection.

class AppModule extends MainModule {

  // Provide a list of dependencies to inject into your project
  @override
  List<Bind> get binds => [
    Bind((_) => AppBloc()), // Injecting a BLoC
    Bind((_) => Counter()), // Injecting a ChangeNotifier class
  ];

  // Provide all the routes for your module
  @override
  List<Router> get routers => [
    Router('/', child: (_, args) => HomePage()),
    Router('/login', child: (_, args) => LoginPage()),
  ];
  
  // Provide the root widget associated with your module
  @override
  Widget get bootstrap => AppWidget();
}

Retrieving your injected dependencies in the view

Let's assume the following BLoC has been defined and injected in our module (as in the previous example):

import 'package:flutter_modular/flutter_modular.dart' show Disposable;

// In Modular, `Disposable` classes are automatically disposed when out of the module scope.

class AppBloc extends Disposable {
  final controller = StreamController();

  @override
  void dispose() {
    controller.close();
  }
}

There are several ways to retrieve our injected AppBloc.

class HomePage extends StatelessWidget {

  @override
  Widget build(BuildContext context) {

    // You can use the object Inject to retrieve..
  
    final appBloc = Modular.get<AppBloc>();
    //...
  }
}

By default, objects in Bind are singletons and lazy. When Bind is lazy, the object will only be instantiated when it is called for the first time. You can use 'lazy: false' if you want your object to be instantiated immediately (eager-loaded).

Bind((i) => OtherWidgetNotLazy(), lazy: false),

If you want the injected object to be instantiated every time it is called (instead of being a singleton instance), you may simple pass false to the singleton parameter:

Bind((i) => OtherWidgetNotLazy(), singleton: false),

Using Modular widgets to retrieve your classes

ModularState

class MyWidget extends StatefulWidget {
  @override
  _MyWidgetState createState() => _MyWidgetState();
}

class _MyWidgetState extends ModularState<MyWidget, HomeController> {

  // Variable controller
  // Automatic dispose of HomeController

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Modular"),
      ),
      body: Center(child: Text("${controller.counter}"),),
    );
  }
}

Consuming a ChangeNotifier class

Example of a ChangeNotifier class:

import 'package:flutter/material.dart';

class Counter extends ChangeNotifier {
  int counter = 0;

  increment() {
    counter++;
    notifyListeners();
  }
}

you can use the Consumer to manage the state of a widget block.

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {

    return Scaffold(
      appBar: AppBar(title: Text("Home")),
      body: Center(
        // By passing your ChangeNotifier class as type parameter, the `builder` will be called every time `notifyListeners` is called
        child: Consumer<Counter>(
          builder: (context, value) {
            return Text('Counter ${value.counter}');
          }
        ),
      ),
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.add),
        onPressed: () {
          // You can retrive the class directly with `get` and execute the increment method
          get<Counter>().increment();
        },
      ),
    );
  }
}

Creating child modules

You can create as many modules in your project as you wish, but they will be dependent of the main module. To do so, instead of inheriting from MainModule, you should inherit from ChildModule:

class HomeModule extends ChildModule {
  @override
  List<Bind> get binds => [
    Bind((i) => HomeBloc()),
  ];

  @override
  List<Router> get routers => [
    Router('/', child: (_, args) => HomeWidget()),
    Router('/list', child: (_, args) => ListWidget()),
  ];

  static Inject get to => Inject<HomeModule>.of();
}

You may then pass the submodule to a Router in your main module through the module parameter:

class AppModule extends MainModule {

  @override
  List<Router> get routers => [
    Router('/home', module: HomeModule()),
  ];
}

We recommend that you split your code in various modules, such as LoginModule, and place all the routes related to this module within it. By doing so, it will much easier to maintain and share your code with other projects.

WidgetModule

WidgetModule has the same structure as MainModule/ChildModule. It is very useful if you want to have a TabBar with modular pages.

class TabModule extends WidgetModule {

    @override
  List<Bind> get binds => [
    Bind((i) => TabBloc(repository: i.get<TabRepository>())),
    Bind((i) => TabRepository()),
  ];

  Widget get view => TabPage();

}

RouterOutlet

A RouterOutlet may be used if you need a routing system that is totally detached from the main routing system. This is useful, for example, when you need an element to have its own set of routes, even though it is inside a page on the main route.

A practical example of this is its use in a TabBar or Drawer:

PageView(
  controller: controller
  children: [
    RouterOutlet(
      module: Tab1Module()
    ),
    RouterOutlet(
      module: Tab2Module()
    ),
    RouterOutlet(
      module: Tab3Module()
    ),
  ]
),

NOTE: Navigation within these modules are only supported through Navigator.of(context) using literal routes paths.

Lazy loading

Another benefit you get when working with modules is that they are (by default) lazily-loaded. This means that your dependency injection will only be available when you navigate to a module, and when you exit that module, Modular will manage the resources disposal by removing all injections and executing dispose() (if available) on each injected dependency.

Unit test

You can use the dependency injection system to replace a Bind with a mocked Bind, like, for example, a mocked repository. You can also do it using "Inversion of Control" (IoC).

For example, you can make a repository interface (ILocalStorage) that satisfies your repository contract requirement and pass it as a paramter type to Bind.

@override
List<Bind> get binds => [
  Bind<ILocalStorage>((i) => LocalStorageSharePreferences()),
];

Then, on your test file, you import flutter_modular_test and provide your mocked repository in the initModule as a replacement of your concrete repository:

import 'package:flutter_modular/flutter_modular_test.dart';
import 'package:flutter_test/flutter_test.dart';

main() {
  test('change bind', () {
    initModule(AppModule(), changeBinds: [
      Bind<ILocalStorage>((i) => LocalMock()),
    ]);
    expect(Modular.get<ILocalStorage>(), isA<LocalMock>());
  });
}

We though it would be interesting to provide a native way to mock the navigation system when used with Modular.to and Modular.link. To do this, you may just implement IModularNavigator and pass your implementation to Modular.navigatorDelegate.

// Modular.to and Modular.link will be called MyNavigatorMock implements!
Modular.navigatorDelegate = MyNavigatorMock();

DebugMode

By default, Modular prints a lot of debug info in the console. You may disable this by disabling debugMode:

Modular.debugMode = false;

Roadmap

This is our current roadmap. Please, feel free to request additions/changes.

FeatureProgress
DI by Module
Routes by Module
Widget Consume for ChangeNotifier
Auto-dispose
Integration with flutter_bloc
Integration with mobx
Multiple routes
Pass arguments by route
Pass url parameters per route
Route Transition Animation

Features and bugs

Please send feature requests and bugs at the issue tracker.

This README was created based on templates made available by Stagehand under a BSD-style license.

Contributors ✨

Our thanks goes out to all these wonderful people (emoji key):


Jacob Moura

🚧 💻 👀

Vilson Blanco Dauinheimer

💻 📖 👀

Pedro Massango

💻 📖 🤔

Kelven I. B. Galvão

📖 🌍

David Araujo

💻

Alvaro Vasconcelos

💻

André de Almeida

💻 📖

Alberto Monteiro

💻 ⚠️

Guilherme Nepomuceno de Carvalho

💻

Eduardo Lúcio

💻

Ascênio

💻 📖

Wemerson Couto Guimarães

💻

Alan D. Cabrera

💻

Jean Lucas

💻

Moacir Schmidt

📖

Felipe Marra

📖 🌍

Adem Kouki

📖

Gabriel Sávio - Flutterando

💻

Tiagosito

💻

Mateus Felipe C. C. Pinto

🌍 📖

Pierre Grimaud

📖

Toshi Ossada

📖 💻

This project follows the all-contributors specification. Contributions of any kind are welcome!

Libraries

flutter_modular
flutter_modular_test