当前位置:网站首页>不到40行代码手撸一个BlocProvider
不到40行代码手撸一个BlocProvider
2022-06-26 12:34:00 【InfoQ】
前言
SimpleBlocProviderSimpleBlocProvider
定义
SimpleBlocProviderStatefulWidgetStatefulWidgetStatefulWidget
SimpleBlocProviderbuilderbuilderWidgettypedef StateBuilder<T> = Widget Function(T state);
SimpleBlocProvider<int> (
builder: (count) => Text('$count'),
)
builderSimpleBlocProviderSimpleBlocProviderclass SimpleBlocProvider<T> extends StatefulWidget {
final StateBuilder<T> builder;
final BlocBase<T> bloc;
const SimpleBlocProvider(
{Key? key, required this.builder, required this.bloc})
: super(key: key);
@override
_SimpleBlocProviderState<T> createState() => _SimpleBlocProviderState<T>();
}
BLoC 刷新
StreamStreamlistenStream StreamSubscription<T> listen(void onData(T event)?,
{Function? onError, void onDone()?, bool? cancelOnError});
listenonDatasetState_SimpleBlocProviderState_streamSubscriptionlistendispose_streamSubscription = widget.bloc.stream.listen((data) {
setState(() {
_state = data;
});
});
//
@override
void dispose() {
_streamSubscription.cancel();
super.dispose();
}
_SimpleBlocProviderStatebuildbuilder_state@override
Widget build(BuildContext context) {
return widget.builder(_state);
}
listenSimpleBlocProvider_stateSimpleBlocProviderbuildertypedef StateBuilder<T> = Widget Function(T state);
class SimpleBlocProvider<T> extends StatefulWidget {
final StateBuilder<T> builder;
final BlocBase<T> bloc;
const SimpleBlocProvider(
{Key? key, required this.builder, required this.bloc})
: super(key: key);
@override
_SimpleBlocProviderState<T> createState() => _SimpleBlocProviderState<T>();
}
class _SimpleBlocProviderState<T> extends State<SimpleBlocProvider<T>> {
late T _state;
late StreamSubscription<T> _streamSubscription;
@override
void initState() {
_state = widget.bloc.state;
super.initState();
_streamSubscription = widget.bloc.stream.listen((data) {
setState(() {
_state = data;
});
});
}
@override
Widget build(BuildContext context) {
return widget.builder(_state);
}
@override
void dispose() {
_streamSubscription.cancel();
super.dispose();
}
}
SimpleBlocProvider 应用
class CounterCubit extends Cubit<int> {
CounterCubit({initial = 0}) : super(initial);
void increment() => emit(state + 1);
void decrement() => emit(state - 1);
@override
void onChange(Change<int> change) {
super.onChange(change);
}
}
class SimpleBlocCounterPage extends StatelessWidget {
final counter = CounterCubit();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Bloc 计数器'),
),
body: Center(
child: SimpleBlocProvider<int>(
builder: (count) => Text(
'$count',
style: TextStyle(
fontSize: 32,
color: Colors.blue,
),
),
bloc: counter,
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
counter.increment();
},
tooltip: '点击增加',
child: Icon(Icons.add),
),
);
}
}

GetBuilderPersoneventclass Person {
final String name;
final String gender;
const Person({required this.name, required this.gender});
}
abstract class PersonEvent {}
class UsingCnNameEvent extends PersonEvent {}
class UsingEnNameEvent extends PersonEvent {}
class PersonBloc extends Bloc<PersonEvent, Person> {
PersonBloc(Person person) : super(person) {
on<UsingCnNameEvent>(
(event, emit) => emit(Person(name: '岛上码农', gender: '男')));
on<UsingEnNameEvent>(
(event, emit) => emit(Person(name: 'island-coder', gender: 'male')));
}
}
class SimpleBlocCounterPage extends StatelessWidget {
final personBloc = PersonBloc(Person(name: '岛上码农', gender: '男'));
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Bloc 事件'),
),
body: Center(
child: SimpleBlocProvider<Person>(
builder: (person) => Text(
'姓名:${person.name},性别:${person.gender}',
style: TextStyle(
fontSize: 22,
color: Colors.blue,
),
),
bloc: personBloc,
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
personBloc.add(UsingEnNameEvent());
},
tooltip: '点击增加',
child: Icon(Icons.add),
),
);
}
}
总结
SimpleBLocProviderflutter_bloc
边栏推荐
- 初探Protostuff的使用[通俗易懂]
- Five trends of member marketing of consumer goods enterprises in the future
- 小程序中控件里面的内容较多,让其支持滚动的良好方案
- How can we reach members more effectively?
- Mysql8 master-slave replication
- Vscode solves the problem of Chinese garbled code
- PHP get directory size
- Rookie practical UML - activity diagram
- Analysis report on the "fourteenth five year plan" and investment prospect of China's pharmaceutical equipment industry 2022-2028
- 手把手带你学会Odoo OWL组件开发(7):OWL项目实战使用
猜你喜欢

This executeQuery (SQL) cannot compile classes for JSP. What is the reason?

PHP laravel+gatewayworker completes im instant messaging and file transfer (Chapter 1: basic configuration)

Laravel subdomain accesses different routing files and different modules

Websocket and socket IO case practice

Ad - update the modified PCB package to the current PCB

Configuring Apache digest authentication

2、 MySQL Foundation

Omnichannel membership - tmall membership 1: opening tutorial

1、 MySQL introduction

TP5 thinkphp5 report serialization of'closure'is not allowed
随机推荐
International beauty industry giants bet on China
Build Pikachu shooting range and introduction
2、 MySQL Foundation
JMeter response time and TPS listener tutorial
How to do well in member marketing three steps to teach you to understand member management
File decryption in webgame development
What software is flush? Is online account opening safe?
Example of parameter passing from laravel query constructor to closure method
2022 edition of Beijing 5g industry investment planning and development prospect forecast analysis report
2022 edition of China's cotton chemical fiber printing and dyeing Market Status Investigation and Prospect Forecast Analysis Report
Xiaolong 888 was released, Xiaomi 11 was launched, and 14 manufacturers carried it in the first batch!
美学心得(第二百三十八集) 罗国正
Scala-day06- pattern matching - Generic
Five problems and solutions of member operation
栈,后入先出
[solved] laravel completes the scheduled job task (delayed distribution task) [execute a user-defined task at a specified time]
Oracle lock table query and unlocking method
Spark-day02-core programming-rdd
Iframe usage and contentwindow, parent and PostMessage communication methods
Spark-day03-core programming RDD operator