Download this source code for
5 USD


Download this source code for
5 USD


Download this source code for
5 USD


Download this source code for
5 USD

mustang

a framework to build flutter applications. following features are available out of the box.

  • state management
  • persistence
  • cache
  • file layout and naming standards
  • reduces boilerplate with open_mustang_cli

framework components

  • screen – screen is a reusable widget. it usually represents a screen in the app or a page in browser.

  • model – a dart class representing application data.

  • state – provides access to subset of models needed for a screen. it is a dart class with 1 or more model fields.

  • service – a dart class for async communication and business logic.

component communication

  • every screen has a corresponding service and a state. all three components work together to continuously
    rebuild the ui whenever there is a change in the application state.

    architecture

    1. screen reads state while building the ui
    2. screen invokes methods in the service as a response to user events (scroll, tap etc.,)
    3. service
      • reads/updates models in the wrenchstore
      • makes api calls, if needed
      • informs state if wrenchstore is mutated
    4. state informs screen to rebuild the ui
    5. back to step 1

persistence

persistence

by default, app state is maintained in memory by wrenchstore. when the app is terminated, the app state is lost
permanently. however, there are cases where it is desirable to persist and restore the app state. for example,

  • save and restore user’s session token to prevent user having to log in everytime
  • save and restore partial changes in a screen so that the work can be resumed from where the user has left off.

enabling persistence is simple and works transparently.

import 'package:xxx/src/models/serializers.dart' as app_serializer;

widgetsflutterbinding.ensureinitialized();

// in main.dart before calling runapp method,
// 1. enable persistence like below
wrenchstore.config(
  ispersistent: true,
  storename: 'myapp',
);

// 2. initialize persistence
directory dir = await getapplicationdocumentsdirectory();
await wrenchstore.initpersistence(dir.path);

// 3. restore persisted state before the app starts
await wrenchstore.restorestate(app_serializer.json2type, app_serializer.serializernames);

with the above change, app state (wrenchstore) is persisted to the disk and will be restored into wrenchstore when the app is started.

cache

cache

cache feature allows switching between instances of the same type on need basis.

persistence is a snapshot of the app state in memory (wrenchstore). however, there are times when data
need to be persisted but restored only when needed. an example would be a technician working on multiple jobs at the same time i.e, technician switches between jobs.
since the wrenchstore allows only one instance of a type, there cannot be two instances of the job object in the wrenchstore.

cache apis, available in services, make it easy to restore any instance into memory (wrenchstore).

  • future<void> addobjecttocache<t>(string key, t t)
    

    save an instance of type t in the cache. key is an identifier for one or more cached objects.

  • future<void> deleteobjectsfromcache(string key)
    

    delete all cached objects having the identifier key

  • static future<void> restoreobjects(
        string key,
        void function(
            void function<t>(t t) update,
            string modelname,
            string jsonstr,
        ) callback,
    )
    

    restores all objects in the cache identified by the key into memory wrenchstore and also into the persisted store
    so that the in-memory and persisted app state remain consistent.

  • bool itemexistsincache(string key)
    

    returns true if an identifier key exists in the cache, false otherwise.

model

  • a class annotated with appmodel

  • model name should start with $

  • initialize fields with initfield annotation

  • methods/getters/setters are not supported inside model classes

  • if a field should be excluded when a model is persisted, annotate that field with serializefield(false)

    @appmodel
    class $user {
      late string name;
    
      late int age;
    
      @initfield(false)
      late bool admin; 
    
      @initfield(['user', 'default'])
      late builtlist<string> roles;
      
      late $address address;  // $address is another model annotated with @appmodel
      
      late builtlist<$vehicle> vehicles;  // use immutable versions of list/map inside model classes
      
      @serializefield(false)
      late string errormsg; // errormsg field will not be included when $user model is persisted 
    }

state

  • a class annotated with screenstate

  • state name should start with $

  • fields of the class must be model classes

    @screenstate
    class $examplescreenstate {
      late $user user;
      
      late $vehicle vehicle;
    }

service

  • a class annotated with screenservice

  • provide state class as an argument to screenservice annotation, to create an association between state and service as shown below.

    @screenservice(screenstate: $examplescreenstate)
    class examplescreenservice {
      void getuser() {
        user user = wrenchstore.get<user>() ?? user();
          updatestate1(user);
        }
    }
  • service also provides following apis

    • updatestate – updates screen state and/or re-build the screen. to update the state without re-building the screen. set reload argument to false to update the state without re-building the screen.

      • updatestate()
      • updatestate1(t model1, { reload: true })
      • updatestate2(t model1, s model2, { reload: true })
      • updatestate3(t model1, s model2, u model3, { reload: true })
      • updatestate4(t model1, s model2, u mode3, v model4, { reload: true })
    • memoizescreen – invokes any method passed as argument only once.

      • t memoizescreen<t>(t function() methodname)
        // in the snippet below, getscreendata method caches the return value of getdata method, a future.
        // even when getdata method is called multiple times, method execution happens only the first time.
        future<void> getdata() async {
          common common = wrenchstore.get<common>() ?? common();
          user user;
          vehicle vehicle;
        
          ...   
        }
        
        future<void> getscreendata() async {
          return memoize(getdata);
        }
    • clearmemoizedscreen – clears value cached by memoizescreen method.

      • void clearmemoizedscreen()
        future<void> getdata() async {
          ...
        }
        
        future<void> getscreendata() async {
          return memoizescreen(getdata);
        }
        
        void resetscreen() {
          // clears future<void> cached by memoizescreen()
          clearmemoizedscreen();
        }

