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

Flutter静态数组生成SettingsTile失效,仅显示单个Tile求助

问题解决:Flutter中静态数组遍历未执行导致SettingsTile未渲染

核心问题

  1. Dart的map()惰性求值特性:你调用tilearray.map(...)后没有消费返回的Iterable对象,导致内部逻辑完全不会执行。map()本身仅生成一个待迭代的序列,必须通过forEach()、toList()或addAll()等方式触发实际遍历。
  2. Map元素访问错误:你用item.name访问Map的name键,这是错误用法,Dart中Map需要通过item['name']的方式取值。

修复后的代码示例

import 'package:flutter/material.dart';
import 'package:settings_ui/settings_ui.dart';
import 'dart:developer' as devtools show log;

class _SettingsScreenState extends State<SettingsScreen> {
  bool lockInBackground = true;

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    final tilearray = [
      {'name':'settings no 1'},
      {'name':'settings no 2'},
      {'name':'settings no 3'}
    ];
    final List<SettingsTile> tiles = [];

    devtools.log('$tilearray');

    // 添加第一个固定Tile
    tiles.add(SettingsTile.switchTile(
      initialValue: lockInBackground,
      onToggle: (bool value) {
        setState(() {
          lockInBackground = value;
        });
      },
      leading: const Icon(Icons.phonelink_lock),
      title: const Text('settings no 0')
    ));

    // 用forEach遍历数组,直接触发逻辑执行
    tilearray.forEach((item) {
      devtools.log('test${item['name']}');
      tiles.add(SettingsTile.switchTile(
        initialValue: lockInBackground,
        onToggle: (bool value) {
          setState(() {
            lockInBackground = value;
          });
        },
        leading: const Icon(Icons.phonelink_lock),
        title: Text(item['name']!)
      ));
    });

    devtools.log('$tiles');

    return Scaffold(
      appBar: AppBar(title: const Text('Settings UI')),
      body: SettingsList(
        sections: [
          SettingsSection(
            title: const Text('First Section'),
            tiles: tiles,
          )
        ]
      )
    );
  }
}

其他可选写法

如果你更倾向于使用map(),可以结合addAll()一次性添加所有生成的Tile:

tiles.addAll(tilearray.map((item) {
  devtools.log('test${item['name']}');
  return SettingsTile.switchTile(
    initialValue: lockInBackground,
    onToggle: (bool value) {
      setState(() {
        lockInBackground = value;
      });
    },
    leading: const Icon(Icons.phonelink_lock),
    title: Text(item['name']!)
  );
}));

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 00:10:36