consumer 0.2.0 consumer: ^0.2.0 copied to clipboard
consumer is like react-consumer state manage, use Stream at dart, consumer have memo and shoudWidgetUpdate function to intercept update.
consumer #
flutter consumer is like react-consumer state manage, use Stream at dart, consumer have memo and shoudWidgetUpdate function to intercept update.
API Document:
- https://pub.flutter-io.cn/documentation/consumer/latest/
- https://pub-web.flutter-io.cn/documentation/consumer/latest/
If your need use old API, please use consumer: 0.1.4
;
Install consumer #
Change pubspec.yaml
:
dependencies:
consumer: ^0.2.0
Getting Started #
import 'package:flutter/material.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),
),
);
}
}
That's all #
Thank you read and use consumer