当前位置:网站首页>不到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
边栏推荐
- NFS shared storage service 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
- SQL injection
- Comparison of latest mobile phone processors in 2020 (with mobile phone CPU ladder diagram)
- Leetcode 78. Subset and 90 Subset II
- Build Pikachu shooting range and introduction
- Member system + enterprise wechat + applet to help the efficient transformation of private domain
- 环形队列php
- Mongodb of NoSQL - 03 mongodb CRUD
- PolarisMesh系列文章——概念系列(一)
猜你喜欢

Php+laravel5.7 use Alibaba oss+ Alibaba media to process and upload image / video files

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

Scala problem solving the problem of slow SBT Download
![[solved] laravel completes the scheduled job task (delayed distribution task) [execute a user-defined task at a specified time]](/img/13/c2c63333a9e5ac08b339449ea17654.jpg)
[solved] laravel completes the scheduled job task (delayed distribution task) [execute a user-defined task at a specified time]

SQL injection in Pikachu shooting range
The loss of female scientists

Scala-day02- variables and data types

New routing file in laravel framework

dried food! Yiwen will show you SD card, TF card and SIM card!

Basic principle of MOS tube and important knowledge points of single chip microcomputer
随机推荐
Seven major trends deeply affecting the U.S. consumer goods industry in 2022
Comparison of latest mobile phone processors in 2020 (with mobile phone CPU ladder diagram)
PHP calculates excel coordinate values, starting with subscript 0
PHP laravel+gatewayworker completes im instant messaging and file transfer functions (Chapter 2: explanation of business logic)
Member system + enterprise wechat + applet to help the efficient transformation of private domain
Is it safe to open a securities account
What should I do from member labels to portraits?
KITTI Detection dataset whose format is letf_top_right_bottom to JDE normalied xc_yc_w_h
TSMC Samsung will mass produce 3nm chips in 2022: will the iPhone be the first?
Omni channel member link - tmall member link 3: preparation of member operation content
Examples of how laravel uses with preload (eager to load) and nested query
File decryption in webgame development
Which is safer and better for great wisdom to open an account
Mysql8 master-slave replication
Redis cannot connect to the server through port 6379
Scala-day03- operators and loop control
Nodejs framework express and KOA
PHP generate order number
PolarisMesh系列文章——概念系列(一)
2022 edition of China's energy and chemical industry market in-depth investigation and investment feasibility analysis report