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

测试向Widget传递函数时出现栈溢出及buildSwitchListTile多次调用问题

问题根源:无限递归调用

你遇到的buildSwitchListTile被调用45次的核心原因是你的widget函数在无限递归调用自身,没有实际返回有效的UI组件。

看你的widget代码:

Widget buildSwitchListTile(
  String title,
  String description,
  bool currentValue,
  void Function(bool)? updateValue,
) {
  return buildSwitchListTile( // 此处直接调用自身,触发无限递归
    title,
    description,
    currentValue,
    updateValue,
  );
}

每次调用这个函数时,它不会创建SwitchListTile组件,而是再次调用自己,直到触发Dart的递归栈深度限制,最终累积出45次左右的调用次数(该数值与Dart默认递归深度限制相关)。

修复方案

将widget函数修改为实际返回SwitchListTile组件的实现,替换掉递归调用逻辑:

import 'package:flutter/material.dart';

Widget buildSwitchListTile(
  String title,
  String description,
  bool currentValue,
  void Function(bool)? updateValue,
) {
  return SwitchListTile(
    title: Text(title),
    subtitle: Text(description),
    value: currentValue,
    onChanged: updateValue,
  );
}
额外优化建议
  • 你在setState前添加的if (newValue != _optionX)判断可以去掉,因为Switch的onChanged回调只会在值发生变化时触发,无需额外校验。
  • 可以通过列表循环简化重复的组件调用逻辑,减少代码冗余:
// 在_MyHomePageState中定义选项列表
final List<Map<String, dynamic>> _options = [
  {'title': 'Option 1', 'desc': 'From widget Select option 1', 'value': false},
  {'title': 'Option 2', 'desc': 'From widget Select option 2', 'value': true},
  {'title': 'Option 3', 'desc': 'From widget Select option 3', 'value': false},
];

// 在build方法中循环生成组件
children: _options.asMap().entries.map((entry) {
  final idx = entry.key;
  final opt = entry.value;
  return buildSwitchListTile(
    opt['title'],
    opt['desc'],
    opt['value'],
    (newVal) => setState(() => _options[idx]['value'] = newVal),
  );
}).toList(),

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 14:15:34