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

时间:2019-04-24 20:35:24

标签: 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,
        ),
      ),
    );
  }

1 个答案:

答案 0 :(得分:2)

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

您的第一个问题: 我是否需要为此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();
  }
}

现在,我将在您的小部件中使用此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
                ),
              ),
            ],
          ),
        );
      },
    );
  }

您的setState中不会再有_buildAddSection个呼叫。只需更改一个switch语句。 changes...调用将更新BLoc类中的流,这将重建正在侦听该流的小部件。

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;
}

请不要忘记在WidgetState bloc.dispose()方法内部调用dispose