如何以干净的方式管理抖动状态?

时间:2019-11-13 14:30:32

标签: flutter bloc

我不熟悉flutter,试图学习状态管理,我正在学习Bloc模式,并探索flutter_block,当在UI层观察状态变化时,我们可以像下面这样使用InheritedWidget

  Widget build(BuildContext context) {
    return Container(
        color: Colors.grey[200],
        child: Column(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: <Widget>[
              Container(
                  child: BlocBuilder<RoundBloc, RoundState>(
                      bloc: _roundBloc,
                      builder: (context, state) => _progressIndicator(state))),
              Container(
                  child: BlocBuilder<RoundBloc, RoundState>(
                bloc: _roundBloc,
                builder: (context, state) => _memorizingCards(state),
              )),
              Container(
                  child: BlocBuilder<RoundBloc, RoundState>(
                bloc: _roundBloc,
                builder: (context, state) => _actions(state),
              ))
            ]));
  }

  Widget _progressIndicator(RoundState state) {
    if (state is RoundCreated) {
      return Text('${state.round.memoIndex}/${state.round.cards.length}');
    } else if (state is RoundMemoIndexUpdated) {
      return Text('${state.round.memoIndex}/${state.round.cards.length}');
    } else {
      return Text('0/0');
    }
  }

  Widget _memorizingCards(RoundState state) {
    if (state is RoundCreated) {
      return _carouse(state.round);
    } else if (state is RoundMemoIndexUpdated) {
      return _carouse(state.round);
    } else {
      return poker.Card.back();
    }
  }

  CarouselSlider _carouse(RoundModel round) {
    return CarouselSlider(
        initialPage: 0,
        height: 300,
        enlargeCenterPage: true,
        enableInfiniteScroll: false,
        onPageChanged: (index) {
          _memoIndexUpdate(index, round);
        },
        items: round.cards.map((card) => poker.Card.of(card)).toList());
  }

  Widget _actions(RoundState state) {
    if (state is RoundCreated) {
      return RaisedButton(
          textColor: Colors.white,
          color: Colors.amber,
          child: Text('完成'),
          onPressed: _finish(state.round));
    } else {
      return RaisedButton(
        textColor: Colors.white,
        color: Colors.amber,
        child: Text('开始'),
        onPressed: _shuffleCards,
      );
    }
  }

  void _shuffleCards() {
    _roundBloc.add(RoundCreate(RoundModel(shuffledDeck())));
  }

  _finish(RoundModel round) {
    return () => _roundBloc.add(RoundFinishMemo(round));
  }

  void _memoIndexUpdate(int index, RoundModel round) {
    _roundBloc.add(RoundUpdateMemoIndex(round, index));
  }

我必须在UI代码中到处编写BlocBuilder,因为我只想针对特定状态更新UI的某些部分,我想知道是否可以编写类似于以下代码的代码:

_roundBloc.listen((state) {
 if (state is RoundCreated) {
   setState(() {
     _localState = state.someValue;
   });
 }
});

通过这种方式,我的UI代码只需要关心本地状态,而无需将BlocBuilder包装到各处,而是只侦听bloc状态更改并相应地更新本地状态。

0 个答案:

没有答案