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

Flutter技术疑问:GridView中map转换代码的作用是什么?

代码片段解释:GridView子项生成逻辑

我们用模拟数据DUMMY_CATEGORIES,基于分类的id、title、color属性创建GridView,但这段代码的作用不太清楚:

children: DUMMY_CATEGORIES.map((catData) => CategoryItem(catData.id, catData.title, catData.color)).toList(),

逐部分拆解说明:

  • DUMMY_CATEGORIES.map(...):map是Dart集合的内置方法,会遍历DUMMY_CATEGORIES里的每一个Category对象(也就是代码里的catData),对每个对象执行后续的转换逻辑。
  • (catData) => CategoryItem(...):这是简化的箭头函数,拿到遍历到的单个分类数据catData后,用它的id、title、color三个属性,创建一个你自定义的CategoryItem组件——这个组件就是用来展示单个分类卡片的UI单元,带渐变背景和点击跳转功能。
  • .toList():map方法执行后返回的是一个Iterable(可迭代对象),但GridView的children属性要求传入List<Widget>类型的数据,所以用toList()把转换后的可迭代对象转成符合要求的列表。

简单说,这段代码就是把模拟的分类数据批量转换成对应的UI卡片组件,让GridView能把这些卡片排列成网格布局。


完整Flutter代码

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Meals App',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: CategoryScreen(),
    );
  }
}

class CategoryScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Meals App'),
      ),
      body: GridView(
        children: DUMMY_CATEGORIES.map((catData) => CategoryItem(catData.id, catData.title, catData.color)).toList(),
        gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent(
          maxCrossAxisExtent: 200, 
          childAspectRatio: 3 / 2, 
          crossAxisSpacing: 20, 
          mainAxisSpacing: 20, 
        ),
      ),
    );
  }
}

class Category {
  final String id;
  final String title;
  final Color color;
  Category({required this.id, required this.title, this.color = Colors.orange});
}

class CategoryItem extends StatelessWidget {
  final String id;
  final String title;
  final Color color;
  CategoryItem(this.id, this.title, this.color);

  @override
  Widget build(BuildContext context) {
    return InkWell(
      onTap: () {
        Navigator.of(context).push(
          MaterialPageRoute(
            builder: (_) => CategoryMealsScreen(id, title),
          ),
        );
      },
      child: Container(
        padding: const EdgeInsets.all(10),
        child: Text(title),
        decoration: BoxDecoration(
          gradient: LinearGradient(
            colors: [
              color.withOpacity(0.7),
              color,
            ],
            begin: Alignment.topLeft,
            end: Alignment.bottomRight,
          ),
          borderRadius: BorderRadius.circular(15),
        ),
      ),
    );
  }
}
class CategoryMealsScreen extends StatelessWidget {
  final String categoryId;
  final String categoryTitle;
  CategoryMealsScreen(this.categoryId, this.categoryTitle);

  @override
  Widget build(BuildContext context) {
    final categoryMeals = DUMMY_MEALS.where((meal) {
      return meal.categories.contains(categoryId);
    }).toList();

    return Scaffold(
      appBar: AppBar(
        title: Text('Meals - $categoryTitle'),
      ),
      body: ListView.builder(
        itemCount: categoryMeals.length,
        itemBuilder: (ctx, index) {
          return InkWell(
            onTap: () {
              Navigator.of(context).push(
                MaterialPageRoute(
                  builder: (_) => MealDetailScreen(categoryMeals[index]),
                ),
              );
            },
            child: Card(
              child: Padding(
                padding: const EdgeInsets.all(8.0),
                child: Text(categoryMeals[index].title),
              ),
            ),
          );
        },
      ),
    );
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 16:10:39