flutter 无法在单独的文件中定义CupertinoTabBar设置

yxyvkwin  于 2022-12-05  发布在  Flutter
关注(0)|答案(1)|浏览(104)

我在另一个文件的TabTwo类中定义了整个CupertinoTabBar,但是我不能在main. dart中使用TabTwo。
错误报告:

lib/main.dart:24:15: Error: The argument type 'TabTwo' can't be assigned to the parameter type 'CupertinoTabBar'.
 - 'TabTwo' is from 'package:untitled/tabtwo.dart' ('lib/tabtwo.dart').
 - 'CupertinoTabBar' is from 'package:flutter/src/cupertino/bottom_tab_bar.dart' ('../../../../snap/flutter/common/flutter/packages/flutter/lib/src/cupertino/bottom_tab_bar.dart').
      tabBar: TabTwo(),

main.dart:

import 'package:flutter/cupertino.dart';
import 'tabtwo.dart';

void main() => runApp(const CupertinoTabBarApp());

class CupertinoTabBarApp extends StatelessWidget {
  const CupertinoTabBarApp({super.key});

  @override
  Widget build(BuildContext context) {
    return const CupertinoApp(
      theme: CupertinoThemeData(brightness: Brightness.light),
      home: CupertinoTabBarExample(),
    );
  }
}

class CupertinoTabBarExample extends StatelessWidget {
  const CupertinoTabBarExample({super.key});

  @override
  Widget build(BuildContext context) {
    return CupertinoTabScaffold(
      tabBar: TabTwo(),
      tabBuilder: (BuildContext context, int index) {
        return const Text('example');
      },
    );
  }
}

tabtwo.dart:
导入“ Package :flutter/库比蒂诺. dart”;
类TabTwo扩展了无状态控件{ const TabTwo({键?键}):super(键:键);
@override Widget build(BuildContext上下文){返回CupertinoTabBar(项:const [底部导航栏项目(图标:图标(CupertinoIcons.star_fill),标签:“收藏夹”、)、底部导航栏项目(图标:图标(Cupertino图标.时钟_实心),标签:'最近'、)、]、);()}}
我尝试了上面的代码,但得到了一个错误。我该如何修复这个问题?

lzfw57am

lzfw57am1#

TabTwo需要扩展CupertinoTabBar(而不是StatelessWidget),以便代替CupertinoTabBar本身使用,如下所示:

class TabTwo extends CupertinoTabBar {
  const TabTwo(List<BottomNavigationBarItem> items, {Key? key}) : super(items: items, key: key);

  @override
  Widget build(BuildContext context) {
    return CupertinoTabBar(
      items: const [
        BottomNavigationBarItem(
          icon: Icon(CupertinoIcons.star_fill),
          label: 'Favourites',
        ),
        BottomNavigationBarItem(
          icon: Icon(CupertinoIcons.clock_solid),
          label: 'Recents',
        ),
      ],
    );
  }
}

相关问题