2

我是 BLoC 模式的新手,出现了一个我无法在其他地方找到的问题。使用 flutter_bloc 库,我可以访问 BlocBuilder 小部件,只要 BLoC 的状态发生变化,它就会重新构建。由于我正在处理独立于框架的状态,是否有必要将父小部件(比如包含来自 BLoC 的数据的卡片)声明为有状态?

我已经能够成功地将 BlocBuilders 实现为有状态和无状态小部件的子级,但我无法决定哪种是最佳实践,或者是否存在任何需要有状态的情况。

如果您不需要更新 BlocBuilder 之外的任何内容,我想我会说无状态很好,但是如果您要添加诸如 RefreshIndicator 之类的东西并且必须为此实现逻辑,那么您将需要有状态(并有条件地将事件传递给 BLoC)。那是对的吗?

我确定我在这里过度解释了,但本着这种精神,如果有助于理解我的问题,我在下面提供了一些代码。

这是与我的项目有关的简化无状态实现:


class WeatherCard extends StatelessWidget {

  /// You can assume that the following is happening:
  ///   1) There is a BlocProvider in the parent widget which
  ///      will implement this WeatherCard.
  ///
  ///   2) The WeatherLoaded state in the WeatherBloc provides an 
  ///      instance of a WeatherModel which contains all of the data
  ///      from a weather API.
  ///

  @override
  Widget build(BuildContext context) {
    return Card(
      child: BlocBuilder(
        bloc: BlocProvider.of<WeatherBloc>(context),
        builder: (BuildContext context, WeatherState state) {
          if (state is WeatherLoading) {
            return Text('Loading...');
          } else if (state is WeatherLoaded) {
            return Text(state.weatherModel.temp.toString());
          } else {
            return Text('Error!');
          }
        }
    );
  }
}

和有状态的实施:


// You can make the same assumptions here as in the Stateless implementation.

class WeatherCard extends StatefulWidget {
  @override
  _WeatherCardState createState() => _WeatherCardState();
}

class _WeatherCardState extends State<WeatherCard> {
  @override
  Widget build(BuildContext context) {
    return Card(
      child: BlocBuilder(
        bloc: BlocProvider.of<WeatherBloc>(context),
        builder: (BuildContext context, WeatherState state) {
          if (state is WeatherLoading) {
            return Text('Loading...');
          } else if (state is WeatherLoaded) {
            return Text(state.weatherModel.temp.toString());
          } else {
            return Text('Error!');
          }
        }
    );
  }
}


4

1 回答 1

4

通过使用 Bloc,您应该能够几乎完全避免声明有状态小部件,尽管这当然是可能的,有时也可以使用有状态小部件或其他状态管理策略。

如果您有条件地将逻辑传递给 bloc,您可能需要考虑将条件逻辑移动到 bloc 本身并只传递触发条件的事件。

也绝对有可能在 bloc 中声明多个 Streams,在 UI 中声明多个 StreamBuilders 来监听同一个 Bloc,尽管我不知道 flutter_bloc 库是否可行。如果您使用的是flutter_bloc,看起来每个块只能使用一个流。您也可以改用此处描述的策略/BlocProvider 。

对于对程序逻辑没有任何/太大影响的 UI 中的一些小更改,使用有状态小部件来处理状态可能比将状态保留在 Bloc 中更容易。对于所有情况,没有真正的正确或错误答案,由您决定从长远来看更容易构建和维护的内容。但是,如果您的架构保持一致,您的程序可能会更容易阅读并且更容易找到您想要更改的内容。因此,如果您使用 bloc,则意味着处理 Blocs 中的所有状态并完全或几乎完全使用无状态小部件构建您的 UI。

于 2019-04-08T18:17:46.193 回答