Cannot define CupertinoTabBar settings in separate file

61 views Asked by At

I defined the whole CupertinoTabBar in class TabTwo in another file, but I cannot use TabTwo in main.dart.

error report:

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:

import 'package:flutter/cupertino.dart';

class TabTwo extends StatelessWidget {
  const TabTwo({Key? key}) : super(key: key);

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

I tried the code above but got an error. How do I fix this?

1

There are 1 answers

0
Ante Bule On

The TabTwo needs to extend the CupertinoTabBar (not the StatelessWidget) in order to be used instead of CupertinoTabBar itself, like so:

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',
        ),
      ],
    );
  }
}