3

我喜欢 Flutter 热重载,但发现我的 BLoC 中的状态没有保留。每次我进行热重载时它都会重置。

有没有办法保存该状态,使其在热重载后仍然存在?(我可以接听电话还是什么?)

谢谢你的时间!

4

1 回答 1

2

@RémiRousselet 出现在现场!我将状态保持在有状态小部件之外!为了清楚起见,这里是之前和之后的代码。(MaterialApp home: 参数和 _MyHomePageState.build 是真正变化的地方)

错误代码:

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      home: BlocProvider<PandemicBloc>(
          bloc: PandemicBloc(), child: MyHomePage(title: 'Pandemic Tracker')),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;

  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final PandemicBloc pandemicBloc = BlocProvider.of<PandemicBloc>(context);
  int _currentTab = 0;

  Widget build(BuildContext context) {
    return DefaultTabController(...

好代码:

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      home: MyHomePage(title: 'Pandemic Tracker'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;

  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _currentTab = 0;
  final _pandemicBloc = PandemicBloc();

  Widget build(BuildContext context) {
    return BlocProvider<PandemicBloc>(
      bloc: _pandemicBloc,
      child: DefaultTabController(...
于 2019-03-14T14:44:19.807 回答