当前位置:网站首页>Use bloc to build a page instance of shutter
Use bloc to build a page instance of shutter
2022-07-02 13:46:00 【InfoQ】
Preface
BlocProvider
Provider
BlocBuilder<CounterCubit, int>(
builder: (context, count) => Text(
'$count',
style: TextStyle(
fontSize: 32,
color: Colors.blue,
),
),
count
BlocProvider
Provider
context.watch
BlocBuilder
BlocBuilder Binding to state objects
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 Counter '),
),
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: ' Click to increase ',
child: Icon(Icons.add),
),
);
}
}
Refresh by conditions
BlocBuilder
buildWhen
bool
typedef BlocBuilderCondition<S> = bool Function(S previous, S current);
enum LoadingStatus {
loading, // load
success, // Loading successful
failed, // Loading failed
}
Bloc
event
Event
abstract class PersonalEvent {}
// Get data events
class FetchEvent extends PersonalEvent {}
// Success Events
class FetchSucessEvent extends PersonalEvent {}
// Failure events
class FetchFailedEvent extends PersonalEvent {}
class PersonalResponse {
PersonalEntity? personalProfile;
LoadingStatus status = LoadingStatus.loading;
PersonalResponse({this.personalProfile, required this.status});
}
PersonalBloc
FetchEvent
: Request network data ;
FetchSucessEvent
: After loading successfully , Build a new... With the requested personal information object and loading statusPersonalResponse
object , Useemit
The notification interface is refreshed ;
FetchFailedEvent
: Loading failed , emptyPersonalResponse
Personal information object , And mark the loading status as failed .
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(' Loading ...'),
);
}
if (personalResponse.status == LoadingStatus.failed) {
return Center(
child: Text(' request was aborted '),
);
}
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;
},
);
}
// Other codes are omitted
}
FetchEvent
BlocBuilder
builder
print
buildWhen
PersonalEntity
==
hashCode

userId
true
summary
BlocBuilder
Bloc
event
Redux
BlocBuilder
BlocProvider
Bloc
Bloc
buildWhen

边栏推荐
- Explanation of 34 common terms on the Internet
- I did it with two lines of code. As a result, my sister had a more ingenious way
- 解答:EasyDSS视频点播时音频是否可以设置为默认开启?
- Verification failed, please check your call back website. You can follow the instructions
- BeanUtils--浅拷贝--实例/原理
- Skillfully use SSH to get through the Internet restrictions
- OpenAPI generator: simplify the restful API development process
- The 29 year old programmer in Shanghai was sentenced to 10 months for "deleting the database and running away" on the day of his resignation!
- 题解《子数整数》、《欢乐地跳》、《开灯》
- Can automatically update the universal weekly report template, you can use it with your hand!
猜你喜欢
浏览器驱动的下载
诚邀青年创作者,一起在元宇宙里与投资人、创业者交流人生如何做选择……...
[Blue Bridge Cup] children's worship circle
Pointer from entry to advanced (1)
Essential for operation and maintenance - Elk log analysis system
(POJ - 1984) navigation nightare (weighted and search set)
[技术发展-22]:网络与通信技术的应用与发展快速概览-2- 通信技术
Bridge of undirected graph
[cloud native database] what to do when encountering slow SQL (Part 1)?
Daily practice of C language --- monkeys divide peaches
随机推荐
混沌工程平台 ChaosBlade-Box 新版重磅发布
中文姓名提取(玩具代码——准头太小,权当玩闹)
Can automatically update the universal weekly report template, you can use it with your hand!
Why is the default of switch followed by break?
OpenApi-Generator:简化RESTful API开发流程
Clean up system cache and free memory under Linux
题解《子数整数》、《欢乐地跳》、《开灯》
EasyDSS点播服务分享时间出错如何修改?
Redis数据库持久化
[技术发展-22]:网络与通信技术的应用与发展快速概览-2- 通信技术
Unity skframework framework (XII), score scoring module
P1347 sorting (topology + SPFA judgment ring or topology [inner judgment ring])
How to use SAP's metadata framework (MDF) to build custom business rules?
Explanation: here is your UFO, Goldbach conjecture
二、帧模式 MPLS 操作
P3807 [template] Lucas theorem /lucas theorem
Solution: Compression Technology (original version and sequel version)
BeanUtils--浅拷贝--实例/原理
Integral link, inertia link and proportion link in Simulink
Explanation of 34 common terms on the Internet