flutter 信息:“runZoned”已弃用,不应使用,它将在v9.0.0中删除,请改用Bloc.Bloc.transformer

mctunoxg  于 2023-01-06  发布在  Flutter
关注(0)|答案(3)|浏览(193)

当我试图在DartPad上运行我的代码时,我遇到了这个问题。

'runZoned' is deprecated and shouldn't be used. This will be removed in v9.0.0. Use Bloc.Bloc.transformer instead...

正确的更换方法是什么?
代码:

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

void main() {
  BlocOverrides.runZoned(
    () => runApp(const App()),
    blocObserver: AppBlocObserver(),
  );
}

/// Custom [BlocObserver] that observes all bloc and cubit state changes.
class AppBlocObserver extends BlocObserver {
  @override
  void onChange(BlocBase bloc, Change change) {
    super.onChange(bloc, change);
    if (bloc is Cubit) print(change);
  }

  @override
  void onTransition(Bloc bloc, Transition transition) {
    super.onTransition(bloc, transition);
    print(transition);
  }
}
zlhcx6iw

zlhcx6iw1#

解决方案是:

void main() {
  Bloc.observer = AppBlocObserver();
  runApp(const App());
}
nx7onnlm

nx7onnlm2#

上述代码虽然看起来无害,但实际上可能会导致许多难以跟踪的 * 错误 *。由于使用了runZoned,因此在转换到 * BlocOverrides * API时发现了 * Flutter * 中的一些错误/限制

    • 一个

修复此问题,请使用Bloc团队提供的以下方法创建***观察器***和***转换器***

void main() {
  Bloc.observer = AppBlocObserver();
  Bloc.transformer = customEventTransformer();

  // ...
}
    • 您可以在他们的官方网站上阅读更多关于拦截的信息。**
fd3cxomn

fd3cxomn3#

对我来说,这起了作用:
之前:

BlocOverrides.runZoned( () {
  runApp(
    BlocProvider(
      create: (_) => AppBloc(
        screen: AppScreen.home,
      )..add(const AppStarted(screen: AppScreen.home)),
      child: const App(),
    ),
  );
},
blocObserver: SimpleBlocObserver(),

);
之后:

Bloc.observer = SimpleBlocObserver();
runApp(
  BlocProvider(
    create: (_) => AppBloc(
      screen: AppScreen.home,
    )..add(const AppStarted(screen: AppScreen.home)),
    child: const App(),
  ),
);

相关问题