如何制作迷你图有状态小部件以随着时间的推移添加新点?

How to make a sparkline stateful widget to add new points along the time in flutter?

我有一个有状态的小部件,它从本地存储的点列表中提取一个:

class Sparkline extends StatefulWidget {

    @override
    _Sparkline create() => _Sparkline;
}

class _Sparkline extends State<Sparkline> {
    List<Offset> _points = [];

    /// Add a new value and redraw
    void add(double value) { 
        SetState(() {
             points.add(value);
        });
    }

    @override
    void build(BuildState context) {
        /// My sparkling custom painter that draw all points
        return CustomPainter(...);
    }
}

我的想法是只要我有一个新值就调用 _Sparkline add() 函数,以便重新绘制迷你图。

最好的方法是什么?

最后,我更新了我的代码以利用 Stream 如下(流本身是在别处创建的,并将传递给 Sparkline 小部件):


class Sparkline extends StatefulWidget {
    late final StreamController<double> streamController;

    Sparkline({required this.streamController});

    @override
    _Sparkline create() => _Sparkline;
}

class _Sparkline extends State<Sparkline> {

    /// List of points to be drawn
    List<Offset> _points = [];

    /// Subscription to the value stream
    late StreamSubscription<double> _subscription;

    @override
    void initState() {
        super.initState();
    
        // Subscribe to the stream of points
        _subscription = widget.streamController.stream.listen((value) {
            setState(() {
                points.add(point);
            });
        });
    }

    @override
    void dispose() {
        _subscription.cancel();
        super.dispose();
     }


    @override
    void build(BuildState context) {
        /// My sparkling custom painter that draw all points
        return CustomPainter(...);
    }
}
``