获取动态列表小部件的值 - Flutter

4

我已经成功地将Flutter和Firestore连接起来,制作了一个动态问卷。

我的自定义Question小部件只是一个包含问题字符串的Text(),以及一个Slider(),让用户可以从1到5给出答案。

现在问题已经显示出来了,我该如何获取值呢?

以下是我的代码:

var questions = <Widget>[];

//Async read to the DB
Future query() async {
  var snap = await Firestore.instance
    .collection("Forms")
    .document(formID)
    .get();

  var arr = <Widget>[]; //just a temp holder of the widgets
  for(String q in list){
    arr.add(Question(min: 1.0, max: 5.0, question: q, value: 1.0,));
  }

  setState(() {
    questions = arr;
  });
}

然后在我正在渲染的构建中:

Scaffold(
  body:Container(
    child:Column(
      children: <Widget>[
        Text("Title"),
        Column(
          children: questions,
        ),
        RaisedButton(
          onPressed: () => sendFeedback(),
          color: Colors.redAccent,
          textColor: Colors.white,
          child: Text("Send")
      ]
    )

sendFeedback()函数的代码应该怎么写?我想获取我children列表中所有滑块的值,然后只使用一次调用将这些值写入Firestore数据库。

2个回答

1
你需要保存所有滑块的状态。我建议使用BLoC模式进行状态管理。 你可以在这里阅读相关内容 编辑:你可以使用一个List<int>来保存bloc中的值,在每个滑块中实现onChangeEnd: bloc.addValue函数,并将滑块的值发送到bloc,bloc将把它们添加到列表中。 然后在按钮上,你会有类似这样的代码onPressed: () => bloc.sendFeedback(),它将从列表中获取值并将它们写入Firestore。
请记住,这只是我脑海中的一种解决方案,让你理解概念。

好的,我已经阅读了,但是每个问题(滑块)都需要一个流吗?你有任何代码或者能否指向一些类似的例子来解决我的问题? - gantonioid
学习和实现这个功能花了一些时间,但在完成后,我遇到了一个错误,大概是“流已被监听”,我猜想这是因为我只能将一个滑块附加到该流中(???)。 - gantonioid
这是因为你需要像这样声明StreamController StreamController.broadcast()。当你这样做时,该流可以在多个位置被监听。否则,你只能监听它一次。 - Sebastian

0

对于这个应用程序而言,拥有一个全局变量就足够了。

Map<String, double> responses = Map();

这是在我导航到问卷时重置的,然后每个滑块都必须像这样更新地图(onChange):

Slider(
  value: value,
  min: widget.min,
  max: widget.max,
  divisions: (widget.max - 1).round(),
  label: value.ceil().toString(),
  activeColor: color,
  onChanged: (double val1) {
     //Force a re-render
     setState(() {
       //Update the value of the Slider
       value = val1;
       //Do some operations, assign a color based on the result
       double p = value / widget.max;
       if (p > 0 && p <= 0.3) {
         color = Colors.red;
       } else if (p > 0.3 && p <= 0.6) {
         color = Colors.orangeAccent;
       } else {
         color = Colors.green;
       }
       //Update the value of the parent Widget
       widget.value = value;
       ratings[widget.question] = value;

       //Done, print in console for debugging
       print(value);
     });
   })

我花了很多时间研究BLoC模式,但是我没能如预期那样让它工作。也许我会很快再试一次,并发布解决方案。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接