当前位置:网站首页>使用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
边栏推荐
- 验证失败,请检查您的回电网址。您可以按照指导进行操作
- 2022 Heilongjiang provincial examination on the writing skills of Application Essays
- Lucky numbers in the [leetcode daily question] matrix
- Embedded software development
- Unity SKFramework框架(十五)、Singleton 单例
- Unity skframework framework (XVIII), roamcameracontroller roaming perspective camera control script
- D为何链接不了dll
- 文件的下载与图片的预览
- Achievements in science and Technology (27)
- 能自动更新的万能周报模板,有手就会用!
猜你喜欢

Solution: Compression Technology (original version and sequel version)

Unity skframework framework (XV), singleton singleton

Embedded software development

2022 Heilongjiang provincial examination on the writing skills of Application Essays

Unity skframework Framework (XVI), package manager Development Kit Manager

Partner cloud form strong upgrade! Pro version, more extraordinary!

伙伴云表格强势升级!Pro版,更非凡!

SAP MM 因物料有负库存导致MMPV开账期失败问题之对策
![[indomitable medal activity] life goes on and writing goes on](/img/c1/54e3f1b37db25af3f1998b39da301b.png)
[indomitable medal activity] life goes on and writing goes on

Node.js通过ODBC访问PostgreSQL数据库
随机推荐
Pocket Raider comments
Unity SKFramework框架(十二)、Score 计分模块
Student course selection information management system based on ssm+jsp framework [source code + database]
Unity SKFramework框架(二十一)、Texture Filter 贴图资源筛选工具
Error function ERF
ArrayList and LinkedList
D how to check null
2022零代码/低代码开发白皮书【伙伴云出品】附下载
Unity SKFramework框架(十六)、Package Manager 開發工具包管理器
P3807 [template] Lucas theorem /lucas theorem
Add sequence number column to query results in MySQL
What are eNB, EPC and PGW?
linux下清理系统缓存并释放内存
Unity SKFramework框架(十九)、POI 兴趣点/信息点
Embedded software development
[youcans' image processing learning course] general contents
TVOC, VOC, VOCs gas detection + Solution
Answer: can the audio be set to on by default during easydss video on demand?
JS逆向之行行查data解密
操作教程:EasyDSS如何将MP4点播文件转化成RTSP视频流?