首页 > 解决方案 > '未来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此处函数中的数据用于该行的系列

标签: flutterdart

解决方案


作为@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],
                );
            },
        );
    }
}

推荐阅读