0

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?

Stéphane de Luca
  • 12,745
  • 9
  • 57
  • 95
  • since you want to update your painter with new data i think that you should check `CustomPainter` official documentation, they say: *"The most efficient way to trigger a repaint is to either: Extend this class and supply a repaint argument to the constructor of the CustomPainter, where that object notifies its listeners when it is time to repaint. Extend Listenable (e.g. via ChangeNotifier) and implement CustomPainter, so that the object itself provides the notifications directly."* – pskink Nov 05 '21 at 08:40

1 Answers1

-1

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(...);
    }
}
``
Stéphane de Luca
  • 12,745
  • 9
  • 57
  • 95