built_viewmodel_flutter_built_redux 1.2.2

  • README.md
  • CHANGELOG.md
  • Example
  • Installing
  • Versions
  • 52

built_viewmodel.dart

The built_viewmodel.dart package provides a way to create ViewModel classes. It is a little bit inspired by the Android ViewModel but just a little bit ;-)

Usually, you call setState() whenever the state of the Widget should change. But in my opinion, it is not a good idea to call setState() when just a small part of the whole state has changed (read more: How fast is Flutter? I built a stopwatch app to find out., Avoiding Empty State Callbacks).

This package creates lots of Streams (as much as you need) to feed StreamBuilders.

Let's start

Create an abstract class, e.g. MyHomePageViewModel:

library main;

import 'dart:async';

import 'package:built_viewmodel/built_viewmodel.dart';

part 'main.g.dart';

abstract class MyHomePageViewModel implements ViewModel<MyHomePageViewModelController> {


  factory MyHomePageViewModel() = _$MyHomePageViewModel;
  MyHomePageViewModel._();
}

And add a reference of it to the Widget:

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final MyHomePageViewModel model = new MyHomePageViewModel();
  final String title;

  @override
  _MyHomePageState createState() {
    model.setCounter(0);
    return new _MyHomePageState();
  }
}

For now, the ViewModel makes nothing. You have to add your needed stream(s):

abstract class MyHomePageViewModel implements ViewModel<MyHomePageViewModelController> {

  Stream<int> get counter;   // new

  factory MyHomePageViewModel() = _$MyHomePageViewModel;
  MyHomePageViewModel._();

You also need to add a code generator. Create a tool/build.dart file with the following content:

import 'dart:async';

import 'package:build_config/build_config.dart';
import 'package:build_runner/build_runner.dart';
import 'package:built_viewmodel_generator/built_viewmodel_generator.dart';
import 'package:source_gen/source_gen.dart';

final builders = [
  applyToRoot(
    new PartBuilder([
      new BuiltViewModelGenerator(),
    ]),
    generateFor: const InputSet(
      include: const [
        'lib/*.dart',
      ],
    ),
  ),
];

Future main(List<String> args) async {
  await build(
    builders,
    deleteFilesByDefault: true,
    verbose: false,
  );
}

Execute the tool/build.dart file and it will generate a main.g.dart file which has all the logic for your stream(s).

Use the stream

To use the stream(s) you need a StreamBuilder where you have to set the stream to the one from the ViewModel:

new StreamBuilder(
  stream: widget.model.counter,
  builder: (BuildContext context, AsyncSnapshot<int> snapshot) {
    if (snapshot.hasError) return new Text('Error: ${snapshot.error}');
    switch (snapshot.connectionState) {
      case ConnectionState.none:
        return new Text('not connected');
      case ConnectionState.waiting:
        return new Text('awaiting interaction...');
      case ConnectionState.active:
        return new Text('counter: ${snapshot.data}');
      case ConnectionState.done:
        return new Text('counter: ${snapshot.data} (closed)');
      default:
        throw "Unknown: ${snapshot.connectionState}";
    }
  },
),

Whenever you send a new value to the stream the content of the StreamBuilder will change but only this small part and not the whole state.

To do that add a void setCounter(int value) method to the ViewModel ...

abstract class MyHomePageViewModel implements ViewModel<MyHomePageViewModelController> {
  Stream<int> get counter;

  void setCounter(int value) => controller.counter.add(value);   // new

  factory MyHomePageViewModel() = _$MyHomePageViewModel;
  MyHomePageViewModel._();
}

... and just call it.

Don't forget ...

... to call dispose()

Add this to your State class

@override
void dispose() {
  widget.model.dispose();
  super.dispose();
}

Advanced feature

Sometimes you need to know the state of the stream, for example, to start a download.

You can create methods and annotate them with one of this annotations: @OnListenHandler, @OnPauseHandler, @OnResumeHandler, @OnCancelHandler. These annotations have a name parameter which must match with the name of the stream.

For example, if you have a counter stream Stream<int> get counter, and you want to know when something is listening for it the annotation should look like this: @OnListenHandler('counter').

abstract class MyHomePageViewModel implements ViewModel<MyHomePageViewModelController> {
  Stream<int> get counter;