screen

  • use stateprovider widget to re-build the screen automatically when there is a change in state

    ...
    widget build(buildcontext context) {
      return stateprovider<homescreenstate>(
          state: homescreenstate(),
          child: builder(
            builder: (buildcontext context) {
              // state variable provides access to model fields declared in the homescreenstate class
              homescreenstate? state = stateconsumer<homescreenstate>().of(context);
              
              # even when this widget is built many times, only 1 api call 
              # will be made because the future from the service is cached
              schedulerbinding.instance?.addpostframecallback(
                (_) => homescreenservice().getscreendata(),
              );
    
              if (state?.common?.busy ?? false) {
                return spinner();
              }
    
              if (state?.counter?.errormsg.isnotempty ?? false) {
                return errorbody(errormsg: state.common.errormsg);
              }
                
              return _body(state, context);
            },
          ),
        );
      }

folder structure

  • folder structure of a flutter application created with this framework looks as below
      lib/
        - main.dart
        - src
          - models/
            - model1.dart
            - model2.dart
          - screens/
            - first/
              - first_screen.dart
              - first_state.dart
              - first_service.dart
            - second/
              - second_screen.dart
              - second_state.dart
              - second_service.dart
    
  • every screen needs a state and a service. so, screen, state, service files are grouped inside a directory
  • all model classes must be inside models directory

quick start

  • install flutter

      mkdir -p ~/lib && cd ~/lib
      
      flutter/flutter.git -b stable
    
      # add path in ~/.zshrc 
      export path=$path:~/lib/flutter/bin
      export path=$path:~/.pub-cache/bin
  • install mustang cli

      dart pub global activate open_mustang_cli
  • create flutter project

      cd /tmp
      
      flutter create quick_start
      
      cd quick_start
      
      # open the project in editor of your choice
      # vscode - code .
      # intellij - idea .
  • update pubspec.yaml

      ...
      dependencies:
        ...
        built_collection: ^5.1.1
        built_value: ^8.1.3
        mustang_core: ^1.0.2
        path_provider: ^2.0.6
    
      dev_dependencies:
        ...
        build_runner: ^2.1.4
        mustang_codegen: ^1.0.3    
  • install dependencies

      flutter pub get
  • generate files for a screen called counter. following command creates file representing a model, and also files representing screen, service and state.

      omcli -s counter
  • generate runtime files and watch for changes.

      omcli -w # omcli -b generates runtime files once
  • update the generated counter.dart model

      class $counter {
        @initfield(0)
        late int value;
      }
  • update the generated counter_screen.dart screen

      import 'package:flutter/material.dart';
      import 'package:mustang_core/mustang_widgets.dart';
      
      import 'counter_service.dart';
      import 'counter_state.state.dart';
      
      class counterscreen extends statelesswidget {
        const counterscreen({
          key key,
        }) : super(key: key);
          
        @override
        widget build(buildcontext context) {
          return stateprovider<counterstate>(
            state: counterstate(),
            child: builder(
              builder: (buildcontext context) {
                counterstate? state = stateconsumer<counterstate>().of(context);
                return _body(state, context);
              },
            ),
          );
        }
      
        widget _body(counterstate? state, buildcontext context) {
          int counter = state?.counter?.value ?? 0;
          return scaffold(
            appbar: appbar(
              title: text('counter'),
            ),
            body: center(
              child: column(
                children: [
                  padding(
                    padding: const edgeinsets.all(8.0),
                    child: text('$counter'),
                  ),
                  elevatedbutton(
                    onpressed: counterservice().increment,
                    child: const text('increment'),
                  ),
                ],
              ),
            ),
          );
        }
      }
  • update the generated counter_service.dart service

      import 'package:mustang_core/mustang_core.dart';
      import 'package:quick_start/src/models/counter.model.dart';
          
      import 'counter_service.service.dart';
      import 'counter_state.dart';
          
      @screenservice(screenstate: $counterstate)
      class counterservice {
        void increment() {
          counter counter = wrenchstore.get<counter>() ?? counter();
          counter = counter.rebuild((b) => b.value = (b.value ?? 0) + 1);
          updatestate1(counter);
        }
      }
  • update main.dart

      ...
    
      widget build(buildcontext context) {
        return materialapp(
          title: 'flutter demo',
          theme: themedata(
            ...
            primaryswatch: colors.blue,
          ),
          home: counterscreen(), // point to counter screen
        );
      }
    
      ...

Download this source code for
5 USD


Download this source code for
5 USD


Download this source code for
5 USD


Download this source code for
5 USD

Comments are closed.