首页 > 解决方案 > 有状态和无状态 Flutter UI 的混合未更新

问题描述

使用有状态的小部件导致显示陈旧的小部件

我有一个通过网络接收更新文本更新的 UI。当有更新出现时,我希望首先将其显示为红色,然后随着消息年龄的增加将其慢慢淡化为黑色。如果新消息来自同一来源,我想用新消息替换旧消息的文本,然后让文本再次从红色变为黑色。

当我使用带有 RestartableTimer 的 Stateful 小部件时,我第一次启动我的 UI 时,一切似乎都运行良好。然而,一旦第二条消息来自特定来源,那就是事情中断的地方。如果我使用纯文本()来显示新消息,它工作得很好。但是,如果我使用 Stateful 小部件来显示文本并从红色变为黑色,则 UI 仍然过时,并且似乎没有任何更新可以解决问题。

我的层次结构(删除了特定于布局的东西)看起来像:

Stateful Container for different sources
|
List View
|
+--- Stateless Custom Widget
     |
     +-- Stateless Text (displays the source)
     |
     +-- Stateful Custom Text class
<repeated for each source>

如果我用纯文本()替换我的自定义类,然后文本突然更新就好了(但没有褪色)。

无状态自定义小部件

  Widget _CreateDataTable() {
    const Color start_color = Colors.red;
    const Color end_color = Colors.black;
    const Duration fade_len = Duration(seconds: 10);
    var read_time = DateTime.fromMillisecondsSinceEpoch(
        _data.data.timeSeconds * 1000,
        isUtc: true);
    String date_text = read_time.toLocal().toString();
    List<String> labels = ["Temperature", "Humidity", "RSSI", "Last Reading"];
    List<Widget> data = [
      Text(_data.data.temperature.toStringAsFixed(2) + " C"),
      Text(_data.data.humidity.toStringAsFixed(2) + "%"),
      Text(_data.rssi.toString() + " dB"),
      FlashText(date_text, start_color, end_color, read_time, fade_len),
      // Text(date_text),
      //
      //  IF I COMMENT OUT FlashText AND UNCOMMENT Text, EVERYTHING
      //  WORKS FINE. IF I KEEP IT AS IS, I ONLY SEE THE FIRST EVER
      //  MESSAGE AND NEW MESSAGES, WHICH I CAN CONFIRM RECEIVING VIA
      //  debugPrint, ARE SEEMINGLY IGNORED.
    ];

    var rows = List<Row>();
    for (int i = 0; i < labels.length; ++i) {
      rows.add(Row(children: [
        IntrinsicWidth(child: SizedBox(width: 10.0)),
        IntrinsicWidth(child: Text(labels[i] + ":")),
        IntrinsicWidth(child: data[i]),
        Expanded(child: SizedBox()),
      ]));
    }
    return Column(children: rows);

有状态的自定义小部件

class FlashText extends StatefulWidget {
  final Color _color0;
  final Color _color1;
  final DateTime _start;
  final Duration _duration;
  final String _text;

  FlashText(
      this._text, this._color0, this._color1, this._start, this._duration);

  @override
  _FlashTextState createState() {
    debugPrint("Creating state for $_text - $_start");
    return _FlashTextState(_text, _color0, _color1, _start, _duration);
  }
}

class _FlashTextState extends State<FlashText> {
  Color _color0;
  Color _color1;
  DateTime _start;
  Duration _duration;
  String _text;

  Animation<double> _animation;
  AnimationController _controller;

  _FlashTextState(
      this._text, this._color0, this._color1, this._start, this._duration);

  @override
  Widget build(BuildContext ctx) {
    return Text(_text,
        style: TextStyle(color: Color.lerp(_color0, _color1, _GetT())));
  }

  @override
  void initState() {
    super.initState();
    RestartableTimer(_duration ~/ 30, _Update);
  }

  double _GetT() {
    DateTime now = DateTime.now().toUtc();
    return min(1, max(0, now.difference(_start).inMilliseconds /
    _duration.inMilliseconds.toDouble()));
  }

  void _Update() {
    if (_GetT() < 1.0) RestartableTimer(_duration ~/ 30, _Update);
  }
}

标签: animationflutterstateful

解决方案


我认为您必须更改小部件的设计,FlashText并在小部件文本更改时使用该didUpdateWidget方法进行重建。

我在一个完整的应用程序下面实现了一个使用文本字段和一个按钮来模拟来自服务器的文本。

我认为这或多或少是您需要的,但可能需要一些调整。

import 'dart:async';

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  var _cont = TextEditingController();

  String text = "qwertrrr";

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Test"),
      ),
      body: Column(
        children: <Widget>[
          TextFormField(
            controller: _cont,
          ),
          RaisedButton(
            child: new Text("Test"),
            onPressed: () => setState(() {
                  text = _cont.text;
                }),
          ),
          FlashText(text, Colors.red, Colors.black, 10),
        ],
      ),
    );
  }
}

class FlashText extends StatefulWidget {
  final Color color0;
  final Color color1;
  final int duration;
  final String text;

  FlashText(this.text, this.color0, this.color1, this.duration);

  @override
  _FlashTextState createState() {
    return _FlashTextState();
  }
}

class _FlashTextState extends State<FlashText>
    with SingleTickerProviderStateMixin<FlashText> {
  Animation<Color> _animation;
  AnimationController _controller;

  Timer timer;

  @override
  void didUpdateWidget(FlashText oldWidget) {
    if (widget.text != oldWidget.text) {
      _controller.forward(from: 0.0);
    }
    super.didUpdateWidget(oldWidget);
  }

  @override
  Widget build(BuildContext ctx) {
    return Text(
      widget.text,
      style: TextStyle(color: _animation.value),
    );
  }

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
        vsync: this, duration: Duration(seconds: widget.duration));
    _animation = ColorTween(begin: widget.color0, end: widget.color1)
        .animate(_controller)
          ..addListener(() => setState(() {}));
    _controller.forward();
  }
}

推荐阅读