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

Flutter点击ElevatedButton无法切换随机字符串问题求助

问题原因

你的代码中,随机打乱列表和获取国家的逻辑写在build方法里。build方法仅在组件初始化、状态变更或布局更新时执行,点击按钮不会触发build重新运行,因此每次点击使用的都是首次build生成的country值,导致内容不变化。

修改方案

把随机获取国家的逻辑移到按钮的onPressed回调中,确保每次点击按钮时都重新执行随机操作。同时可以将国家列表提取为组件成员变量,避免重复创建:

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

  @override
  // ignore: library_private_types_in_public_api
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  // 国家列表作为成员变量,复用列表实例
  final List<String> countries = [
    "USA",
    "United Kingdom",
    "China",
    "Russia",
    "Brazil"
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("GeeksForGeeks"),
        backgroundColor: Colors.green,
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            // 每次点击时执行随机逻辑
            countries.shuffle();
            final country = countries[0];
            
            showDialog(
              context: context,
              builder: (ctx) => AlertDialog(
                title: const Text("Shuffle List in Flutter"),
                content: Text(country),
                actions: <Widget>[
                  TextButton(
                    onPressed: () => Navigator.of(ctx).pop(),
                    child: Container(
                      color: Colors.green,
                      padding: const EdgeInsets.all(14),
                      child: const Text("okay"),
                    ),
                  ),
                ],
              ),
            );
          },
          child: const Text("Show alert Dialog box"),
        ),
      ),
    );
  }
}
另一种实现方式(无需打乱列表)

如果不想打乱整个列表,可以直接通过随机索引选取国家:

onPressed: () {
  final random = Random();
  final country = countries[random.nextInt(countries.length)];
  
  showDialog(
    // 弹窗代码保持不变
  );
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 11:10:27