Ошибка сопоставления flutter: тип String не является подтипом типа Widget в приведении типов - PullRequest
1 голос
/ 07 августа 2020

Я использую bottomNavigationBar с двумя элементами, которые я определяю на карте:

final List<Map<String, Object>> _pages = [
{
  'page': CategoriesScreen(),//My categories widget
  'title': 'Categories',//title of current page (with navigation bar)
},
{
  'page': FavoritesScreen(),//My favorites widget
  'title': 'Your Favorite',//title of current page (with navigation bar)
},

];

Когда я использую его так:

return Scaffold(
  appBar: AppBar(
    title: Text(_pages[_selectedPageIndex]['title']),
  ),
  body: _pages[_selectedPageIndex]['page'],//<----- ERROR HERE
  bottomNavigationBar: BottomNavigationBar(....

Когда я пытаюсь запустить приложение из студии Android, я получаю сообщение об ошибке:

тип String не является подтипом типа Widget в типе cast

Любая идея, почему?

Обновление 1 (полный код) :

import 'package:flutter/material.dart';    
import './favorites_screen.dart';
import './categories_screen.dart';

class TabsScreen extends StatefulWidget {
  @override
  _TabsScreenState createState() => _TabsScreenState();
}

class _TabsScreenState extends State<TabsScreen> {

  final List<Map<String, Object>> _pages = [
    {
      'page': CategoriesScreen(),
      'title': 'Categories',
    },
    {
      'page': FavoritesScreen(),
      'title': 'Your Favorite',
    },
  ];
  
  int _selectedPageIndex = 0;

  void _selectPage(int index) {
    setState(() {
      _selectedPageIndex = index;
    });
  }

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

Спасибо

1 Ответ

1 голос
/ 07 августа 2020

Не нужно помещать его на карту. Просто используйте List для _pages и добавьте заголовок виджет State на TabsScreen.

import 'package:flutter/material.dart';    
import './favorites_screen.dart';
import './categories_screen.dart';

class TabsScreen extends StatefulWidget {
  @override
  _TabsScreenState createState() => _TabsScreenState();
 }

 class _TabsScreenState extends State<TabsScreen> {

  final List<Widget> _pages = [
    CategoriesScreen(),
    FavoritesScreen(),
  ];

  String title = 'Categories';

  int _selectedPageIndex = 0;

  void _selectPage(int index) {
    setState(() {
      _selectedPageIndex = index;
      if (_selectedPageIndex == 0) {
          title = 'Categories';
      } else if (_selectedPageIndex == 1) {
          title = 'Your Favorite';
      }
    });
  }

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

Я все еще ищу более элегантный способ достижения, но этот подход работает.

...