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

问题描述 投票:0回答:1

我目前正在开展一个侧面项目,以了解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,
        ),
      ),
    );
  }
dart flutter bloc
1个回答
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...calls将更新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

© www.soinside.com 2019 - 2024. All rights reserved.