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 ascreen
. it is a dart class with 1 or moremodel
fields. -
service – a dart class for async communication and business logic.
component communication
-
every
screen
has a correspondingservice
and astate
. all three components work together to continuously
rebuild the ui whenever there is a change in the application state.screen
readsstate
while building the uiscreen
invokes methods in theservice
as a response to user events (scroll
,tap
etc.,)service
- reads/updates
models
in thewrenchstore
- makes api calls, if needed
- informs
state
ifwrenchstore
is mutated
- reads/updates
state
informsscreen
to rebuild the ui- back to step 1
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
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 service
s, 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 memorywrenchstore
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 identifierkey
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 insidemodel
classes -
if a field should be excluded when a
model
is persisted, annotate that field withserializefield(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 toscreenservice
annotation, to create an association betweenstate
andservice
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 thestate
without re-building the screen. setreload
argument tofalse
to update thestate
without re-building thescreen
.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 bymemoizescreen
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 thescreen
automatically when there is a change instate
... 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 astate
and aservice
. so,screen, state, service
files are grouped inside a directory - all
model
classes must be insidemodels
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 amodel
, and also files representingscreen
,service
andstate
.omcli -s counter
-
generate runtime files and watch for changes.
omcli -w # omcli -b generates runtime files once
-
update the generated
counter.dart
modelclass $counter { @initfield(0) late int value; }
-
update the generated
counter_screen.dart
screenimport '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
serviceimport '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 ); } ...
Comments are closed.