【问题标题】:How to set local state with flutter bloc如何使用颤振块设置本地状态
【发布时间】:2021-10-02 11:40:59
【问题描述】:

我有一个使用 Bloc 模式进行状态管理的 Flutter 应用。

我在存储状态的页面中有一个局部变量。

PageA:

// Outside build function 
List<String> _names = []; // local variable to show the changes visually
.
.
.
// Inside build function
return Scaffold(
 body: BlocConsumer<PageABloc, PageAState>(
        builder: (context, state) {
          if (state is PageASuccessState) { 
            _names = state.names;                              // here is problem
            return _body();
          } else if (state is PageALoadingState ||
              state is PageAInitState) {
            return Center(child: CircularProgressIndicator());
          } else
            return Center(child: Text("Something went wrong"));
        },
        listener: (context, state) {},
      ),
);

用户点击_body()中的保存按钮时,我只需要更新state.names的状态,但要向用户显示视觉变化,我正在使用_names 局部变量。

如何将state.names的初始值加载到_names

我尝试的代码不起作用,因为它会在每一帧上重置对 _names(local) 的任何更改。

我试过类似的东西,

if (state is PageASuccessState) { 
            final List<String> _n = state.names;
            _names.addAll(_n);
            return _body(_width);
   } 

但这只是将state.names 重复添加到_names,无限次。

救命!

【问题讨论】:

    标签: flutter bloc flutter-bloc


    【解决方案1】:

    发生这种情况是因为每次调用 BlocBuilder 的构建器时,您的状态都包含 names 列表。

    您应该将List&lt;String&gt; _names = [] 替换为LinkedHashSet&lt;String&gt; _names = LinkedHashSet&lt;String&gt;()

    LinkedHashSet 的工作方式与列表完全相同,但不允许重复。您可以通过调用将其更改为列表 _names.iterator.toList(); 随时随地。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-17
      • 2020-02-07
      相关资源
      最近更新 更多