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

Flutter:如何在_ListItem中调用_SettingRoute的lastChanged变量?

解决Flutter组件间状态变量传递问题

你的核心问题是子组件无法直接访问父组件的状态变量,用static变量又会导致无法通过setState更新UI。这里给你最直接的解决方案:通过构造函数逐层传参,既符合Flutter的组件设计规范,又能正常触发UI更新。

具体修改步骤:

  • 给_ListItem添加构造函数,接收需要展示的settingVersion和lastChanged变量
  • 给_Body添加构造函数,接收父组件传来的变量,再传递给_ListItem
  • 在_SettingRoute的build方法中,调用_Body时传入当前状态的变量

修改后的完整代码:

class SettingRoute extends StatefulWidget {
  const SettingRoute({Key? key}) : super(key: key);

  @override
  State<SettingRoute> createState() => _SettingRoute();
}

class _SettingRoute extends State<SettingRoute> {
  String settingVersion = "1.0.0"; // 示例值
  String lastChanged = "2024-05-20"; // 示例值
  String tagVersionDriving = "";
  String tagVersionParking = "";
  bool defaultTagDriving = true;
  bool defaultTagParking = true;
  List<Label> labels = [];

  @override
  void initState() {
    super.initState();
    // 这里可以初始化变量,比如从本地存储或接口获取
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold( // 去掉const,因为要传递动态变量
      body: _Body(
        settingVersion: settingVersion,
        lastChanged: lastChanged,
      ),
      bottomNavigationBar: const _PageButton(),
    );
  }
}

class _Body extends StatelessWidget {
  final String settingVersion;
  final String lastChanged;

  // _Body的构造函数
  const _Body({
    required this.settingVersion,
    required this.lastChanged,
    Key? key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Expanded(
          child: Padding(
            padding: const EdgeInsets.all(16),
            child: ListView.separated(
              itemBuilder: (context, index) => _ListItem(
                settingVersion: settingVersion,
                lastChanged: lastChanged,
              ),
              separatorBuilder: (context, index) => const SizedBox(height: 20),
              itemCount: 3,
            ),
          ),
        )
      ],
    );
  }
}

class _ListItem extends StatelessWidget {
  final String settingVersion;
  final String lastChanged;

  // _ListItem的构造函数
  const _ListItem({
    required this.settingVersion,
    required this.lastChanged,
    Key? key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return DecoratedBox(
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(8),
        border: Border.all(),
      ),
      child: Padding(
        padding: const EdgeInsets.all(6),
        child: Column(
          children: [
            ListTile(
              onTap: () {
                if (kDebugMode) {
                  print("click");
                }
              },
              leading: const Icon(
                Icons.settings,
                color: Colors.black,
                size: 50.0,
              ),
              title: const Text("Setting Version"),
              subtitle: Text(settingVersion),
            ),
            ListTile(
              onTap: () {
                if (kDebugMode) {
                  print("click");
                }
              },
              leading: const Icon(
                Icons.access_time,
                color: Colors.black,
                size: 50.0,
              ),
              title: const Text("Last change of the tag-version"),
              subtitle: Text(lastChanged),
            ),
          ],
        ),
      ),
    );
  }
}

class _PageButton extends StatelessWidget {
  const _PageButton();

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Padding(
        padding: const EdgeInsets.fromLTRB(16, 0, 16, 0),
        child: ElevatedButton(
          onPressed: () {},
          child: const Text("Some Button"),
        ),
      ),
    );
  }
}

关键说明:

  • 去掉了Scaffold的const修饰,因为要传递动态的状态变量,const组件不能引用非const的变量
  • 通过构造函数传参后,当_SettingRoute中调用setState更新settingVersion或lastChanged时,所有依赖这些变量的子组件都会自动刷新UI
  • 不推荐用static变量的原因:static变量属于类本身,不是组件实例的状态,调用setState不会触发UI更新,还可能导致全局状态混乱

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 14:15:01