  @OnListenHandler('counter')                           // new
  onListen() => print('start listening for updates');   // new

  void setCounter(int value) => controller.counter.add(value);

  factory MyHomePageViewModel() = _$MyHomePageViewModel;

  MyHomePageViewModel._();
}

You can find the full example here.

1.2.1 - 2018/04/10

  • small enhancements

1.2.0 - 2018/04/09

1.1.1 - 2018/04/04

  • handle import prefixes
  • optimise code generator to pass static analysis check

1.1.0 - 2018/04/03

  • API breaking change: rename listener classes to match Dart naming guide

1.0.1 - 2018/04/02

  • small enhancements

1.0.0 - 2018/04/01

  • first release

example/lib/main.dart

// Copyright (c) 2018., Ralph Bergmann.
// All rights reserved. Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

library main;

import 'dart:async';

import 'package:built_redux/built_redux.dart';
import 'package:built_value/built_value.dart';
import 'package:built_viewmodel/built_viewmodel.dart';
import 'package:built_viewmodel_flutter_built_redux/built_viewmodel_flutter_built_redux.dart';
import 'package:flutter/material.dart' hide Builder;
import 'package:flutter_built_redux/flutter_built_redux.dart';

part 'main.g.dart';

void main() => runApp(new MyApp());

class IncrementAction {}

abstract class AppState implements Built<AppState, AppStateBuilder> {
  factory AppState() => new _$AppState._(count: 0);

  AppState._();

  int get count;
}

abstract class AppActions extends ReduxActions {
  factory AppActions() => new _$AppActions();

  AppActions._();

  ActionDispatcher<Null> get increment;
}

ReducerBuilder<AppState, AppStateBuilder> reducerBuilder = new ReducerBuilder<AppState, AppStateBuilder>()
  ..add(AppActionsNames.increment, (s, a, b) => b.count++);

class MyApp extends StatelessWidget {
  final Store<AppState, AppStateBuilder, AppActions> store = new Store<AppState, AppStateBuilder, AppActions>(
    reducerBuilder.build(),
    new AppState(),
    new AppActions(),
  );

  Widget build(BuildContext context) => new ReduxProvider(
        store: store,
        child: new MaterialApp(
          title: 'Flutter Demo',
          theme: new ThemeData(primarySwatch: Colors.blue),
          home: new MyHomePage(title: 'Flutter Demo Home Page'),
        ),
      );
}

class MyHomePage extends StatelessWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final MyHomePageViewModel model = new MyHomePageViewModel();
  final String title;

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text(title),
      ),
      body: new ViewModelConnector(
        viewModel: model,
        onInit: (MyHomePageViewModel viewModel) => viewModel.setCounter(0),
        builder: (MyHomePageViewModel viewModel) => new Center(
              child: new Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  new Text('You have pushed the button this many times:'),
                  new StreamBuilder(
                    stream: viewModel.counter,
                    builder: (BuildContext context, AsyncSnapshot<int> snapshot) {
                      if (snapshot.hasError) return new Text('Error: ${snapshot.error}');
                      switch (snapshot.connectionState) {
                        case ConnectionState.none:
                          return new Text('not connected');
                        case ConnectionState.waiting:
                          return new Text('awaiting interaction...');
                        case ConnectionState.active:
                          return new Text('counter: ${snapshot.data}');
                        case ConnectionState.done:
                          return new Text('counter: ${snapshot.data} (closed)');
                        default:
                          throw "Unknown: ${snapshot.connectionState}";
                      }
                    },
                  ),
                ],
              ),
            ),
      ),
      floatingActionButton: new FloatingActionButton(
        onPressed: () => model.increaseCounter(),
        tooltip: 'Increment',
        child: new Icon(Icons.add),
      ),
    );
  }
}

abstract class MyHomePageViewModel extends ViewModel<MyHomePageViewModelController>
    with ViewModelFlutterBuiltReduxMixin<AppState, AppStateBuilder, AppActions> {
  Stream<int> get counter;

  @OnListenHandler('counter')
  void onListen() => print('start listening');

  @OnCancelHandler('counter')
  void onCancel() => print('cancel listening');

  void setCounter(int value) => controller.counter.add(value);

  void increaseCounter() => actions?.increment();

  @override
  void onStateChanged(StoreChange<AppState, AppStateBuilder, dynamic> stateChange) {
    setCounter(stateChange.next.count);
  }

  factory MyHomePageViewModel() = _$MyHomePageViewModel;

  MyHomePageViewModel._();
}

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:


