I'm still new to dart, so here is the issue, I'm trying to use the BottomNavigationBar
widget, to it we should have a list of widgets right?
I'm trying to also add a title to this list, so my list looks like this one:
final List<Map<String, dynamic>> _pages = [
const {'page': CategoriesScreen(), 'title': 'Categories'},
const {'page': FavouritesScreen(), 'title': "Favourite"}
]
and I'm using it like this:
body: _pages[_selectedPageIndex]['page'] as Widget
So far I get this error:
type 'List' is not a subtype of type 'List<Map<String, dynamic>>' of 'function result'
Here is the scaffold the reproduce the issue:
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Meals'),
),
body: _pages[_selectedPageIndex]['page'] as Widget,
bottomNavigationBar: BottomNavigationBar(
onTap: _selectPage,
backgroundColor: Theme.of(context).colorScheme.primary,
unselectedItemColor: Colors.white,
currentIndex: _selectedPageIndex,
// type: BottomNavigationBarType.fixed,
selectedItemColor: Theme.of(context).colorScheme.secondary,
items: [
BottomNavigationBarItem(
backgroundColor: Theme.of(context).colorScheme.primary,
icon: const Icon(Icons.category),
label: 'Categories',
),
BottomNavigationBarItem(
backgroundColor: Theme.of(context).colorScheme.primary,
icon: const Icon(Icons.star),
label: 'Favourites',
),
],
),
);
}
I believe the issue here is with the type definition for this list, so how should I define it?
CodePudding user response:
Just change the declaration of the _pages
to:
final List<Map<String, dynamic>> _pages = [
<String, dynamic>{
'page': Container(),
'title': 'Categories',
},
<String, dynamic>{
'page': Container(),
'title': 'Favourite',
}
];
The same use:
body: _pages[_selectedPageIndex]['page'] as Widget,
Recommended solution
I recommend you to create your custom model, e.g: "Screen" which will have following properties:
- page which is Widget type,
- title which is String type,
so:
class Screen {
const Screen({
required this.page,
required this.title,
});
final Widget page;
final String title;
}
then declare the list:
final List<Screen> _pages = [
Screen(page: Container(), title: 'Categoris'),
Screen(page: Container(), title: 'Favourite'),
];
and then use it:
body: _pages[_selectedPageIndex].page,