当前位置:网站首页>不到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
边栏推荐
- 洛谷P3426 [POI2005]SZA-Template 题解
- Scala-day03- operators and loop control
- The transformation of enterprise customers' digital assets needs to suit the case
- China's smart toy market outlook and investment strategy consulting forecast report from 2022 to 2027
- The loss of female scientists
- Iframe usage and contentwindow, parent and PostMessage communication methods
- power designer - 自定义注释按钮
- VMware虚拟机 桥接模式 无法上网 校园网「建议收藏」
- Several methods added to the ES6 array (foreach, filter, some, every. Includes, reduce)
- Research on the current situation of China's modified engineering plastics market and demand forecast analysis report 2022-2028
猜你喜欢

International beauty industry giants bet on China

Ad - update the modified PCB package to the current PCB

TSMC Samsung will mass produce 3nm chips in 2022: will the iPhone be the first?

MS17_ 010 utilization summary

Scala-day06- pattern matching - Generic

Vscode solves the problem of Chinese garbled code

Build Pikachu shooting range and introduction

JS get the current screen height method and listen for DOM elements to enter the viewport

Introduction to the four major FPGA manufacturers abroad

This executeQuery (SQL) cannot compile classes for JSP. What is the reason?
随机推荐
Analysis report on China's photovoltaic inverter market prospect forecast and investment strategy recommendations in 2022
BigInt:处理大数字(任意长度的整数)
2、 MySQL Foundation
程序员必备,一款让你提高工作效率N倍的神器uTools
大智慧哪个开户更安全,更好点
Common problems and Thoughts on member operation management
SQL injection
PHP get directory size
UDP协议详解[通俗易懂]
What software is flush? Is online account opening safe?
Spark-day03-core programming RDD operator
Implementing mixins scheme in applet
5+API,清除应用缓存
Scala-day01- companion objects and HelloWorld
How do consumer goods enterprises formulate membership interests?
几行代码就能实现复杂的 Excel 导入导出,这个工具类真心强大!
New routing file in laravel framework
[redis series] redis learning 16. Redis Dictionary (map) and its core coding structure
Analysis report on dynamic research and investment planning suggestions of China's laser medical market in 2022
What determines the rent