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

跟随Udemy教程开发餐厅App时遇Flutter类型匹配错误

Flutter类型错误解决:'Object?'无法赋值给'Widget?'

错误信息

Error: The argument type 'Object?' can't be assigned to the parameter type 'Widget?'.
tabs_screen.dart:34
  • Object 来自 dart:core
  • Widget 来自 package:flutter/src/widgets/framework.dart

报错代码行:

body: _pages[_selectPageIndex]['page'],

问题代码

class TapScreen extends StatefulWidget {
  const TapScreen({super.key});

  @override
  State<TapScreen> createState() => _TapScreenState();
}

List<Map<String, Object>> _pages = [
  {'page': CategoriesScreen(), 'title': 'Catergories'},
  {'page': FavoitesScreen(), 'title': 'your Favorites'}
];

class _TapScreenState extends State<TapScreen> {
  int _selectPageIndex = 0;
  void _selectPage(int index) {
    setState(() {
      _selectPageIndex = index;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("meal"),
      ),
      body: _pages[_selectPageIndex]['page'],
      bottomNavigationBar: BottomNavigationBar(
        onTap: _selectPage,
        backgroundColor: Theme.of(context).primaryColor,
        unselectedItemColor: Colors.white,
        selectedItemColor: Colors.amber,
        currentIndex: _selectPageIndex,
        type: BottomNavigationBarType.shifting,
        items: [
          BottomNavigationBarItem(
            backgroundColor: Theme.of(context).primaryColor,
            icon: Icon(Icons.star),
            label: 'Favorites',
          ),
          BottomNavigationBarItem(
            backgroundColor: Theme.of(context).primaryColor,
            icon: Icon(Icons.category),
            label: 'Favorites',
          ),
        ],
      ),
    );
  }
}

解决方法

问题核心是类型不匹配:_pages 被定义为 List<Map<String, Object>>,通过['page']取出的值类型为Object?,但Scaffold的body参数要求Widget?类型,以下是三种修复方案:

方案1:强制类型转换

直接将取出的值转换为Widget类型,这是最快捷的修复方式:

body: _pages[_selectPageIndex]['page'] as Widget,

方案2:优化集合类型定义

将_pages的类型改为List<Map<String, dynamic>>,让Dart自动推断内部元素类型:

List<Map<String, dynamic>> _pages = [
  {'page': CategoriesScreen(), 'title': 'Catergories'},
  {'page': FavoitesScreen(), 'title': 'your Favorites'}
];

方案3:自定义类封装(更规范)

创建专门的类来封装页面和标题,彻底避免类型问题:

class PageItem {
  final Widget page;
  final String title;

  PageItem({required this.page, required this.title});
}

List<PageItem> _pages = [
  PageItem(page: CategoriesScreen(), title: 'Catergories'),
  PageItem(page: FavoitesScreen(), title: 'your Favorites'),
];

使用时直接调用:

body: _pages[_selectPageIndex].page,

内容的提问来源于stack exchange,提问作者M.Shahzad

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 08:59:16