当前位置:网站首页>Why does blocprovider feel similar to provider?
Why does blocprovider feel similar to provider?
2022-07-01 23:38:00 【Ma Nong @ official account on the island with the same name】
Preface
Last one Flutter Introduction and actual combat ( eighty-six ): Less than 40 One line of code BlocProvider, We only used less than 40 A line of code hand rolled a SimpleBlocProvider
, It feels OK to use , This is it. Bloc One of the advantages of , You can be based on Bloc
This model extends itself , Form your own state management component . Let's take a look at the official flutter_bloc Plugins provide BlocProvider
What about? .
Provider Imitator ?
Let's see first BlocProvider
Implementation of the counter sample code :
class BlocCounterWrapper extends StatelessWidget {
@override
Widget build(BuildContext context) {
return BlocProvider(
create: (_) => CounterCubit(),
child: BlocCounterPage(),
);
}
}
class BlocCounterPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Bloc Counter '),
),
body: Center(
child: BlocBuilder<CounterCubit, int>(
builder: (context, count) => Text(
'$count',
style: TextStyle(
fontSize: 32,
color: Colors.blue,
),
),
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
context.read<CounterCubit>().increment();
},
tooltip: ' Click to increase ',
child: Icon(Icons.add),
),
);
}
}
Is this code very familiar ? If we look back on our previous Provider
State management , It feels very similar ! such as :
Widget build(BuildContext context) {
return BlocProvider(
create: (_) => CounterCubit(),
child: BlocCounterPage(),
);
}
stay Provider
The implementation in is as follows .
Widget build(BuildContext context) {
return Provider(
create: (_) => CounterCubit(),
child: BlocCounterPage(),
);
}
And in the FloatingActionButton
Inside context.read
The usage is the same as Provider
The same in . therefore , If you want to from Provider
Migrate to Bloc It's also very simple . Actually, from the source code layer by layer up , You will find that there is provider Code for .
library flutter_bloc;
export 'package:bloc/bloc.dart';
export 'package:provider/provider.dart'
show ProviderNotFoundException, ReadContext, SelectContext, WatchContext;
And from Provider
and bloc
Of GitHub Among the source code contributors, we also found Provider
The code contributor to Felix Angelov Namely bloc The originator of the code .. So it's not surprising Bloc Use in Provider 了 .
And Provider Similarities and differences
BlocProvider
and Provider
equally , Provide status data for sub components through component tree . That is, we can use Provider
The use of BlocProvider
, For example, the use of existing state objects and Provider
The use of value
parameter assignment :
final counter = CounterCubit();
//...
BlocProvider.value(
value: counter,
child: SomeWidget(),
);
For example, it can be used in subcomponents context.read
and context.watch
. And the use of select Method listens for partial changes in state data .
final isPositive = context.select((CounterBloc b) => b.state >= 0);
also MultiBlocProvider
To pass multiple... To the subcomponent tree Bloc State object .
MultiBlocProvider(
providers: [
BlocProvider<BlocA>(
create: (BuildContext context) => BlocA(),
),
BlocProvider<BlocB>(
create: (BuildContext context) => BlocB(),
),
BlocProvider<BlocC>(
create: (BuildContext context) => BlocC(),
),
],
child: ChildA(),
)
so to speak , If you used Provider
State management , Can move seamlessly to BlocProvider
. Of course , The state object class still needs to be changed . This is also BlocProvider
and Provider
The difference between . For example, state objects do not need to implement ChangeNotifier
Interface , When the state data changes, there is no need to call notifyListeners
To inform refresh . Actually, we start from BlocProvider
The source code picks out a method of monitoring the implementation of state objects , In fact, it is also used here that we are SimpleBlocProvider
Used in Stream.listen
Method to achieve .
static VoidCallback _startListening(
InheritedContext<BlocBase?> e,
BlocBase value,
) {
final subscription = value.stream.listen(
(dynamic _) => e.markNeedsNotifyDependents(),
);
return subscription.cancel;
}
The code of other parts is basically reuse Provider
Code for . therefore BlocProvider
It can be seen as using Stream.listen
Listen for status data ChangeNotifer
Of Provider
Variants . therefore , If you want to go from Provider
Switch to BlocProvider
, You can switch boldly , The workload of code modification is very low . And there is no need to call... Repeatedly in the state object notifyListeners
To notify that the interface has been refreshed .
summary
This article introduces BlocProvider
Use , In terms of writing , Don't feel too much advantage , Personally, I think this is what the author wants Provider
Users can switch directly to BlocProvider
To provide such a Provider
substitute . however , This is just the tip of the iceberg , actually ,flutter_bloc There are many other options , We will introduce them one by one .
边栏推荐
- Notes to problems - file /usr/share/mysql/charsets/readme from install of mysql-server-5.1.73-1 glibc23.x86_ 64 c
- Redis RDB snapshot
- What category does the Internet of things application technology major belong to
- The third part of the construction of the defense system of offensive and defensive exercises is the establishment of a practical security system
- Postgresql源码(57)HOT更新为什么性能差距那么大?
- 纪念成为首个DAYUs200三方demo贡献者
- 物联网技术应用属于什么专业分类
- ShanDong Multi-University Training #3
- How excel opens CSV files with more than one million lines
- ConcurrentSkipListMap——跳表原理
猜你喜欢
【必会】BM41 输出二叉树的右视图【中等+】
神经网络物联网的发展趋势和未来方向
使用uni-simple-router,动态传参 TypeError: Cannot convert undefined or null to object
The essence of software architecture
ARP message header format and request flow
Stm32f030f4 drives tim1637 nixie tube chip
Matplotlib常用图表
Redis 主从同步
Notblank and notempty
De PIP. Interne. CLI. Main Import main modulenotfounderror: No module named 'PIP'
随机推荐
Reproduction process and problems of analog transformer (ICLR 2022 Spotlight)
Switch to software testing, knowing these four points is enough!
小程序表单校验封装
MySQL Replication中并行复制怎么实现
纪念成为首个DAYUs200三方demo贡献者
Matplotlib common charts
在代码中使用SqlCommand对象
2021 RoboCom 世界机器人开发者大赛-高职组复赛
jpa手写sql,用自定义实体类接收
Redis AOF log
Is it safe to choose mobile phone for stock trading account opening in Shanghai?
const // It is a const object...class nullptr_t
Redis RDB snapshot
Leetcode(34)——在排序数组中查找元素的第一个和最后一个位置
使用VB.net将PNG图片转成icon类型图标文件
转行软件测试,知道这四点就够了!
[must] bm41 output the right view of the binary tree [medium +]
Stm32f030f4 drives tim1637 nixie tube chip
Overview of edge calculation
ADO.NET之SqlDataAdpter对象