如何使用 BLoC 模式管理表单状态?

Q. *_*ude 1 dart flutter bloc

我目前正在做一个辅助项目来了解 Rx 和 BLoC 模式。

我想在不使用任何setState().

我已经有一个 BLoC 来管理我的“事件”,这些事件存储在 SQLite 数据库中并在验证此表单后添加。

我是否需要专门为此 UI 部分创建一个需要的 BLoC,以及如何创建?保留这样的代码可以吗?我应该更改我的实际 BLoC 吗?

你可以在这里找到我当前的代码:

class _EventsAddEditScreenState extends State<EventsAddEditScreen> {
  bool hasDescription = false;
  bool hasLocation = false;  
  bool hasChecklist = false;

  DateTime eventDate;
  TextEditingController eventNameController =  new TextEditingController();
  TextEditingController descriptionController =  new TextEditingController();

  @override
  Widget build(BuildContext context) {
    final eventBloc = BlocProvider.of<EventsBloc>(context);
    return BlocBuilder(
      bloc: eventBloc,
      builder: (BuildContext context, EventsState state) {
        return Scaffold(
          body: Stack(
            children: <Widget>[
              Column(children: <Widget>[
                Expanded(
                    child: ListView(
                  shrinkWrap: true,
                  children: <Widget>[
                    _buildEventImage(context),
                    hasDescription ? _buildDescriptionSection(context) : _buildAddSection('description'),
                    _buildAddSection('location'),
                    _buildAddSection('checklist'),
                    //_buildDescriptionSection(context),
                  ],
                ))
              ]),
              new Positioned(
                //Place it at the top, and not use the entire screen
                top: 0.0,
                left: 0.0,
                right: 0.0,
                child: AppBar(
                  actions: <Widget>[
                    IconButton(icon: Icon(Icons.check), onPressed: () async{
                      if(this._checkAllField()){
                        String description = hasDescription ? this.descriptionController.text : null;
                        await eventBloc.dispatch(AddEvent(Event(this.eventNameController.text, this.eventDate,"balbla", description: description)));
                        print('Saving ${this.eventDate} ${eventNameController.text}');
                      }
                    },)
                  ],
                  backgroundColor: Colors.transparent, //No more green
                  elevation: 0.0, //Shadow gone
                ),
              ),
            ],
          ),
        );
      },
    );
  }

  Widget _buildAddSection(String sectionName) {
    TextStyle textStyle = TextStyle(
        color: Colors.black87, fontSize: 18.0, fontWeight: FontWeight.w700);
    return Container(
      alignment: Alignment.topLeft,
      padding:
          EdgeInsets.only(top: 20.0, left: 40.0, right: 40.0, bottom: 20.0),
      child: FlatButton(
        onPressed: () {
          switch(sectionName){
            case('description'):{
              this.setState((){hasDescription = true;});
            }
            break;
            case('checklist'):{
              this.setState((){hasChecklist = true;});
            }
            break;
            case('location'):{
              this.setState((){hasLocation=true;});
            }
            break;
            default:{

            }
            break;
          }
        },
        padding: EdgeInsets.only(top: 0.0, left: 0.0),
        child: Text(
          '+ Add $sectionName',
          style: textStyle,
        ),
      ),
    );
  }
Run Code Online (Sandbox Code Playgroud)

Mar*_*ura 5

让我们一步步解决这个问题。

你的第一个问题: 我是否需要专门为这个 UI 部分创建一个需要的 BLoC?

那么这与您的需求和您的应用程序有关。如果需要,您可以为每个屏幕设置一个 BLoC,但您也可以为 2 或 3 个小部件设置一个 BLoC,对此没有规定。如果您认为在这种情况下为您的屏幕实现另一个 BLoC 是一种好方法,因为代码将更具可读性、组织性和可扩展性,您可以这样做,或者如果您认为这样做更好,则只制作一个包含所有内容的块,您可以自由也到此为止。

你的第二个问题:如何?

那么在你的代码中我只看到setState调用,_buildAddSection所以让我们改变这个编写一个新的 BLoc 类并使用RxDart流处理状态更改。

class LittleBloc {
  // Note that all stream already start with an initial value. In this case, false.

  final BehaviorSubject<bool> _descriptionSubject = BehaviorSubject.seeded(false);
  Observable<bool> get hasDescription => _descriptionSubject.stream;

  final BehaviorSubject<bool> _checklistSubject = BehaviorSubject.seeded(false);
  Observable<bool> get hasChecklist => _checklistSubject.stream;

  final BehaviorSubject<bool> _locationSubject = BehaviorSubject.seeded(false);
  Observable<bool> get hasLocation => _locationSubject.stream;

  void changeDescription(final bool status) => _descriptionSubject.sink.add(status);
  void changeChecklist(final bool status) => _checklistSubject.sink.add(status);
  void changeLocation(final bool status) => _locationSubject.sink.add(status);

  dispose(){
    _descriptionSubject?.close();
    _locationSubject?.close();
    _checklistSubject?.close();
  }
}
Run Code Online (Sandbox Code Playgroud)

现在我将在您的小部件中使用这个 Bloc。我会将整个build方法代码与更改一起放在下面。基本上我们将用于StreamBuilder在小部件树中构建小部件。

 final LittleBloc bloc = LittleBloc(); // Our instance of bloc 
 @override
  Widget build(BuildContext context) {
    final eventBloc = BlocProvider.of<EventsBloc>(context);
    return BlocBuilder(
      bloc: eventBloc,
      builder: (BuildContext context, EventsState state) {
        return Scaffold(
          body: Stack(
            children: <Widget>[
              Column(children: <Widget>[
                Expanded(
                    child: ListView(
                      shrinkWrap: true,
                      children: <Widget>[
                        _buildEventImage(context),
                        StreamBuilder<bool>(
                          stream: bloc.hasDescription,
                          builder: (context, snapshot){
                            hasDescription = snapshot.data; // if you want hold the value
                            if (snapshot.data)
                              return _buildDescriptionSection(context);//we got description true

                            return buildAddSection('description'); // we have description false
                          }
                        ),
                        _buildAddSection('location'),
                        _buildAddSection('checklist'),
                        //_buildDescriptionSection(context),
                      ],
                    ),
                ),
              ]
              ),
              new Positioned(
                //Place it at the top, and not use the entire screen
                top: 0.0,
                left: 0.0,
                right: 0.0,
                child: AppBar(
                  actions: <Widget>[
                    IconButton(icon: Icon(Icons.check), 
                      onPressed: () async{
                        if(this._checkAllField()){
                          String description = hasDescription ? this.descriptionController.text : null;
                          await eventBloc.dispatch(AddEvent(Event(this.eventNameController.text, this.eventDate,"balbla", description: description)));
                          print('Saving ${this.eventDate} ${eventNameController.text}');
                        }
                      },
                    ),
                  ],
                  backgroundColor: Colors.transparent, //No more green
                  elevation: 0.0, //Shadow gone
                ),
              ),
            ],
          ),
        );
      },
    );
  }
Run Code Online (Sandbox Code Playgroud)

并且setState您的_buildAddSection. 只需要更改一个switch语句。的changes...通话将更新集团类流,这将使重建监听的流窗口小部件。

switch(sectionName){
  case('description'):
    bloc.changeDescription(true);
    break;

  case('checklist'):
    bloc.changeChecklist(true);
    break;

  case('location'):
    bloc.changeLocation(true);
    break;

  default:
    // you better do something here!
    break;
}
Run Code Online (Sandbox Code Playgroud)

并且不要忘记bloc.dispose()在 WidgetStatedispose方法内部调用。