跟随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:coreWidget来自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
相关产品推荐
相关产品推荐

