当前位置:网站首页>Less than 40 lines of code to create a blocprovider
Less than 40 lines of code to create a blocprovider
2022-06-26 12:42:00 【InfoQ】
Preface
SimpleBlocProviderSimpleBlocProvider
Definition
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 Refresh
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 application
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 Counter '),
),
body: Center(
child: SimpleBlocProvider<int>(
builder: (count) => Text(
'$count',
style: TextStyle(
fontSize: 32,
color: Colors.blue,
),
),
bloc: counter,
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
counter.increment();
},
tooltip: ' Click to increase ',
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: ' Ma Nong on the island ', gender: ' male ')));
on<UsingEnNameEvent>(
(event, emit) => emit(Person(name: 'island-coder', gender: 'male')));
}
}
class SimpleBlocCounterPage extends StatelessWidget {
final personBloc = PersonBloc(Person(name: ' Ma Nong on the island ', gender: ' male '));
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Bloc event '),
),
body: Center(
child: SimpleBlocProvider<Person>(
builder: (person) => Text(
' full name :${person.name}, Gender :${person.gender}',
style: TextStyle(
fontSize: 22,
color: Colors.blue,
),
),
bloc: personBloc,
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
personBloc.add(UsingEnNameEvent());
},
tooltip: ' Click to increase ',
child: Icon(Icons.add),
),
);
}
}
summary
SimpleBLocProviderflutter_bloc
边栏推荐
- TP5 thinkphp5 report serialization of'closure'is not allowed
- "Pinduoduo and short video speed version", how can I roast!
- [solved] laravel completes the scheduled job task (delayed distribution task) [execute a user-defined task at a specified time]
- Assembly language (7) operation instruction
- Basic principle of MOS tube and important knowledge points of single chip microcomputer
- imagecopymerge
- Why is password salt called "salt"? [Close] - why is a password salt called a "salt"? [closed]
- 菜鸟实战UML——活动图
- 关于NaN的一些总结
- Fengshentai old shooting range Kali series
猜你喜欢

Scala-day03- operators and loop control

JMeter response time and TPS listener tutorial

Omnichannel membership - tmall membership 1: opening tutorial

简易数字电路交通灯设计

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

"Pinduoduo and short video speed version", how can I roast!

Several rare but useful JS techniques
![[solved] data duplication or data loss after laravel paginate() paging](/img/68/7bf51bbf893a91bee24f5f7d4a369f.jpg)
[solved] data duplication or data loss after laravel paginate() paging

Several methods added to the ES6 array (foreach, filter, some, every. Includes, reduce)

Laravel subdomain accesses different routing files and different modules
随机推荐
7-3 最低通行费
Laravel subdomain accesses different routing files and different modules
The transformation of enterprise customers' digital assets needs to suit the case
一个快速切换一个底层实现的思路分享
环形队列php
Precautions for opening a securities account is it safe to open an account
power designer - 自定义注释按钮
fastjson的JSONArray和JSONObject[通俗易懂]
大智慧哪个开户更安全,更好点
File decryption in webgame development
Build Pikachu shooting range and introduction
7-16 货币系统Ⅰ
Research on the current situation of China's modified engineering plastics market and demand forecast analysis report 2022-2028
2022 edition of Beijing 5g industry investment planning and development prospect forecast analysis report
Nodejs get get/post request parameters
A most practical arbitrage wizard EA [2022 modified version]
5+API,清除应用缓存
Installing MySQL under Linux (RPM package installation)
Laravel uses find_ IN_ The set() native MySQL statement accurately queries whether a special string exists in the specified string to solve the problem that like cannot be accurately matched. (resolve
[probability theory] conditional probability, Bayesian formula, correlation coefficient, central limit theorem, parameter estimation, hypothesis test