gpt4 book ai didi

Flutter BLoC : Navigator. 在 build() 方法中弹出 StreamBuilder

转载 作者:IT王子 更新时间:2023-10-29 06:45:20 27 4
gpt4 key购买 nike

我正在遵循 BLoC 模式并订阅流,并对构建方法中的状态变化使用react。加载数据后,我想关闭屏幕。

  @override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Bloc'),
),
body: SafeArea(
child: StreamBuilder<UserState>(
stream: _userBloc.user,
initialData: UserInitState(),
builder: (context, snapshot) {
if (snapshot.data is UserInitState) {
return _buildInit();
}
if (snapshot.data is UserDataState) {
Navigator.pop(context, true);
return Container();
}
if (snapshot.data is UserLoadingState) {
return _buildLoading();
}
},
),
),
);
}

当我在 build() 方法中执行 Navigator.pop(context, true); 时,我得到:

I/flutter ( 4360): ══╡ EXCEPTION CAUGHT BY ANIMATION LIBRARY ╞═════════════════════════════════════════════════════════
I/flutter ( 4360): The following assertion was thrown while notifying status listeners for AnimationController:
I/flutter ( 4360): setState() or markNeedsBuild() called during build.
I/flutter ( 4360): This Overlay widget cannot be marked as needing to build because the framework is already in the
I/flutter ( 4360): process of building widgets. A widget can be marked as needing to be built during the build phase
I/flutter ( 4360): only if one of its ancestors is currently building. This exception is allowed because the framework
I/flutter ( 4360): builds parent widgets before children, which means a dirty descendant will always be built.
I/flutter ( 4360): Otherwise, the framework might not visit this widget during this build phase.

在 BLoC 模式中处理此类情况的正确方法是什么?

我提出的解决方案之一是开始在 initState() 上收听流。在这种情况下,我需要 broadcast() 我的流,因为我有 2 个订阅者。

有没有更好的解决方案?

最佳答案

我想我已经为您找到了解决方案。 (请检查)

让你的代码看起来像:

Widget build(BuildContext context) {
// other stuff

if (snapshot.data is UserDataState) {
myCallback(() {
Navigator.pop(context, true);
});
}

// other stuff
}
// after build method (but still in the same class,...) write below method

void myCallback(Function callback) {
WidgetsBinding.instance.addPostFrameCallback((_) {
callback();
});
}

希望对您有所帮助。试试吧,请在这里报告以帮助其他人!

Source (flutter_bloc Login medium article)

Description

关于Flutter BLoC : Navigator. 在 build() 方法中弹出 StreamBuilder,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55665643/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com