如何在Flutter的多个屏幕上重用BottomNavigationBar小部件?

时间:2019-06-02 11:52:00

标签: flutter

所以我想知道是否有可能使用BottomNavigationBar小部件创建一个单独的类,然后在其他类中使用它。一个可行的示例会有所帮助。

2 个答案:

答案 0 :(得分:0)

您可以编写自己的课程:

class BottomNavigation extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return BottomNavigationBar(
        ...
      );
  }

然后导入页面并在sacffold中使用它:

bottomNavigationBar: BottomNavigation,

答案 1 :(得分:0)

也许我不太了解您的问题。不应在许多屏幕上看到BottomNavigationBar吗? 我的BottomNavigationBar位于MyApp类中,该类由主体调用。从MyApp类,启动我的应用程序的所有屏幕。我的代码如下:

class MyApp extends StatefulWidget
{
  MyApp({Key key,}) : super(key: key);

  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp>
{
  int _selectedIndex = 1;

  @override
  Widget build(BuildContext context)
  {
    ///////////Here are your different screens//////////////
    final _widgetOptions = [
      Screen1(),
      Screen2(),
      Screen3(),
    ];
    /////////////////////////////////

    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Name of your App',
      theme: ThemeData(primarySwatch: Colors.grey,
          accentColor: Colors.blueAccent,),

      home: Scaffold(
        backgroundColor: Colors.black12,

        body: Center
          (
          child: _widgetOptions.elementAt(_selectedIndex),
        ),


        //////////Bottom navigation////////////////
        bottomNavigationBar: Theme
          (
          data: Theme.of(context).copyWith(
            // sets the background color of the `BottomNavigationBar`
              canvasColor: Colors.white,
              // sets the active color of the `BottomNavigationBar`
              primaryColor: Colors.blueAccent,
              textTheme: Theme.of(context).textTheme.copyWith(
                  caption: new TextStyle(
                      color: Colors.grey))), // sets the inactive color of the                 
`BottomNavigationBar`
          child: new BottomNavigationBar(

            type: BottomNavigationBarType.fixed,


            items: <BottomNavigationBarItem>
            [
              new BottomNavigationBarItem(icon: Icon(Icons.local_hospital), title: Text('Screen 1')),
          new BottomNavigationBarItem(icon: Icon(Icons.search), title: Text('Screen 2')),
          new BottomNavigationBarItem(icon: Icon(Icons.play_for_work), title: Text('Screen 3')),
        ],

        currentIndex: _selectedIndex,
        fixedColor: Colors.deepPurple,
        onTap: _onItemTapped,
      ),

    ),
    /////////////End of Bottom Navigation


  ),
);
  }










  void _onItemTapped(int index)
  {
    setState(()
    {
      _selectedIndex = index;
    });

  }

}

您必须定义Screen1(),Screen2()和Screen3()。就我而言,它们是Statefulwidgets