What is Flutter Modular?

What is Flutter Modular?

Application project grows and becomes complex, it’s hard to keep your code and project structure mantainableand 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).

What is Flutter Modular

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.

Advantage :

  1. Automatic Memory Management.
  2. Dependency Injection.
  3. Dynamic Routing.
  4. Code Modularization.
  5. Route animation.

Must be :

  1. navigatorKey: Modular.navigatorKey: That is add MaterialApp
  2. Modular.to.pushNamed(‘/signUp’): New screen open
  3. Modular.to.pushReplacementNamed(‘/login/’): Splash screen after
  4. class _SplashPageState extends ModularState<SplashPage, SplashStore> {}: Use ‘controller’ variable to access controller

Repository :

They are objects responsible for executing connections with APIs and must be injected into controllers or stores. It is not good for a controller to execute a rule that accesses the internet or an internal component such as a database, for this use Repository or Services.

Services :

Used to broker a connection with components or hardware such as Bluetooth, database, GPS, etc …

MainModule :

Everything that is placed in the Binds, can be accessed in any other module.

bootstrap access the main widget (MaterialApp)of application.

ChildModule :

Creating a tree of Modules totally independent from each other, with their own Binds and routers, that’s why we call ChildModule, and can be a child of MainModule or even another ChildModule.

Bind :

Bind has this structure because it can receive the injection during the call of classes and also provides “Lazy Loading”, that is, the class is instantiated only when it is called for the first time, after that it starts to obey certain parameters, which Singleton pattern does during the lifetime of the module that has been implemented !.

Bind(this.inject, {this.singleton = true,
this.lazy = true})

lazy: When ‘true’, the object is instantiated only the first time it is called.When ‘false’, the object is instantiated along with the module.

Multiple bind in flutter:

Bind<IAPIService>((i) => Repository(i.get<Firestore>(),i.get<FirebaseAuth>())),

Argument pass :
flutter_modular 2 way argument pass:

1) main module
2) child module

main module :

Router('/other/:text', child: (_, args) => OtherPage(text: args.params['text'])), 
Modular.to.pushNamed("/other/${homeController.text}");

child module :

Router(contactUsRoute, child: (context, args) => ContactUsPage(title: args.data), transition: TransitionType.rotate)

Modular.to.pushNamed(contactUsRoute, arguments: contactUsRoute);

(OR)

Navigator.pushNamed(context, contactUsRoute, arguments: titleContactUs);

flutter_mobx store create using terminal command

  1. flutter pub get
  2. flutter packages pub run build_runner build –delete-conflicting-outputs
  3. flutter packages pub run build_runner watch
  4. flutter packages pub run build_runner clean && flutter packages pub run build_runner build –delete-conflicting-outputs

Live Event Application in flutter:

Live Event application provide the functionality:

1) Mobx in flutter

2) flutter_modular in flutter

3) firebase (firestore) in flutter

4) User profile image upload firebase in flutter

5) Login

6) Register

7) Insert, update

8) Every validation call the function mobx

9) Profile Edit

Screenshot :1

Screenshot :2

Screenshot :3

Screenshot :4

Screenshot :5

Complex Observables in mobx :

With Jacob Moura contribution, now have extensions that transform List, Set, Map, Future and Stream to an observable.

1) Observable {List, Set, Map}: A Iterable that notifies the observers in every manipulation.

2) ObservableFuture: Wrap a Future in an observable and listen its value inside the Observer Widget, without the FutureBuilder necessity.

3) ObservableStream: Wrap a Stream in an observable and listen its value inside the Observer Widget, without the StreamBuilder necessity.

Firebase in flutter :

How to add firebase and get unique or documentId in flutter :

varaddSignUp = await _fireStore.collection(signUpTable).add({
userNameParam: userName.toLowerCase(),
emailParam: email.toLowerCase(),
socialIdParam: socialId,
passwordParam: password,
mobileParam: mobile,
profilePictureParam: '',
whereSignUpParam: whereSignUp,
notificationParam: '',
addressParam: '',
createDateParam: DateTime.now().toIso8601String(),
statusParam: true,
      });
