我是新手,我需要知道一件事,我正在函数中计算一些值,需要在文本小部件中显示此值,这怎么可能?
这是我的功能
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),
]
)
答案 0 :(得分:1)
您的数字看起来实际上是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;
}
Text('$percentage1Calculate');
答案 1 :(得分:0)
您可以返回在函数中计算出的值,并将其作为值传递到小部件内。
假设您的函数返回int,
int percentage1Calculate(){
final percentage1 = _questions[index]['wouldclick'] / _questions[index] ['wouldclick'] + _questions[index]['ratherclick'] * 100;
return percentage1;
}
调用上述函数并将其保存在变量中,
int store = percentage1Calculate();
在小部件中使用它,如下所示,
Text(data: $store);