consumer 1.0.4

  • Readme
  • Changelog
  • Example
  • Installing
  • 70

consumer #

中文文档

consumer is like react-consumer state manage, use Stream at dart.

Feature #

  • consumer not need Provider at root Widget.
  • consumer can ease create sub StateManager at detail modules.
  • consumer use memo to intercept update, like react.Hooks.
  • consumer is tiny and ease use, only 3 API:
    • getState
    • setState
    • build

API Document:

If your need use old API, please use consumer: 0.1.4;

Install consumer #

Change pubspec.yaml:

dependencies:
  consumer: ^1.0.2

Getting Started #

It's Flutter default example, we use Consumer change StateFulWidget to StatelessWidget:

import 'package:flutter/material.dart';
void main() => runApp(MyApp());

// *** definition a state ***
class ExampleState {
  int counter = 0;
}

// *** create a consumer ***
var consumer = Consumer(ExampleState());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Consumer Demo Home Page'),
    );
  }
}

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

  final String title;

  _incrementCounter() {
    // *** Update some widget ***
    consumer.setState((state) => state.counter++);
  }

  @override
  Widget build(BuildContext context) {
    print('only run once');

    return Scaffold(
      appBar: AppBar(
        title: Text(title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            // *** Use consumer.build connect to widget ***
            consumer.build(
              memo: (state) => [state.counter],
              builder: (ctx, state) {
                print('Update when state.counter change');
                return Text(
                  '$state.counter',
                  style: Theme.of(context).textTheme.display1,
                );
              },
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}

About memo detail

If your project have very many state's subscribe, use memo can significantly improved performance.

memo param is learn by react.Hooks, there have some example:

If we have two consumer.build widget:

// *** definition a state ***
class ExampleState {
  int age = 0;
  String name = 'dog';
}

// *** create a consumer ***
var consumer = Consumer(ExampleState());

Column(
  children: <Widget>[
    consumer.build(
      memo: (state) => [state.age],
      builder: (ctx, state) {
        print('Update when state.age change');
        return Text(
          '$state.age',
          style: Theme.of(context).textTheme.display1,
        );
      },
    ),
    consumer.build(
      memo: (state) => [state.name],
      builder: (ctx, state) {
        print('Update when state.name change');
        return Text(
          state.name,
          style: Theme.of(context).textTheme.display1,
        );
      },
    ),
  ],
);

We update state.name, Only update use memo: (state) => [state.name] the widget:

consumer.setState((state){
  state.name = 'cat';
});

Why not update widget before consumer.setState?

Maybe your use state.name, bug memo not subscribe state.name:

Center(
  child: consumer.build(
    memo: (state) => [state.age],
    builder: (ctx, state) {
      return Text(
        state.name,
        style: Theme.of(context).textTheme.display1,
      );
    },
  ),
);

Maybe memo not return anything:

Center(
  child: consumer.build(
    memo: (state) => [],
    builder: (ctx, state) {
      return Text(
        state.name,
        style: Theme.of(context).textTheme.display1,
      );
    },
  ),
);

Maybe your only change List or Map, bu not set new List or Map:

class ExampleState {
  List<String> names = ['dog', 'cat'];
}

var consumer = Consumer(ExampleState());

Center(
  child: consumer.build(
    memo: (state) => [state.names],
    builder: (ctx, state) {
      return Text(
        state.names[0],
        style: Theme.of(context).textTheme.display1,
      );
    },
  ),
);

// Error update:
Consumer.setState((state){
  state.names[0] = 'fish'
});

// right update:
Consumer.setState((state){
  List<String> names = [...state.names];
  names[0] = 'fish'
  state.names = names;
});

State Skills #

If your need change data before update, you can add function props at State.

This have change List data's example:

// *** definition a state ***
class ExampleState {
  int lastChangeNamesIndex;
  List<String> names = ['dog', 'cat'];

  changeNameAt(int index, String name) {
    lastChangeNamesIndex = index;
    List<String> nextNames = [...names];
    nextNames[index] = name;
    names = nextNames;
  }
}

var consumer = Consumer(ExampleState());

Center(
  child: consumer.build(
    memo: (state) => [state.names, state.lastChangeNamesIndex],
    builder: (ctx, state) {
      return Text(
        state.names[state.lastChangeNamesIndex],
        style: Theme.of(context).textTheme.display1,
      );
    },
  ),
);

// ease update names and lastChangeNamesIndex
consumer.setState((state){
  state.changeNameAt(0, 'monkey');
})

That's all #

Thank you read and use consumer

[1.0.4] - Update Dart DOC

[1.0.3] - Update readme

  • Add FAQ

[1.0.2] - Add Chinese README-CN.md

[1.0.1] - Update readme

[1.0.0] - Update readme

[0.2.2] - Update readme

[0.2.1] - Update readme

[0.2.0] - Change to New API, We can create sub consumer

[0.1.4] - Delete shouldWidgetUpdate API

[0.1.3] - Update readme

[0.1.2] - Update readme

[0.1.1] - Add code documents

[0.1.0] - Init package

  • Update this state manage, use react-consumer style

example/example.dart

import 'package:flutter/material.dart';

import '../lib/consumer.dart';

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

// definition a state
class ExampleState {
  int counter = 0;
}

// create a consumer

var consumer = Consumer(ExampleState());

// Flutter base example, StateFulWidget change to StatelessWidget
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

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

  final String title;

  _incrementCounter() {
    consumer.setState((state) => state.counter++);
  }

  @override
  Widget build(BuildContext context) {
    print('only run once');

    return Scaffold(
      appBar: AppBar(
        title: Text(title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            consumer.build(
              // use memo, we can subscribe to valid changes
              memo: (state) => [state.counter],
              builder: (ctx, state) {
                print('update when state.counter change');
                return Text(
                  '$state.counter',
                  style: Theme.of(context).textTheme.display1,
                );
              },
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}

Use this package as a library

1. Depend on it

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


dependencies:
  consumer: ^1.0.4

2. Install it

You can install packages from the command line:

with Flutter:


$ flutter pub get

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

3. Import it

Now in your Dart code, you can use:


import 'package:consumer/consumer.dart';
  
Popularity:
Describes how popular the package is relative to other packages. [more]
41
Health:
Code health derived from static analysis. [more]
100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
100
Overall:
Weighted score of the above. [more]
70
Learn more about scoring.

We analyzed this package on Dec 11, 2019, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.6.1
  • pana: 0.13.1+4
  • Flutter: 1.12.13+hotfix.2

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.3.0 <3.0.0
flutter 0.0.0
Transitive dependencies
collection 1.14.11 1.14.12
meta 1.1.8
sky_engine 0.0.99
typed_data 1.1.6
vector_math 2.0.8