【问题标题】:New state overwrite previous state新状态覆盖之前的状态
【发布时间】:2021-06-22 21:16:48
【问题描述】:

所以我创建了List<Map<String, dynamic>> 的状态,但是当我尝试添加一个新元素时,它会覆盖所有元素。例如,第一次我在地址值 1 上添加了一个新元素,第二次我在地址值 9 上添加了一个新元素,但是所有元素都被新元素覆盖(列表的所有元素,地址值变为 9)。你们有没有和我一样的问题?我被困了好几天了

在我添加一个新元素之前:

添加新元素后:

这是我添加新元素的代码,state.values 来自 BlocListener,它在状态更改时进行监听并携带值

...
List<Map<String, dynamic>> _records = [];

Widget build(BuildContext context) {
    final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
    return Scaffold(
      key: _scaffoldKey,
      appBar: AppBar(
        centerTitle: true,
        backgroundColor: ColorConst.appBarColor,
        title: Text(
          widget.field!.label!,
          style: TextStyle(color: Colors.white),
        ),
      ),
      body: SafeArea(
        child: BlocListener<ViewPageBloc, ViewPageState>(
            bloc: _formViewBloc,
            listener: (context, state) {
              if (state.isProcessing) {

                if (isSaveAndNew) {
                  _records.add(state.values);

                  _formViewBloc.add(ViewPageLoadFormModel(
                      modelName: (widget.field as RelationalField)
                          .relation!
                          .modelName));
                  isSaveAndNew = false;
                }
              }
            }
        .
        .
        .
        )
      )
    )
}

【问题讨论】:

    标签: flutter dart bloc


    【解决方案1】:
    final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
    

    不要在构建方法上声明它。您的构建方法被触发两次。 改用 ScaffoldMessenger()。

    final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
    Widget build(BuildContext context) {
        return Scaffold(
          key: _scaffoldKey,
          appBar: AppBar(
            centerTitle: true,
            backgroundColor: ColorConst.appBarColor,
            title: Text(
              widget.field!.label!,
              style: TextStyle(color: Colors.white),
            ),
          ),
          body: SafeArea(
            child: BlocListener<ViewPageBloc, ViewPageState>(
                bloc: _formViewBloc,
                listener: (context, state) {
                  if (state.isProcessing) {
    
                    if (isSaveAndNew) {
                      _records.add(state.values);
    
                      _formViewBloc.add(ViewPageLoadFormModel(
                          modelName: (widget.field as RelationalField)
                              .relation!
                              .modelName));
                      isSaveAndNew = false;
                    }
                  }
                }
            .
            .
            .
            )
          )
        )
    }
    
    

    【讨论】:

    • 我已经完成了,但它仍然会覆盖所有元素。
    猜你喜欢
    • 2021-11-09
    • 2021-09-05
    • 2018-09-29
    • 2023-01-28
    • 2019-06-15
    • 2021-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多