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

Flutter报错:命名参数‘height’未定义,如何解决?

修复Flutter自定义按钮的height/width参数错误

问题根源很明确:height和width是Container组件的直接配置属性,你错误地把它们放到了BoxDecoration的参数列表里,而BoxDecoration并没有这两个参数,所以会触发未定义参数的报错。

只需要把这两个参数从decoration内部移到Container的顶层参数中即可,修复后的完整代码如下:

import 'package:flutter/cupertino.dart';
import 'package:flutter/src/widgets/container.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:fruits_market/core/constants.dart';
import 'package:flutter/material.dart';

class CustomGeneralButton extends StatelessWidget {
  const CustomGeneralButton({super.key,this.text});
  final String? text;

  @override
  Widget build(BuildContext context) {
    return Container(
      // 将height和width移到Container的直接参数中
      height: 60,
      width: 100,
      decoration: BoxDecoration(
        color: KMainColor,
        borderRadius: BorderRadius.circular(8), 
      ),
      child: Center(
        child: Text(
          text!,
          style: TextStyle(
            fontSize: 14,
            color: const Color(0xffffffff),
            fontWeight: FontWeight.w500,
          ),
          textAlign: TextAlign.left,
        ),
      ),
    );
  }
}

额外提个小优化点:你用text!强制解包,如果调用组件时未传入text值,会触发空指针异常。可以给text设置必填约束或者默认值,比如:

  • 设为必填参数:
const CustomGeneralButton({super.key, required this.text});
final String text;
  • 设置默认值:
const CustomGeneralButton({super.key, this.text = '确认'});
final String? text;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 17:45:46