当前位置:网站首页>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
边栏推荐
- JS get the current screen height method and listen for DOM elements to enter the viewport
- Nodejs get get/post request parameters
- Configuring Apache digest authentication
- International beauty industry giants bet on China
- 7-2 数的三次方根
- 2022 edition of China's cotton chemical fiber printing and dyeing Market Status Investigation and Prospect Forecast Analysis Report
- Investment forecast and development strategy analysis report of China's rural sewage treatment industry in 2022
- NoSQL mongodb - 01 introduction to NoSQL and mongodb
- 2016年四川省TI杯电子设计竞赛B题
- MS17_ 010 utilization summary
猜你喜欢

快手实时数仓保障体系研发实践

环形队列php

Laravel subdomain accesses different routing files and different modules

Mongodb of NoSQL - 03 mongodb CRUD

简易数字电路交通灯设计

Scala-day02- variables and data types

BigInt:处理大数字(任意长度的整数)

Scala-day06- pattern matching - Generic

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

MySQL optimization - index (what is an index?)
随机推荐
A most practical arbitrage wizard EA [2022 modified version]
Current situation investigation and investment prospect forecast analysis report of China's electrolytic copper market from 2022 to 2028
Adobe Acrobat阻止30款安全软件查看PDF文件 或存在安全风险
Lodash common methods (filtering, anti shake...)
Build Pikachu shooting range and introduction
Analysis report on dynamic research and investment planning suggestions of China's laser medical market in 2022
小程序中控件里面的内容较多,让其支持滚动的良好方案
Fengshentai old shooting range Kali series
Installing MySQL under Linux (RPM package installation)
Leetcode 78. Subset and 90 Subset II
Is it safe to open a securities account in general
Php+laravel5.7 use Alibaba oss+ Alibaba media to process and upload image / video files
NoSQL mongodb - 01 introduction to NoSQL and mongodb
Function collapse and expansion shortcut keys in vscode (latest and correct)
[probability theory] conditional probability, Bayesian formula, correlation coefficient, central limit theorem, parameter estimation, hypothesis test
菜鸟实战UML——活动图
简易数字电路交通灯设计
2022 edition of China's medical robot industry investment status investigation and prospect dynamic analysis report
Spark-day03-core programming RDD operator
Learning directory