简体   繁体   English

带有 flutter 块的控制小部件

[英]Controll widget with flutter bloc

Project项目

Hi, I recently discovered flutter bloc and now I'm trying to understand how exactly this works.嗨,我最近发现了 flutter 集团,现在我试图了解它是如何工作的。 My goal is to separate logic from widget classes in order to easily manage my projects.我的目标是将逻辑与小部件类分开,以便轻松管理我的项目。

Problem问题

I'm stuck with something that is very simple using classic setState, but I was trying to achieve this with bloc.我坚持使用经典 setState 非常简单的东西,但我试图用 bloc 来实现这一点。

Here is an old widget of mine这是我的一个旧小部件

Widget build(BuildContext context) {
 return AnimatedOpacity(
   duration: Duration(milliseconds: 200),
   opacity: _opacity,
   curve: Curves.easeInOut,
   child: Text(
     _currentTitle,
     style: TitleTextStyle,
   ),
 );
}

Is it possible to control _opacity and _currentTitle from a bloc?是否可以从一个集团控制 _opacity 和 _currentTitle? Something like this:像这样的东西:

List<String> titles = ['title1', 'title2', ....];
int myIndex;

@override
Stream<SomeBlocState> mapEventToState(SomeEvent event,) 
async* {

....
if (event is SomeSpecificEvent)
  setWidgetTitle(titles[myIndex]);
....
}

I am trying to avoid buiding different state for each possible title, that would be a mess我试图避免为每个可能的标题构建不同的 state,那将是一团糟

Thanks谢谢

You can try and make the title widget build in a StreamBuilder instead.您可以尝试在StreamBuilder中构建标题小部件。 That will give you a clean separation of responsibilities.这将使您清楚地分离职责。 So that the BLoC doesn't know of any state changes or widget specific things.因此 BLoC 不知道任何 state 更改或小部件特定的事情。

Widget build(BuildContext context) {
 return AnimatedOpacity(
      duration: Duration(milliseconds: 200),
      opacity: _opacity,
      curve: Curves.easeInOut,
      child: StreamBuilder<String>(
        stream: myBloc.title,
        builder: (_, snap) {
          return Text(
            snap?.data ?? 'Some default',
            style: TitleTextStyle,
          );
        }
      ),
    );
}

And you create some logic in your BLoC that emits the title as needed然后在 BLoC 中创建一些逻辑,根据需要发出标题

List<String> titles = ['title1', 'title2', ....];
int myIndex;
final _myObservableTitles = PublishSubject();

Stream<String> get title => _myObservableTitles.stream;

....
if (event is SomeSpecificEvent)
  _myObservableTitles.add(titles[myIndex]);
....

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM