代码之家  ›  专栏  ›  技术社区  ›  Stéphane de Luca

如何制作一个有状态的小部件,在flutter中添加新的时间点?

  •  0
  • Stéphane de Luca  · 技术社区  · 4 年前

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

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

    我的想法是,只要我有一个新值,就调用_sparklineadd()函数,这样Sparkline就会重新绘制。

    最好的方法是什么?

    0 回复  |  直到 4 年前
        1
  •  -1
  •   Stéphane de Luca    4 年前

    最后,我对代码进行了如下更新,以利用流(流本身是在其他地方创建的,将被传递到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(...);
        }
    }
    ``