flutter 类型“List< Widget>”不是“function result”的类型“List〈Map〈String,Object>>”的子类型

jjhzyzn0  于 2023-01-21  发布在  Flutter
关注(0)|答案(2)|浏览(148)

在下面的代码中,当我访问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',
          ),
        ],
      ),
    );
  }
}
8ftvxx2r

8ftvxx2r1#

尝试将List<Map<String, Object>>更改为List<Map<String, dynamic>>,它应该可以工作。
回到你的问题:

为什么它不适用于对象类型?

让我们看看您的列表项

{
 'page': CategoriesScreen(),
 'title': 'Categories',
},

在左端,有String字段,因此与我们在Map中使用的字段相同
现在,如果您注意到右端的数据类型,则有两种类型的值

  1. CategoriesScreen()这是Widget的一种类型
  2. 'Categories'这是String的类型
    因此,因为我们有多种类型的值,我们需要一个特定的type来适应这两种类型,这就是我们使用dynamic的原因
2sbarzqh

2sbarzqh2#

一旦将列表〈Map〈字符串,对象〉〉更改为列表〈Map〈字符串,动态〉〉
我希望这些东西能解决你的问题。

相关问题