在下面的代码中,当我访问body参数中的map时,我遇到了一个问题,它将显示错误object?type can't be assign to widget?type,因此我在运行后将其用作Widget,我得到了我在这里询问的错误,因此如何在不得到这些错误的情况下访问widget(这里是构造函数)。
import 'package:flutter/material.dart';
import '../screens/categories_screen.dart';
import '../screens/favorites_screen.dart';
class TabsScreenBottom extends StatefulWidget {
const TabsScreenBottom({Key? key}) : super(key: key);
@override
State<TabsScreenBottom> createState() => _TabsScreenBottomState();
}
class _TabsScreenBottomState extends State<TabsScreenBottom> {
final List<Map<String, Object>> _pages = const [
{
'page': CategoriesScreen(),
'title': 'Categories',
},
{
'page': FavoritesScreen(),
'title': 'My Favorites',
},
];
int _selectedPageIndex = 0;
void _selectPage(int index) {
setState(() {
_selectedPageIndex = index;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Meal'),
),
body: _pages[_selectedPageIndex]['page'] as Widget,
bottomNavigationBar: BottomNavigationBar(
backgroundColor: Theme.of(context).colorScheme.primary,
selectedItemColor: Theme.of(context).colorScheme.secondary,
unselectedItemColor: Colors.white,
currentIndex: _selectedPageIndex,
// type: BottomNavigationBarType.shifting,
// giving animation when tab is changed
onTap: _selectPage,
items: [
BottomNavigationBarItem(
backgroundColor: Theme.of(context).colorScheme.primary,
icon: const Icon(
Icons.category,
),
label: 'Categorey',
),
BottomNavigationBarItem(
// if your use type shifting
backgroundColor: Theme.of(context).colorScheme.primary,
icon: const Icon(
Icons.star,
),
label: 'Favorites',
),
],
),
);
}
}
2条答案
按热度按时间8ftvxx2r1#
尝试将
List<Map<String, Object>>
更改为List<Map<String, dynamic>>
,它应该可以工作。回到你的问题:
为什么它不适用于对象类型?
让我们看看您的列表项
在左端,有
String
字段,因此与我们在Map
中使用的字段相同现在,如果您注意到右端的数据类型,则有两种类型的值
CategoriesScreen()
这是Widget
的一种类型'Categories'
这是String
的类型因此,因为我们有多种类型的值,我们需要一个特定的
type
来适应这两种类型,这就是我们使用dynamic
的原因2sbarzqh2#
一旦将列表〈Map〈字符串,对象〉〉更改为列表〈Map〈字符串,动态〉〉
我希望这些东西能解决你的问题。