当前位置:网站首页>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
边栏推荐
- 简易数字电路交通灯设计
- Polarismesh series articles - concept series (I)
- PHP laravel+gatewayworker completes im instant messaging and file transfer (Chapter 1: basic configuration)
- 2016年四川省TI杯电子设计竞赛B题
- Realize microservice load balancing (ribbon)
- Examples of how laravel uses with preload (eager to load) and nested query
- Spark-day03-core programming RDD operator
- 美学心得(第二百三十八集) 罗国正
- Example of parameter passing from laravel query constructor to closure method
- Rookie practical UML - activity diagram
猜你喜欢

power designer - 自定义注释按钮

Omnichannel membership - tmall membership 1: opening tutorial
![[probability theory] conditional probability, Bayesian formula, correlation coefficient, central limit theorem, parameter estimation, hypothesis test](/img/2f/f44381ea759f4c1c957a8f9434f0ee.png)
[probability theory] conditional probability, Bayesian formula, correlation coefficient, central limit theorem, parameter estimation, hypothesis test
![[graduation season · advanced technology Er] I remember the year after graduation](/img/e7/8e1dafa561217b77a3e3992977a8ec.png)
[graduation season · advanced technology Er] I remember the year after graduation

TP5 thinkphp5 report serialization of'closure'is not allowed

Realize microservice load balancing (ribbon)

NoSQL mongodb - 01 introduction to NoSQL and mongodb

不到40行代码手撸一个BlocProvider

Mongodb of NoSQL - 03 mongodb CRUD

Fengshentai old shooting range Kali series
随机推荐
详细实操分享,下班刷了两小时的搞笑视频,一个月收益7000多
imagecopymerge
Typescript learning (I) type
Lodash common methods (filtering, anti shake...)
Fengshentai old shooting range Kali series
Is it safe to open a securities account in general
I'd like to know what preferential activities are available for stock account opening? Is it safe to open an account online?
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
7-16 货币系统Ⅰ
Is it safe to open a securities account
几行代码就能实现复杂的 Excel 导入导出,这个工具类真心强大!
Omnichannel membership - tmall membership 2: frequently asked questions
dried food! Yiwen will show you SD card, TF card and SIM card!
PHP unit conversion
NoSQL mongodb - 02 mongodb server installation, mongodb shell, basic concepts and visualization tools
栈,后入先出
Vscode solves the problem of Chinese garbled code
一个初级多线程服务器模型
Tiger DAO VC产品正式上线,Seektiger生态的有力补充
班主任让开股票账户,在挖财理财开户安全吗?