'Future<double> Function(dynamic, int)' 不能分配给参数类型 'num Function(dynamic, int)'

时间:2021-06-05 22:16:43

标签: flutter dart

我在 Flutter 应用程序中使用 charts_flutter,目前我正在尝试实现此图表:https://google.github.io/charts/flutter/example/combo_charts/scatter_plot_line

这是我在图表中的线的Series

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 函数中的数据用于该行的 Series

2 个答案:

答案 0 :(得分:0)

在为图表调用构建之前,您需要进行数据处理。在包含图表的 StatefulWidget 类中的异步函数中调用 analyticsLinearRegression.predict。等待异步函数的返回,然后调用 setState() 并构建图表,将完成的数据传递给图表。

答案 1 :(得分:0)

补充 @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],
                );
            },
        );
    }
}