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

Flutter:如何用Widget类参数作props创建带Row/Column的动态组件

问题解答

一、CustomCard无法正常工作的原因及修复

你的CustomCard报错核心是两个问题:

1. const上下文无法引用实例变量

你给Column的children数组加了const修饰,但title是CustomCard的实例成员变量,不属于编译时常量,在const列表里无法访问。必须去掉children前的const。

2. 废弃的@required注解

Flutter早已废弃@required注解,现在直接用required关键字标记必填参数。另外如果title是必填项,建议定义为非空类型(去掉?),避免后续强制解包(title!)的风险。

修复后的CustomCard代码:

import 'package:flutter/material.dart';

class CustomCard extends StatelessWidget {
  final String title;

  const CustomCard({super.key, required this.title});

  @override
  Widget build(BuildContext context) {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(3.0),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Icon(
              Icons.sports_soccer,
              color: Colors.black,
              size: 50.0,
            ),
            const SizedBox(height: 8.0),
            Text(
              title,
              style: const TextStyle(
                color: Colors.black,
                fontSize: 15.0,
                fontWeight: FontWeight.bold,
                letterSpacing: 1.0,
                fontFamily: 'Lato',
              ),
            ),
            const SizedBox(height: 8.0),
            const Text(
              '26',
              style: TextStyle(
                color: Colors.black,
                fontWeight: FontWeight.bold,
                fontSize: 15.0,
                letterSpacing: 1.0,
                fontFamily: 'Lato',
              ),
            ),
          ],
        ),
      ),
    );
  }
}

二、创建支持任意子组件的ScoreRow

要实现类似原生Row的任意子组件接收能力,需要把参数类型从Widget?改为List<Widget>——因为Row的children属性本身就是列表类型。

修复后的ScoreRow代码:

import 'package:flutter/material.dart';
import 'widgets/neo_text.dart';

class ScoreRow extends StatelessWidget {
  final List<Widget> children;

  const ScoreRow({super.key, required this.children});

  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      children: children,
    );
  }
}

使用示例:

ScoreRow(
  children: const [
    NeoText(text: "⚽️Goals: 2"),
    NeoText(text: "🅰️Assists: 6"),
    NeoText(text: "🧤Saves: 26"),
  ],
)

如果希望支持可选子组件(允许不传),可以给参数设置默认空列表:

class ScoreRow extends StatelessWidget {
  final List<Widget> children;

  const ScoreRow({super.key, this.children = const []});

  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      children: children,
    );
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 04:05:24