当前位置:网站首页>使用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
边栏推荐
- What are the classifications of SSL certificates? How to choose the appropriate SSL certificate?
- Error function ERF
- Pocket Raider comments
- Memory management 01 - link script
- SAP MM 因物料有负库存导致MMPV开账期失败问题之对策
- Unity SKFramework框架(二十一)、Texture Filter 贴图资源筛选工具
- Don't spend money, spend an hour to build your own blog website
- Unity skframework framework (XXI), texture filter map resource filtering tool
- 2022 zero code / low code development white paper [produced by partner cloud] with download
- When tidb meets Flink: tidb efficiently enters the lake "new play" | tilaker team interview
猜你喜欢

Unity skframework framework (XIV), extension extension function
![[技术发展-22]:网络与通信技术的应用与发展快速概览-2- 通信技术](/img/a7/44609a5acf25021f1fca566c3d8c90.png)
[技术发展-22]:网络与通信技术的应用与发展快速概览-2- 通信技术

MAC (MacOS Monterey 12.2 M1) personal use PHP development

Unity skframework framework (XVIII), roamcameracontroller roaming perspective camera control script

What are eNB, EPC and PGW?

(POJ - 1984) navigation nightare (weighted and search set)

Memory management 01 - link script
![[indomitable medal activity] life goes on and writing goes on](/img/c1/54e3f1b37db25af3f1998b39da301b.png)
[indomitable medal activity] life goes on and writing goes on

What are eNB, EPC and PGW?

OpenFOAM:lduMatrix&lduAddressing
随机推荐
OpenFOAM:lduMatrix&lduAddressing
Uniapp develops wechat applet Tencent map function and generates sig signature of location cloud
Daily practice of C language --- monkeys divide peaches
三谈exception——错误处理
研究表明“气味相投”更易成为朋友
ArrayList and LinkedList
nohup命令
D为何链接不了dll
Chinese name extraction (toy code - accurate head is too small, right to play)
I did it with two lines of code. As a result, my sister had a more ingenious way
Solve "sub number integer", "jump happily", "turn on the light"
Redis数据库持久化
JS generates 4-digit verification code
Independent and controllable 3D cloud CAD: crowncad enables innovative design of enterprises
Android kotlin broadcast technology point
Unity skframework framework (XVII), freecameracontroller God view / free view camera control script
Unity SKFramework框架(十七)、FreeCameraController 上帝视角/自由视角相机控制脚本
What are eNB, EPC and PGW?
Engineers who can't read device manuals are not good cooks
EasyDSS点播服务分享时间出错如何修改?