Search code examples
flutterdartstatefulwidget

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


I have a stateful widget that draws a one from a list of points stored locally:

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(...);
    }
}

My idea would be to invoke the _Sparkline add() function anytime I've got a new value so that the sparkline redraws.

What's the best way to do that?


Solution

  • Finally, I updated my code to take advantage of a Stream as follows (The stream itself was created elsewhere and is to be passed to the Sparkline widget):

    
    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(...);
        }
    }
    ``