标签: flutter-bloc

Flutter 从其他 Bloc 监听 Bloc 状态

您好,我正在尝试从其他集团中收听集团的状态。我正在使用这个包https://pub.dev/packages/bloc

从我的UserBloc我想听AuthBloc,当它具有AuthenticationAuthenticated状态时,UserBloc应该触发一个事件。

final UserRepository userRepository;
final authBloc;
StreamSubscription authSub;
UserBloc({ @required this.userRepository, @required this.authBloc}) {
    authSub = authBloc.listen((stateAuth) {

      //here is my problem because stateAuth, even is AuthenticationAuthenticated it return always false.
      if (stateAuth is AuthenticationAuthenticated) {
        this.add(GetUser())  ;
      }
    });
  }

@override
  Future<void> close() async {
    authSub?.cancel();
    super.close();
  }
Run Code Online (Sandbox Code Playgroud)

现在我有这个问题:在调试时我试图打印 stateAuth 它返回:

stateAuth = {AuthenticationAuthenticated} AuthenticationAuthenticated
   props = {_ImmutableList} size = 0
Run Code Online (Sandbox Code Playgroud)

但是stateAuth 是 AuthenticationAuthenticated返回始终为 false。

有没有办法从其他 Bloc …

flutter flutter-bloc

9
推荐指数
4
解决办法
1万
查看次数

莫代尔底片和块

当我运行类似于以下代码的代码时,出现以下错误:使用不包含 Bloc 的上下文调用 BlocProvider.of()。

复制

