You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter点击按钮生成新文本问题:旧文本消失求助

问题解决:保留所有生成的随机位置Text组件

问题出在你的实现逻辑里:每次调用setState时,Stack的children里只会渲染最新生成的单个Positioned组件,之前的组件没有被保存,所以旧的Text会消失。要保留所有生成的Text,你需要把每个生成的Text的位置和文本信息存储起来,每次重建时渲染所有历史条目。

修改后的完整代码如下:

class AddNewWidget extends StatefulWidget {
  const AddNewWidget({Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() => _AddNewWidgetState();
}

class _AddNewWidgetState extends State<AddNewWidget> {
  // 存储所有生成的文本条目:包含文本内容、left、top位置
  final List<Map<String, dynamic>> _textItems = [];
  final Random _random = Random(); // 统一使用一个Random实例,避免重复随机

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Add Text"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            const Text('Add Text Below:'),
            Expanded( // 用Expanded避免布局溢出,适配不同屏幕
              child: Stack(
                children: [
                  Container(
                    width: double.infinity,
                    height: double.infinity,
                    decoration: BoxDecoration(
                      border: Border.all(width: 2.0, color: Colors.red),
                    ),
                  ),
                  // 遍历所有存储的条目,生成对应的Positioned组件
                  for (var item in _textItems)
                    Positioned(
                      key: ValueKey(item['id']), // 用唯一id作为key,优化组件复用
                      child: Text(item['text']),
                      left: item['left'],
                      top: item['top'],
                    ),
                ],
              ),
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _press,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ),
    );
  }

  void _press() {
    setState(() {
      // 生成随机数据并添加到列表
      final id = _random.nextInt(1000); // 生成唯一id
      _textItems.add({
        'id': id,
        'text': "hello ${_random.nextInt(10)}",
        'left': _random.nextInt(300).toDouble(),
        'top': _random.nextInt(500).toDouble(), // 调整高度避免溢出
      });
    });
  }
}

关键修改说明:

  • 添加存储列表:用_textItems保存所有生成的文本的位置和内容,确保每次重建UI时能渲染所有历史组件。
  • 统一Random实例:避免多次创建Random导致的重复随机值问题,同时提升性能。
  • 遍历生成组件:在Stack的children里通过循环遍历列表,生成所有历史的Positioned组件,而不是只生成单个新组件。
  • 优化布局:用Expanded包裹Stack,避免固定高度导致的屏幕适配问题,同时调整top的随机范围防止文本溢出红色容器。

内容的提问来源于stack exchange,提问作者flutter_bee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 23:03:23