当前位置:网站首页>使用BLoC 构建 Flutter的页面实例
使用BLoC 构建 Flutter的页面实例
2022-07-02 10:11:00 【InfoQ】
前言
BlocProvider
Provider
BlocBuilder<CounterCubit, int>(
builder: (context, count) => Text(
'$count',
style: TextStyle(
fontSize: 32,
color: Colors.blue,
),
),
count
BlocProvider
Provider
context.watch
BlocBuilder
BlocBuilder 与状态对象的绑定
class BlocBuilder<B extends BlocBase<S>, S> extends BlocBuilderBase<B, S> {
const BlocBuilder({
Key? key,
required this.builder,
B? bloc,
BlocBuilderCondition<S>? buildWhen,
}) : super(key: key, bloc: bloc, buildWhen: buildWhen);
final BlocWidgetBuilder<S> builder;
@override
Widget build(BuildContext context, S state) => builder(context, state);
}
bloc
BlocProvider
context
BlocBuilderBase
StatefulWidget
State
context.read
@override
void initState() {
super.initState();
_bloc = widget.bloc ?? context.read<B>();
_state = _bloc.state;
}
bloc
bloc
bloc
BlocProvider
GetBuilder
class BlocBuilderDemoPage extends StatelessWidget {
final counterCubit = CounterCubit();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Bloc 计数器'),
),
body: Center(
child: BlocBuilder<CounterCubit, int>(
builder: (context, count) => Text(
'$count',
style: TextStyle(
fontSize: 32,
color: Colors.blue,
),
),
bloc: counterCubit,
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
counterCubit.increment();
},
tooltip: '点击增加',
child: Icon(Icons.add),
),
);
}
}
按条件刷新
BlocBuilder
buildWhen
bool
typedef BlocBuilderCondition<S> = bool Function(S previous, S current);
enum LoadingStatus {
loading, //加载
success, //加载成功
failed, //加载失败
}
Bloc
event
Event
abstract class PersonalEvent {}
// 获取数据事件
class FetchEvent extends PersonalEvent {}
// 成功事件
class FetchSucessEvent extends PersonalEvent {}
// 失败事件
class FetchFailedEvent extends PersonalEvent {}
class PersonalResponse {
PersonalEntity? personalProfile;
LoadingStatus status = LoadingStatus.loading;
PersonalResponse({this.personalProfile, required this.status});
}
PersonalBloc
FetchEvent
:请求网络数据;
FetchSucessEvent
:加载成功后,用请求得到的个人信息对象和加载状态构建新的PersonalResponse
对象,使用emit
通知界面刷新;
FetchFailedEvent
:加载失败,置空PersonalResponse
的个人信息对象,并且标记加载状态为失败。
class PersonalBloc extends Bloc<PersonalEvent, PersonalResponse> {
final String userId;
PersonalEntity? _personalProfile;
PersonalBloc(PersonalResponse initial, {required this.userId})
: super(initial) {
on<FetchEvent>((event, emit) {
getPersonalProfile(userId);
});
on<FetchSucessEvent>((event, emit) {
emit(PersonalResponse(
personalProfile: _personalProfile,
status: LoadingStatus.success,
));
});
on<FetchFailedEvent>((event, emit) {
emit(PersonalResponse(
personalProfile: null,
status: LoadingStatus.failed,
));
});
on<RefreshEvent>((event, emit) {
getPersonalProfile(userId);
});
add(FetchEvent());
}
void getPersonalProfile(String userId) async {
_personalProfile = await JuejinService().getPersonalProfile(userId);
if (_personalProfile != null) {
add(FetchSucessEvent());
} else {
add(FetchFailedEvent());
}
}
}
GetX
BlocBuilder
class PersonalHomePage extends StatelessWidget {
PersonalHomePage({Key? key}) : super(key: key);
final personalBloc = PersonalBloc(
PersonalResponse(
personalProfile: null,
status: LoadingStatus.loading,
),
userId: '70787819648695');
@override
Widget build(BuildContext context) {
return BlocBuilder<PersonalBloc, PersonalResponse>(
bloc: personalBloc,
builder: (_, personalResponse) {
print('build PersonalHomePage');
if (personalResponse.status == LoadingStatus.loading) {
return Center(
child: Text('加载中...'),
);
}
if (personalResponse.status == LoadingStatus.failed) {
return Center(
child: Text('请求失败'),
);
}
PersonalEntity personalProfile = personalResponse.personalProfile!;
return Stack(
children: [
CustomScrollView(
slivers: [
_getBannerWithAvatar(context, personalProfile),
_getPersonalProfile(personalProfile),
_getPersonalStatistic(personalProfile),
],
),
Positioned(
top: 40,
right: 10,
child: IconButton(
onPressed: () {
personalBloc.add(FetchEvent());
},
icon: Icon(
Icons.refresh,
color: Colors.white,
),
),
),
],
);
},
buildWhen: (previous, next) {
if (previous.personalProfile == null || next.personalProfile == null) {
return true;
}
return previous.personalProfile!.userId != next.personalProfile!.userId;
},
);
}
// 其他代码略
}
FetchEvent
BlocBuilder
builder
print
buildWhen
PersonalEntity
==
hashCode

userId
true
总结
BlocBuilder
Bloc
event
Redux
BlocBuilder
BlocProvider
Bloc
Bloc
buildWhen

边栏推荐
- Unity skframework framework (XII), score scoring module
- Detailed collection of common MySQL commands
- Redis database persistence
- Android kotlin broadcast technology point
- 【youcans 的图像处理学习课】总目录
- 量子三体问题: Landau Fall
- 题解《子数整数》、《欢乐地跳》、《开灯》
- Unity SKFramework框架(十六)、Package Manager 開發工具包管理器
- Don't spend money, spend an hour to build your own blog website
- JS reverse row query data decryption
猜你喜欢
Partner cloud form strong upgrade! Pro version, more extraordinary!
net share
为什么switch 的default后面要跟break?
What are eNB, EPC and PGW?
Unity skframework framework (XXI), texture filter map resource filtering tool
Solve "sub number integer", "jump happily", "turn on the light"
Three methods of finding LCA of the nearest common ancestor
Node.js通过ODBC访问PostgreSQL数据库
Can automatically update the universal weekly report template, you can use it with your hand!
Unity skframework framework (XIV), extension extension function
随机推荐
中文姓名提取(玩具代码——准头太小,权当玩闹)
Why is the default of switch followed by break?
(6) Web security | penetration test | network security encryption and decryption ciphertext related features, with super encryption and decryption software
Japan bet on national luck: Web3.0, anyway, is not the first time to fail!
屠榜多目标跟踪!BoT-SORT:稳健的关联多行人跟踪
Professor of Shanghai Jiaotong University: he Yuanjun - bounding box (containment / bounding box)
ADB basic commands
MySQL: Invalid GIS data provided to function st_ geometryfromtext
De4000h storage installation configuration
Explanation of 34 common terms on the Internet
Can automatically update the universal weekly report template, you can use it with your hand!
D how to check null
numpy数组计算
能自动更新的万能周报模板,有手就会用!
OpenApi-Generator:简化RESTful API开发流程
OpenAPI generator: simplify the restful API development process
2022零代码/低代码开发白皮书【伙伴云出品】附下载
How to explain binary search to my sister? This is really difficult, fan!
Answer: can the audio be set to on by default during easydss video on demand?
伙伴云表格强势升级!Pro版,更非凡!