BlocProvider(
          create: (context) => getIt<TheBloc>()
          child: BlocBuilder<TheBloc, TheState>(
          build: (context, state) =>
          MaterialButton(
            onPressed: () => _showModal(context),
            child: const Text('SHOW BLOC MODAL'),
),
Run Code Online (Sandbox Code Playgroud)

...

void _showModal(BuildContext context) {
  showModalBottomSheet<void>(
    context: context,
    builder: (_) {
          return MaterialButton(
               onPressed() {
                       context.bloc<TheBloc>().add(
                         TheEvent.someEvent(),
                       );
               }
              child: Text('Press button to add event to bloc')
          );
    },
  );
}
Run Code Online (Sandbox Code Playgroud)

flutter bloc flutter-bloc

9
推荐指数
1
解决办法
1万
查看次数

Flutter bloc state 在更新 List/array 索引时不更新状态

我正在尝试在 bloc 类中实现复选框逻辑。为此,我List<bool> checked在块类中创建的代码如下。当CheckBoxClicked事件触发时,状态第一次更新,我可以看到该框已选中。

class CartProductsListBloc
    extends Bloc<CartProductsListEvent, CartProductsListState> {
  CartProductsListBloc() : super(InitialCartProductsListState());

  final ProductRepository productRepository = ProductRepository();
  List<bool> checked = List<bool>();
  var productsList;

  @override
  Stream<CartProductsListState> mapEventToState(
      CartProductsListEvent event) async* {
    if (event is FetchCartProductsList) {
      yield FetchingInProgress();
      try {
        productsList = await productRepository.loadListOfProductInUserCart();
        //initialize checked according to productsList
        for (int i = 0; i < productsList.length; i++) {
          checked.add(false);
        }
        yield FetchCartProductsListSuccess(
            productsList: productsList, checked: checked);
      } catch (error) {
        yield FetchCartProductsListFail(
            error: 'Fail to …
Run Code Online (Sandbox Code Playgroud)

equatable flutter-bloc

9
推荐指数
1
解决办法
1197
查看次数

谁能说出 Flutter 中“flutter_bloc”和“bloc”包的区别

我正在 Flutter 中开始使用 Bloc。谁能告诉我什么是真正的“flutter_bloc”和“bloc”包我有这些问题。

  1. 他们是一样的吗?
  2. 何时/如何使用它。
  • 谢谢

flutter flutter-test flutter-dependencies flutter-packages flutter-bloc

9
推荐指数
2
解决办法
985
查看次数

如何在 flutter 上使用 go_router 将块传递到另一个屏幕

在 Flutter 上,我想将本地传递bloc到另一个屏幕。这就是我在使用默认导航器时将块传递到新路线的方式。

Navigator.of(context).push(
      MaterialPageRoute<void>(
        builder: (BuildContext context) =>  BlocProvider.value(
          value: localBloc,
          child: MyPage(),
      ),
    ));
Run Code Online (Sandbox Code Playgroud)

但现在,我正在使用该go_router包进行导航。我怎样才能将本地提供bloc给我想要使用的屏幕BlocProvider.value()

dart flutter bloc flutter-bloc flutter-go-router

9
推荐指数
2
解决办法
3816
查看次数

如何在Flutter App中正确使用BlocListener和BlocProvider

我在 Flutter 应用程序中使用 flutter_bloc 4.0.0,我使用 Felix Angelov 的示例(https://medium.com/flutter-community/firebase-login-with-flutter-bloc-47455e6047b0)来实现登录或使用块模式的登录流程。它工作正常,但在我更新我的 Flutter 并检查我的代码后,我发现了一系列错误。我不明白他们为什么要来,因为上周一切都很好。小部件的构建方法中的块的实现对我来说突然变得错误了。我收到错误:

\n\n

1.“BlocListener的\xe2\x80\x98A值类型不能从方法构建中返回\xe2\x80\x99,因为它有一个widget的返回类型”

\n\n
    \n
  1. \xe2\x80\x98BlocProvider> 的值类型可以从方法构建中返回\xe2\x80\x99,因为它的返回类型为 widget\xe2\x80\x99
  2. \n
\n\n

第一个错误的代码

\n\n
class LoginForm extends StatefulWidget {\n  final UserRepository _userRepository;\n\n  LoginForm({Key key, @required UserRepository userRepository})\n      : assert(userRepository != null),\n        _userRepository = userRepository,\n        super(key: key);\n\n  State<LoginForm> createState() => _LoginFormState();\n}\n\nclass _LoginFormState extends State<LoginForm> {\n  final TextEditingController _emailController = TextEditingController();\n  final TextEditingController _passwordController = TextEditingController();\n\n  LoginBloc _loginBloc;\n\n  UserRepository get _userRepository => widget._userRepository;\n\n  bool get isPopulated =>\n      _emailController.text.isNotEmpty && _passwordController.text.isNotEmpty;\n\n  bool isLoginButtonEnabled(LoginState state) …
Run Code Online (Sandbox Code Playgroud)

flutter flutter-packages flutter-bloc

8
推荐指数
1
解决办法
4万
查看次数

放置在 flutter bloc 中

在下面的代码中,profileBloc 在 EditProfileScreenState 的 didChangeDependency() 方法中初始化。

我们应该在 EditProfileScreenState 类上调用 dispose 方法来处置 profileBloc 吗?

如果是这样,应该如何处置 profileBloc 方法,因为 ProfileBloc 类扩展了没有 dispose 方法的 Bloc 类?

class Profile extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      create: (BuildContext context) => ProfileBloc(AuthRepo()),
      child: ProfileScreen(),
    );
  }
}

class ProfileScreen extends StatefulWidget {

  @override
  EditProfileScreenState createState() => EditProfileScreenState();
}


class EditProfileScreenState extends State<ProfileScreen> {

  ProfileBloc profileBloc;

  @override
  void didChangeDependencies() {
    profileBloc = BlocProvider.of<ProfileBloc>(context);
    super.didChangeDependencies();
  }

  @override
  void dispose() {
    // TODO: implement dispose
    //profileBloc.dispose() …
Run Code Online (Sandbox Code Playgroud)

dart flutter flutter-bloc

8
推荐指数
1
解决办法
2万
查看次数

如何使用flutter_bloc 8+、go_router +6和refreshListenable

我使用 go_router 进行导航,使用 flutter_bloc 进行状态管理。

我想使用refreshListenable并在我的GoRouter配置中监听我的AuthBloC事件,但是,我无权访问我的GoRouter中的上下文,并且我不想提供它。

我发现的大多数答案都已过时,或者使用 StreamBuilder 等替代方案在事件更改时重新渲染整个应用程序,这并不理想。

如何在上下文之外监听我的 AuthEvents?

主程序.dart

return RepositoryProvider.value(
      value: authRepo,
      child: BlocProvider(
        create: (_) => AuthBloc(authRepo),
        child: MaterialApp.router(
          ...
          routerConfig: Routes.router,
          builder: (_, child) {
            final isRTL = LocaleSettings.currentLocale == AppLocale.ar;

            return Directionality(
              textDirection: isRTL ? TextDirection.rtl : TextDirection.ltr,
              child: child!,
            );
          },
        ),
      ),
Run Code Online (Sandbox Code Playgroud)

块/auth/auth_bloc.dart

class AuthBloc extends Bloc<AuthEvent, AuthState> {
  AuthBloc(this._authenticationRepository) : super(const AuthState()) {
    on<AuthEvent>((event, emit) {
      event.when(
        authStateChangeEvent: (account) => _authStateChangeEvent(account, emit),
        signOutEvent: _signOutEvent,
        verifyAccount: _verifyAccount,
      );
    });
    _userSubscription = …
Run Code Online (Sandbox Code Playgroud)

dart firebase-authentication flutter flutter-bloc flutter-go-router

8
推荐指数
0
解决办法
2095
查看次数

从一个选项卡滑动到另一个选项卡时,TabView 不保留状态

上下文:这里的页面可以TabView在所有这些选项卡使用的选项卡之间导航flutter_bloc(版本 6.0.1)。

问题:当滑动到任何选项卡时,状态不会被保留,整个小部件树正在重建,如下面的 gif 所示

滑动时未保留页面视图状态

这是build()方法:

 @override
  Widget build(BuildContext context) {
    super.build(context);
    return DefaultTabController(
      initialIndex: 0,
      length: 3,
      child: Scaffold(
        backgroundColor: Colors.white,
        appBar: _buildAppBarWithTabs(),
        body: TabBarView(
          children: <Widget>[
            defaultViewforCategory(1), //Women
            defaultViewforCategory(3), //Men
            defaultViewforCategory(2), //Kids
          ],
        ),
      ),
    );
  }
Run Code Online (Sandbox Code Playgroud)

下面是函数的实现 defaultViewforCategory()

Widget defaultViewforCategory(int mainCategoryId) {
    return PageStorage(
      bucket: bucket,
      key: PageStorageKey(mainCategoryId),
      child: ConstrainedBox(
        constraints: BoxConstraints(maxWidth: 1200),
        child: ListView(
          scrollDirection: Axis.vertical,
          children: <Widget>[
            Padding(
              padding: const EdgeInsets.only(bottom: 150),
              child: Container(
                height: 800,
                child: …
Run Code Online (Sandbox Code Playgroud)

state-management flutter flutter-bloc

7
推荐指数
1
解决办法
87
查看次数

使用带有 flutter_bloc 的 Equatable 类

为什么当我们需要使用带有 flutter_bloc 的 Equatable 类时?,还有我们需要的道具呢?这是在颤振中以块模式创建状态的示例代码,请我需要详细的答案。先感谢您

abstract class LoginStates extends Equatable{}

class LoginInitialState extends LoginStates{
  @override
  List<Object> get props => [];

}
Run Code Online (Sandbox Code Playgroud)

equatable flutter flutter-bloc

7
推荐指数
2
解决办法
2765
查看次数