dependencies:
  built_viewmodel_flutter_built_redux: "^1.2.2"

2. Install it

You can install packages from the command line:

with Flutter:


$ flutter packages get

Alternatively, your editor might support flutter packages get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


      import 'package:built_viewmodel_flutter_built_redux/built_viewmodel_flutter_built_redux.dart';
  
Version Uploaded Documentation Archive
1.2.2 Apr 12, 2018 Go to the documentation of built_viewmodel_flutter_built_redux 1.2.2 Download built_viewmodel_flutter_built_redux 1.2.2 archive
1.2.1 Apr 10, 2018 Go to the documentation of built_viewmodel_flutter_built_redux 1.2.1 Download built_viewmodel_flutter_built_redux 1.2.1 archive
1.2.0 Apr 9, 2018 Go to the documentation of built_viewmodel_flutter_built_redux 1.2.0 Download built_viewmodel_flutter_built_redux 1.2.0 archive

Analysis

We analyzed this package on Jun 23, 2018, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.0.0-dev.63.0
  • pana: 0.11.3
  • Flutter: 0.5.4

Scores

Popularity:
Describes how popular the package is relative to other packages. [more]
10 / 100
Health:
Code health derived from static analysis. [more]
97 / 100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
90 / 100
Overall score:
Weighted score of the above. [more]
52
Learn more about scoring.

Platforms

Detected platforms: Flutter

References Flutter, and has no conflicting libraries.

Suggestions

  • Running dartdoc failed.

    Make sure dartdoc runs without any issues.

  • Fix analysis and formatting issues.

    Analysis or formatting checks reported 1 hint.

    Run flutter format to format lib/built_viewmodel_flutter_built_redux.dart.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2-0-0-dev <2.0.0
built_viewmodel ^1.2.2 1.2.3
flutter 0.0.0
flutter_built_redux ^0.5.0 0.5.0
Transitive dependencies
analyzer 0.31.1 0.32.1
analyzer_plugin 0.0.1-alpha.0 0.0.1-alpha.3
args 1.4.3
async 2.0.7
boolean_selector 1.0.3
build 0.12.7
build_config 0.2.6+2 0.3.1
built_collection 3.1.1
built_redux 7.4.1-dev 7.4.1
built_value 5.5.2
built_value_generator 5.5.0 5.5.2
charcode 1.1.1
cli_util 0.1.3
collection 1.14.6 1.14.10
convert 2.0.1
crypto 2.0.5
csslib 0.14.4
dart_style 1.0.9+1 1.1.0
fixnum 0.10.7
front_end 0.1.0-alpha.9 0.1.1
glob 1.1.6
html 0.13.3+1
http 0.11.3+16
http_multi_server 2.0.5
http_parser 3.1.2
io 0.3.2+1
isolate 1.1.0 2.0.1
js 0.6.1
json_rpc_2 2.0.8
kernel 0.3.0-alpha.9 0.3.1
logging 0.11.3+1
matcher 0.12.3
meta 1.1.5
mime 0.9.6+1
multi_server_socket 1.0.1
node_preamble 1.4.2
package_config 1.0.3
package_resolver 1.0.3
path 1.6.0 1.6.1
plugin 0.2.0+2
pool 1.3.5
pub_semver 1.4.1
quiver 0.29.0+1
shelf 0.7.3+1
shelf_packages_handler 1.0.3
shelf_static 0.2.7+1
shelf_web_socket 0.2.2+2
sky_engine 0.0.99
source_gen 0.8.2
source_map_stack_trace 1.1.4
source_maps 0.10.5
source_span 1.4.0
stack_trace 1.9.2
stream_channel 1.6.7+1
string_scanner 1.0.2
term_glyph 1.0.0
test 0.12.42 1.0.0
typed_data 1.1.5
utf 0.9.0+4
vector_math 2.0.6 2.0.7
vm_service_client 0.2.4+3
watcher 0.9.7+8
web_socket_channel 1.0.8
yaml 2.1.14