当前位置:网站首页>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

边栏推荐
- OpenFOAM:lduMatrix&lduAddressing
- Pointer from entry to advanced (1)
- P1347 排序(拓扑 + spfa判断环 or 拓扑[内判断环])
- Download files and preview pictures
- 三翼鸟两周年:羽翼渐丰,腾飞指日可待
- [Unity]使用GB2312,打包后程序不正常解决方案
- 使用BLoC 构建 Flutter的页面实例
- [cloud native database] what to do when encountering slow SQL (Part 1)?
- Essential for operation and maintenance - Elk log analysis system
- [technology development-22]: rapid overview of the application and development of network and communication technology-2-communication Technology
猜你喜欢
Sum of the first n terms of Fibonacci (fast power of matrix)
题解:《压缩技术》(原版、续集版)
[indomitable medal activity] life goes on and writing goes on
MAC (MacOS Monterey 12.2 M1) personal use PHP development
Don't spend money, spend an hour to build your own blog website
不会看器件手册的工程师不是个好厨子
Integral link, inertia link and proportion link in Simulink
de4000h存储安装配置
EasyDSS点播服务分享时间出错如何修改?
Unity small map production [2]
随机推荐
[USACO05JAN]Watchcow S(欧拉回路)
Qt新项目_MyNotepad++
We sincerely invite young creators to share with investors and entrepreneurs how to make choices in life in the metauniverse
三谈exception——错误处理
Node.js通过ODBC访问PostgreSQL数据库
Professor of Shanghai Jiaotong University: he Yuanjun - bounding box (containment / bounding box)
Chinese name extraction (toy code - accurate head is too small, right to play)
Principle analysis of security rememberme
Tupang multi-target tracking! BOT sort: robust correlated multi pedestrian tracking
代码实现MNLM
Don't spend money, spend an hour to build your own blog website
免费SSL证书知多少?免费SSL证书和收费SSL证书的区别
Three methods of finding LCA of the nearest common ancestor
每日一题:1175.质数排列
Qt-制作一个简单的计算器-实现四则运算-将结果以对话框的形式弹出来
P3008 [USACO11JAN]Roads and Planes G (SPFA + SLF优化)
【模板】最长公共子序列 (【DP or 贪心】板子)
Japan bet on national luck: Web3.0, anyway, is not the first time to fail!
[true topic of the Blue Bridge Cup trials 43] scratch space flight children's programming explanation of the true topic of the Blue Bridge Cup trials
Redis数据库持久化