returnaddSignUp.documentID;
    } else {
return null;
    }

Live data retrieve in flutter :

Stream<List<ContactUsResponse>>contactUs() {
returnFirestore().collection(contactUsTable).snapshots().map((docs) => docs
        .documents
        .map<ContactUsResponse>(
            (employees) =>ContactUsResponse.fromDocument(employees))
        .toList());
  }

Filter in firebase :

How to login in flutter using the firebase :

varquerySnapshot = await _fireStore
.collection(signUpTable)
    .where(emailParam, isEqualTo: email)
    .where(passwordParam, isEqualTo: password)
    .limit(1)
    .getDocuments();

return querySnapshot;

querySnapshot.documents[0].documentID profile unique id threw firebase.

Flutter modular structure :

1) runApp: runApp calling the AppModule that is main modular.

2) AppModule: AppModule bind the service, Router and bootstrap for example LocalStore (SavePref), Repository.

3) ChildMoule: That is contain bind the page related functionality. For example LoginModule.

4) bootstrap is MaterialApp call. That is must add inMaterialApponGenerateRoute: Modular.generateRoute.

For example :

MaterialApp(
onGenerateRoute: Modular.generateRoute,
    );

5) Repository is contains web service, firebase and your logic that communication using Store. Store is mobx pattern in flutter.

For example :

Login View – Button press login -> calling mobx store ->Repository (common share data).

6) Route is calling must Modular using.

mobx pattern using firebase stream data filter (search) :

class ContactResponse {
  String uid, appName, webSite, email, mobile, address;

  ContactResponse(
      this.appName, this.webSite, this.email, this.mobile, this.address);

  ContactResponse.fromJson(Map<String, dynamic> map) {
    this.appName = map['appName'];
    this.webSite = map['webSite'];
    this.email = map['email'];
    this.mobile = map['mobile'];
    this.address = map['address'];
  }
}

Stream<QuerySnapshot> contactUs() {
  return _fireStore.collection(contactUsTable).snapshots();
}

ObservableList<ContactResponse> contactUsList = ObservableList<ContactResponse>.of([]);

  @action
  contactUs() {
    _repository.contactUs().listen((QuerySnapshot snapshot) => contactUsList =
        ObservableList.of(snapshot.documents
            .map((documentSnapshot) =>
                ContactResponse.fromJson(documentSnapshot.data))
            .toList()));
  }

call feature in firebase :

@observable
ObservableList<Category> categories = ObservableList<Category>.of([]);

QuerySnapshot query = await _api.fetchCategories;
  categories = ObservableList.of(
    query.documents
        .map((DocumentSnapshot doc) => Category.fromJson(doc.data))
        .toList(),
  );

mobx using StreamController :

import 'dart:async';
import 'dart:math';
import 'package:mobx/mobx.dart';
part 'random_store.g.dart';

class RandomStore = _RandomStore with _$RandomStore;

abstract class _RandomStore with Store {
  _RandomStore() {
    _streamController = StreamController<int>();

    _timer = Timer.periodic(const Duration(seconds: 1),
        (_) => _streamController.add(_random.nextInt(100)));

    randomStream = ObservableStream(_streamController.stream);
  }

  Timer _timer;
  final _random = Random();

  StreamController<int> _streamController;

  ObservableStream<int> randomStream;

  // ignore: avoid_void_async
  void dispose() async {
    _timer.cancel();
    await _streamController.close();
  }
}

Observer(
           builder: (_) {
             final value = store.randomStream.value;

             return Text(
               '${value == null ? '---' : value}',
               style: const TextStyle(fontSize: 96),
             );
           },
         ),

Click Here to Download Area Event Source Code

  Click Here to Download Live Event Source Code

The flutter tutorial  is a website that bring you the latest and amazing resources of code. All the languages codes are included in this website. The languages like flutter, android, java,kotlin etc.with the help of this languages any user can develop the beautiful application

For more information about Flutter. visit www.fluttertutorial.in