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

如何基于Flutter内置组件自定义Widget及解决子组件访问父属性异常问题

问题解决方案

错误原因

  • 递归调用死循环:你自定义的MyColumn类重写children getter方法时,内部调用this.children.add会再次触发该getter,形成无限递归,导致组件无法正常渲染
  • 不符合Flutter最佳实践:Flutter框架原生的Widget(如Column、Container)设计上不推荐直接继承修改属性,优先使用组合的方式实现自定义组件,避免出现不可预期的兼容问题

修正后可运行完整代码

import 'package:flutter/material.dart';

void main(List<String> args) {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        appBar: AppBar(
          title: const Text("Hello World App", style: TextStyle(color: Colors.white)),
        ),
        // 支持滚动,避免内容超出屏幕报错
        body: SingleChildScrollView(child: MyColumn()),
      ),
    );
  }
}

// 改用组合实现自定义Container
class MyContainer extends StatelessWidget {
  final int numbr;
  const MyContainer(this.numbr, {Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.blue,
      child: Center(
        child: Text("Container $numbr",
            style: const TextStyle(
                fontSize: 34, fontFamily: "Cursive", color: Colors.white)),
      ),
    );
  }
}

// 改用组合实现自定义Column
class MyColumn extends StatelessWidget {
  const MyColumn({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Column(
      // 直接生成children列表,避免递归
      children: List.generate(10, (index) => MyContainer(index + 1)),
    );
  }
}

主要修正点

  • 把自定义组件的实现方式从继承原生Widget改为组合原生Widget,符合Flutter开发规范
  • 移除了递归调用的错误逻辑,改用List.generate直接生成10个MyContainer组件
  • 外层加了SingleChildScrollView,避免Column内容超出屏幕高度时报渲染溢出错误
  • 优化了AppBar标题的写法,无需额外嵌套Title组件

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 12:54:02