首页 文章

获取动态窗口小部件的值 - 颤动

提问于
浏览
2

我设法制作了一个动态的调查问卷,将颤振与Firestore联系起来 .

我的自定义问题窗口小部件只是一个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()函数的代码是什么?我想获取我的子列表中所有滑块的值,然后只在一次调用DB中将它们写入Firestore .

2 回答

  • 0

    您需要保持所有滑块的状态 . 我建议您使用BLoC模式进行状态管理 .

    You can read about it here

    编辑:您可以使用 List<int> 来保存块中的值,并且在每个滑块中您将实现函数 onChangeEnd: bloc.addValue 并将滑块值发送到bloc,这将把它们添加到列表中 . 然后在按钮上,您将获得类似于 onPressed: () => bloc.sendFeedback() 的内容,它将从列表中获取值并将其写入Firestore .

    请记住,这是我现在头脑中的一个解决方案,让您了解这个概念

  • 0

    出于这个应用程序的目的,它足以拥有一个全局变量

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

    当我导航到调查问卷时重置,然后每个Slider必须像这样更新 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模式上投入了相当多的时间,但我无法按预期工作 . 也许我会尽快再试一次并回复解决方案 .

相关问题