Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/flutter/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Flutter 在颤振中,如何从函数中获取值?_Flutter - Fatal编程技术网

Flutter 在颤振中,如何从函数中获取值?

Flutter 在颤振中,如何从函数中获取值?,flutter,Flutter,我是颤振新手,我需要知道一件事,我正在计算我函数中的一些值,需要在文本小部件中显示这是怎么可能的 这是我的职责 final List _questions = [ {'would': 'Coffe1', 'rather': 'Tea', 'wouldclick': '1', 'ratherclick':'2'}, {'would': 'Blue', 'rather': 'Red', 'wouldclick': '2', 'ratherclick':'2'}, {'wo

我是颤振新手,我需要知道一件事,我正在计算我函数中的一些值,需要在文本小部件中显示这是怎么可能的

这是我的职责

  final List _questions = [
    {'would': 'Coffe1', 'rather': 'Tea', 'wouldclick': '1', 'ratherclick':'2'},
    {'would': 'Blue', 'rather': 'Red', 'wouldclick': '2', 'ratherclick':'2'},
    {'would': 'Green', 'rather': 'Yellow', 'wouldclick': '3', 'ratherclick':'2'},
  ];

  int index = 0;
  void percentage1Calculate(){
     final percentage1 = _questions[index]['wouldclick'] / _questions[index]['wouldclick'] + _questions[index]['ratherclick'] * 100;
  }
  void percentage2Calculate(){
     final percentage2 = _questions[index]['ratherclick'] / _questions[index]['wouldclick'] + _questions[index]['ratherclick'] * 100;
  }
需要在一列中显示

Column(
     children: <Widget>[
       Text(percentage1),
       Text(percentage2),
    ]
)
列(
儿童:[
文本(百分比1),
文本(百分比2),
]
)

您可以返回函数中计算的值,并将其作为值传递到小部件中

假设函数返回int

int percentage1Calculate(){
  final percentage1 = _questions[index]['wouldclick'] / _questions[index] ['wouldclick'] + _questions[index]['ratherclick'] * 100;
  return percentage1;
}
调用上述函数并将其保存在变量中

int store = percentage1Calculate();
在小部件中使用它,如下所示

Text(data: $store);

您的数字看起来像是实际的
String
类型,请在进行数学运算之前先尝试转换它们:

double percentage1Calculate(){
     int wouldClick = int.parse(_questions[index]['wouldclick']);
     int ratherClick = int.parse(_questions[index]['ratherclick']);
     double percentage1 = wouldClick / wouldClick + ratherClick * 100;
     return percentage1;
}
然后,您应该能够像这样设置一个变量:

Text('${percentage1Calculate()}');
如果将其设置为
get
方法,则可以这样使用:

double get percentage1Calculate {
     int wouldClick = int.parse(_questions[index]['wouldclick']);
     int ratherClick = int.parse(_questions[index]['ratherclick']);
     double percentage1 = wouldClick / wouldClick + ratherClick * 100;
     return percentage1;
}

是否可以在文本小部件中直接调用函数?请尝试此操作,但其显示错误类“String”没有实例方法“/”。当我打印存储值时,这是一个完全不同的错误,在web上搜索时,这个问题已经解决。Text(percentage1Calculate().toString())尝试第一个方法,它显示无效参数:源不能为null我刚才做了一些编辑,你尝试过修改后的副本吗?显示在整个小部件中。我认为问题是json格式的maybeYep,引用了无效的映射键,请检查上面的编辑。我可以验证这是在我自己的机器上工作。
Text('$percentage1Calculate');