flutter - '未来Function(dynamic, int)' 不能分配给参数类型 'num Function(dynamic, int)'
问题描述
我在我的 Flutter 应用程序中使用了 charts_flutter,目前我正在尝试实现这个图表:https ://google.github.io/charts/flutter/example/combo_charts/scatter_plot_line 。
这是图表中线条的系列:
charts.Series(
measureFn: ((dynamic number, _) async => await analyticsLinearRegression.predict(number * 1.0)),
domainFn: ((dynamic number, _) async => await analyticsLinearRegression.predict(number * 1.0)),
colorFn: (dynamic number, _) => charts.ColorUtil.fromDartColor(Colors.blue[900]),
id: "linearRegression",
data: [
0,
highestX,
],
)..setAttribute(charts.rendererIdKey, "linearRegressionLine")
问题很明显:The argument type 'Future<double> Function(dynamic, int)' can't be assigned to the parameter type 'num Function(dynamic, int)'.
我知道问题出在哪里,但是函数analyticsLinearRegression.predict
返回Future<double>
而不是返回double
,我无法更改。
那么如何将analyticsLinearRegression.predict
此处函数中的数据用于该行的系列?
解决方案
作为@Scott's answer的补充,您应该执行以下操作:
class YourWidget extends StatelessWidget {
// Create a future inside your widget to store the computations
Future<List<double>> _future;
// Do your asynchronous computations inside a asynchronous method
Future<List<double>> _compute() async {
double x = await analyticsLinearRegression.predict(number * 1.0);
double y = await analyticsLinearRegression.predict(number * 1.0);
return [x, y];
}
// When creating the widget, assign the future to the async method result
@override
void initState() {
super.initState();
_future = _compute();
}
// When building, use a FutureBuilder to avoid blocking the screen
@override
Widget build(BuildContext context) {
return FutureBuilder(
// Wait for the computation of the created future
future: _future,
builder: (context, snapshot) {
// If the computation is not ready yet, return a progress indicator
if (snapshot.connectionState == ConnectionState.waiting)
return Center(child: CircularProgressIndicator());
// If it's ready, display it
final List<double> result = snapshot.data;
return charts.Series(
measureFn: (dynamic number, _) => result[0],
domainFn: (dynamic number, _) => result[1],
colorFn: (dynamic number, _) => charts.ColorUtil.fromDartColor(Colors.blue[900]),
id: "linearRegression",
data: [0, highestX],
);
},
);
}
}
推荐阅读
- mysql - mysql - 在一个查询中为同一个表选择两个条件的结果
- c++ - 保存用户输入的文件名 c++
- ef-core-2.2 - EFCORE 2.2.6 简单连接抛出 必须是可约节点
- ms-access - 如何创建一个使用方程式对另一个表中的数据进行平均的表?
- r - 在不知道重复次数的情况下,如何计算同一样本的重复实验值的平均值?
- c - 调用 FreeImage_GetPixelColor() 时出现奇怪的段错误
- javascript - React Native UI Kittens:输入组件中的多行
- reactjs - 在 onClick 中反应处理这个
- python - 如何从图像中获取文本
- optimization - 我可以使用哪些优化技术来最大化单位超立方体中每个点到其他点的最小距离之和?