【问题标题】:Update Text() based on user input in a TextFormField() within a container in a ListVIew根据 ListVIew 中容器内 TextFormField() 中的用户输入更新 Text()
【发布时间】:2020-06-15 03:12:09
【问题描述】:

我是新来的,并且对上述内容有一个挑战。

我从 FireStore 中检索有关多个对象/文档的数据并创建一个 ListView。

逻辑或缺乏逻辑如下所示:

Container
    StreamBuilder
         ListView
             Container
                 Rows, Columns, Text and whatever to display each document from StreamBuilder.

此 ListView 包含多个 Container,其中每个 Container 显示来自一个对象的数据。在每个 Container 中都有一个 TextFormField,它需要一个 double。基于这个值,我想在同一个容器中更改一个 Text() - 一个计算。

这可能吗?如果是这样 - 如何?我知道我可以以某种方式使用 TextEditController,但是计算的结果将是可编辑的。还是?

return new ListView(//
  children: getMedicationItem(asyncSnapshot
    shrinkWrap: true,
    children: asyncSnapshot.data.documents.map((DocumentSnapshot document) {
      MyObject object = new MyObject(document, integerValue);
      backgroundColor = !backgroundColor;
      return new Container(
        color: backgroundColor? Colors.black26: Colors.white,
          child: new Row(
            children: <Widget>[
              new Flexible(
                child: TextFormField(
                  onChanged: (text) {
                    double calculation = 0.0;
                    if (text.length > 0)
                      calculation = double.tryParse(text) * 23;
                    **UPDATE "$calculation" in Text() below** 
                  },
                  keyboardType: TextInputType.number,
                  inputFormatters: [_decimal_validator],
                )
              ),
              new Flexible(
                child: Text("$calculation"),
              )
            ]
          ),
        );
      }
    ).toList(),
  )
);

【问题讨论】:

    标签: flutter flutter-layout flutter-listview flutter-text


    【解决方案1】:

    您需要做的就是使用setState 告诉 Flutter 该变量已更改,并且您希望重建使用它的任何 Widget:

    if (text.length > 0){
      setState((){
        calculation = double.tryParse(text) * 23;
      });
    }
    

    【讨论】:

    • 我有点急于在问题中删减我的代码。 ListView 在 StreamBuilder 中。并且不会调用 setState() 重绘包含 ListView 的整个 StreamBuilder?每个 Container 都有一个唯一的对象,该对象具有不同的值,应根据 TextFormField 中键入的内容进行计算,并且仅更改该 Container 中的 Text($calculation)。
    • 您需要为您想要的每个结果创建一个变量,或者为每个结果创建一个 List,然后更新您需要的结果。这将触发视图的重建。您不必担心性能。除非你视野开阔,否则应该没问题。
    • 我已经通过使用 List 解决了这个问题,但是当小部件重新绘制时,对象列表会重新下载/从 firestore 读取。这一定会在我的应用程序和 firestor 之间产生大量流量,并且有几个用户经常这样做,读取量会很大。那是另一个……挑战。谢谢。
    • @user1086500 如果答案解决了您的问题,请将其标记为正确,以便其他用户也可以找到它。还可以考虑为相关性投票。
    猜你喜欢
    • 2015-06-22
    • 1970-01-01
    • 2014-05-27
    • 1970-01-01
    • 2022-12-06
    • 2013-06-06
    • 1970-01-01
    • 2022-06-30
    • 1970-01-01
    相关资源
    最近更新 更多