flutter - 如何从处于状态(flutter_bloc)的对象中获取值
问题描述
在构建器方法中,我达到了状态的值,例如
return BlocBuilder<UsersOwnProfileBloc, UsersOwnProfileState>(
cubit: widget.bloc,
builder: (context, state) {
if (state is FetchedUserSettingState) {
bool account = state.userSettings.publicAccount
}
但我需要从 initState 中获取值。我需要设置小部件的值。我尝试过这样的事情,但我得到了错误
@override
void initState() {
super.initState();
UsersOwnProfileState state = BlocProvider.of<UsersOwnProfileBloc>(context).state;
if (state is FetchedUserSettingState) {
publicAccount = state.userSettings.publicAccount;
}
}
谁能告诉我如何在 initState 中获取状态值?
class UserSettingPage extends StatefulWidget {
final UsersOwnProfileBloc bloc;
const UserSettingPage({Key key, this.bloc}) : super(key: key);
@override
_UserSettingPageState createState() => _UserSettingPageState();
}
class _UserSettingPageState extends State<UserSettingPage> {
bool newListingAlert;
bool listingForSearchAlert;
bool searchForListingAlert;
bool followAlert;
bool publicAccount;
@override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_) {
final state = BlocProvider.of<UsersOwnProfileBloc>(context).state;
if (state is FetchedUserSettingState) {
publicAccount = state.userSettings.publicAccount;
}
});
}
@override
Widget build(BuildContext context) {
return BlocBuilder<UsersOwnProfileBloc, UsersOwnProfileState>(
cubit: widget.bloc,
builder: (context, state) {
if (state is FetchedUserSettingState) {
return Scaffold(
appBar: PreferredSize(
preferredSize: Size.fromHeight(25.h),
child: ListingEditAppBar(
onCancel: () {
widget.bloc.add(FetchUserEvent(userId: CurrentUser.currentUser.id));
Navigator.pop(context);
},
),
),
body: Column(
children: [
PageTitle(title: "Preferences"),
Expanded(
child: ListView(
children: [
Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Text("Profilim herkese açık"),
Switch(
onChanged: (value) {
setState(() {
publicAccount = value;
});
},
value: publicAccount,
)
],
),
)
],
),
)
],
),
);
}
return MyProgressIndicator();
},
);
}
}
我已经添加了整个代码。我收到以下错误。
断言失败:布尔表达式不能为空相关的导致错误的小部件是 Switch
解决方案
如果你想访问 initState 中的状态,你需要使用它WidgetsBinding
来访问它。但是,使用它可以确保构建您的小部件,然后触发获取值的方法。仅使用 BlocBuilder、Watch 或 Select 来获取您正在寻找的值会更快。
但是要回答您的问题,您可以执行以下操作
WidgetsBinding.instance.addPostFrameCallback((_) {
final state = BlocProvider.of<UsersOwnProfileBloc>(context).state;
if (state is FetchedUserSettingState) {
publicAccount = state.userSettings.publicAccount;
}
});
推荐阅读
- django - 模型和自定义查询集之间的 Django 循环导入依赖关系
- javascript - 为什么这个正则表达式不为每个单独的匹配项
- ?
- excel - Excel表中按列值分组的随机数?
- javascript - 如何用两个过滤器制作一个过滤器?
- python - TypeError:列表索引必须是整数而不是列表
- reactjs - 使用 Material-UI JSS 和 React 将正确的项目定位为样式
- javascript - 如果 Firebase 数据库部分中未定义数据,我如何更新配置文件?
- c# - 如何模拟特定功能
- javascript - 将临时数据保存为后端面板上的子选项的最佳做法是什么?
- batch-file - 我正在用批处理文件制作一个随机数生成器