当前位置:网站首页>使用BLoC 构建 Flutter的页面实例
使用BLoC 构建 Flutter的页面实例
2022-07-02 10:11:00 【InfoQ】
前言
BlocProviderProviderBlocBuilder<CounterCubit, int>(
builder: (context, count) => Text(
'$count',
style: TextStyle(
fontSize: 32,
color: Colors.blue,
),
),
countBlocProviderProvidercontext.watchBlocBuilderBlocBuilder 与状态对象的绑定
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);
}
blocBlocProvidercontextBlocBuilderBaseStatefulWidgetStatecontext.read@override
void initState() {
super.initState();
_bloc = widget.bloc ?? context.read<B>();
_state = _bloc.state;
}
blocblocblocBlocProviderGetBuilderclass 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),
),
);
}
}
按条件刷新
BlocBuilderbuildWhenbooltypedef BlocBuilderCondition<S> = bool Function(S previous, S current);
enum LoadingStatus {
loading, //加载
success, //加载成功
failed, //加载失败
}
BloceventEventabstract 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});
}
PersonalBlocFetchEvent:请求网络数据;
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());
}
}
}
GetXBlocBuilderclass 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;
},
);
}
// 其他代码略
}
FetchEventBlocBuilderbuilderprintbuildWhenPersonalEntity==hashCode
userIdtrue总结
BlocBuilderBloceventReduxBlocBuilderBlocProviderBlocBlocbuildWhen
边栏推荐
- Unity skframework framework (XXI), texture filter map resource filtering tool
- Unity skframework framework (XIX), POI points of interest / information points
- (7) Web security | penetration testing | how does network security determine whether CND exists, and how to bypass CND to find the real IP
- EasyDSS点播服务分享时间出错如何修改?
- 互联网常见34个术语解释
- [indomitable medal activity] life goes on and writing goes on
- What are the classifications of SSL certificates? How to choose the appropriate SSL certificate?
- 量子三体问题: Landau Fall
- Unity SKFramework框架(十八)、RoamCameraController 漫游视角相机控制脚本
- A better database client management tool than Navicat
猜你喜欢

PR usage skills, how to use PR to watermark?

(7) Web security | penetration testing | how does network security determine whether CND exists, and how to bypass CND to find the real IP

Daily practice of C language --- monkeys divide peaches

题解《子数整数》、《欢乐地跳》、《开灯》

Three methods of finding LCA of the nearest common ancestor

Unity SKFramework框架(十四)、Extension 扩展函数

Unity skframework framework (XV), singleton singleton
![Jerry's watch ringtone audition [article]](/img/18/905c4b64443f4efca55188e36f4b28.jpg)
Jerry's watch ringtone audition [article]

Essential for operation and maintenance - Elk log analysis system

MAC (MacOS Monterey 12.2 M1) personal use PHP development
随机推荐
JS reverse row query data decryption
nohup命令
JS generates 4-digit verification code
Unity skframework Framework (XVI), package manager Development Kit Manager
最近公共祖先LCA的三种求法
2022 Heilongjiang provincial examination on the writing skills of Application Essays
挥发性有机物TVOC、VOC、VOCS气体检测+解决方案
Unity skframework framework (XVII), freecameracontroller God view / free view camera control script
【OpenGL】笔记二十九、高级光照(镜面高光)
伙伴云表格强势升级!Pro版,更非凡!
numpy数组计算
Clean up system cache and free memory under Linux
Chinese name extraction (toy code - accurate head is too small, right to play)
Add sequence number column to query results in MySQL
【youcans 的图像处理学习课】总目录
Japan bet on national luck: Web3.0, anyway, is not the first time to fail!
SAP MM 因物料有负库存导致MMPV开账期失败问题之对策
Unity skframework framework (XXI), texture filter map resource filtering tool
【蓝桥杯选拔赛真题43】Scratch航天飞行 少儿编程scratch蓝桥杯选拔赛真题讲解
Error function ERF