You need to enable JavaScript to run this app. Flutter开发中如何随机展示不同的SizedBox组件?
优惠活动
大模型
产品
解决方案
定价
更多

Flutter开发中如何随机展示不同的SizedBox组件?

报错原因

你遇到的类型报错是因为直接在Row的children数组中插入了返回int类型的赋值/运算语句,而children数组要求所有元素必须为Widget类型,非Widget类型的表达式不能直接放在数组内。另外你写的random.nextInt(1)逻辑也存在问题:nextInt的参数为随机数的生成上限(不包含上限值),传1只能得到固定返回值0,无法实现二选一的随机效果。

实现方案

这个需求完全可以实现,提供两种常用实现方式:

方案1:提前计算随机逻辑后传入Widget

在build方法内先完成随机数生成和组件选择,再把最终的Widget放到children数组中:

import 'dart:math';

@override
Widget build(BuildContext context) {
  // 生成0或1的随机数
  final random = Random();
  final int randomNumber = random.nextInt(2);
  // 提前选择要展示的SizedBox
  final Widget showSizedBox = randomNumber == 0 
    ? const SizedBox(width: 100, height: 100, child: Text("SizedBox1"))
    : const SizedBox(width: 100, height: 100, child: Text("SizedBox2"));

  return Row(
    children: [
      // 其他固定组件
      const Text("其他前置组件"),
      // 直接传入已经处理好的Widget
      showSizedBox,
      // 其他固定组件
      const Text("其他后置组件"),
    ],
  );
}

方案2:使用集合if语法直接在children内判断

Dart支持集合if/for语法,可以直接在列表内编写逻辑返回Widget,不需要额外定义变量:

import 'dart:math';

@override
Widget build(BuildContext context) {
  final random = Random();
  return Row(
    children: [
      const Text("其他前置组件"),
      // 直接在children内用集合if做判断
      if (random.nextInt(2) == 0)
        const SizedBox(width: 100, height: 100, child: Text("SizedBox1"))
      else
        const SizedBox(width: 100, height: 100, child: Text("SizedBox2")),
      const Text("其他后置组件"),
    ],
  );
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 06:24:00