根据带有 BottomNavigationBar 的页面更改 AppBar 标题

问题描述 投票:0回答:6

我正在尝试根据用户所在的页面更改 AppBar 标题 - 页面由加载不同类(页面)的 BottomNavigationBar 控制

我设法改变这一点的唯一方法是为每个页面添加一个应用栏,我认为这不是继续下去的方法。

class HomePage extends StatefulWidget {
  final String title;

  HomePage({Key key, this.auth, this.userId, this.onSignedOut, this.title})
      : super(key: key);

  final BaseAuth auth;
  final VoidCallback onSignedOut;
  final String userId;

  @override
  State<StatefulWidget> createState() => new _HomePageState();
}

class _HomePageState extends State<HomePage> {
  int _currentIndex = 0;
  final List<Widget> _children = [
    Projects(),
    TimedProject(),
    Overview(),
    Clients(),
  ];

  GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey();

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      key: _scaffoldKey,
      appBar: AppBar(
        title: Text('TITLE I NEED TO CHANGE DEPENDING ON PAGE',
          style: TextStyle(color: Colors.black),
        ),

        backgroundColor: Colors.white,
      ),
      endDrawer: AppDrawer(),
      body: _children[_currentIndex],
      bottomNavigationBar: BottomNavigationBar(
        onTap: onTabTapped,
        currentIndex: _currentIndex,
        selectedItemColor: Theme.of(context).primaryColor,
        type: BottomNavigationBarType.fixed,
        items: [
          new BottomNavigationBarItem(
            icon: Icon(Icons.storage),
            title: Text('Jobs'),
          ),
          new BottomNavigationBarItem(
            icon: Icon(Icons.timer),
            title: Text('Timer'),
          ),
          new BottomNavigationBarItem(
            icon: Icon(Icons.pie_chart_outlined),
            title: Text('Overview'),
          ),
          new BottomNavigationBarItem(
              icon: Icon(Icons.supervisor_account), title: Text('Clients'))
        ],
      ),
    );
  }

  void onTabTapped(int index) {
    setState(() {
      _currentIndex = index;
    });
  }
}
flutter appbar
6个回答
26
投票

创建一个保存应用程序栏标题的变量,或者您可以使用在 HomePage 类中传递的相同标题变量,但必须删除最终的变量。

如果您在 HomePage 类中使用 title 变量,请确保使用 “小部件.标题”

class HomePage extends StatefulWidget {
  final String title;

  HomePage({Key key, this.auth, this.userId, this.onSignedOut, this.title})
      : super(key: key);

  final BaseAuth auth;
  final VoidCallback onSignedOut;
  final String userId;

  @override
  State<StatefulWidget> createState() => new _HomePageState();
 }

class _HomePageState extends State<HomePage> {
  int _currentIndex = 0;
  String _title;

  final List<Widget> _children = [
     Projects(),
     TimedProject(),
     Overview(),
     Clients(),
  ];

  GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey();

 @override
  initState(){
    _title = 'Some default value';
  }


  @override
  Widget build(BuildContext context) {
     return new Scaffold(
       key: _scaffoldKey,
       appBar: AppBar(
       title: Text(_title,
          style: TextStyle(color: Colors.black),
       ),

       backgroundColor: Colors.white,
      ),
  endDrawer: AppDrawer(),
  body: _children[_currentIndex],
  bottomNavigationBar: BottomNavigationBar(
    onTap: onTabTapped,
    currentIndex: _currentIndex,
    selectedItemColor: Theme.of(context).primaryColor,
    type: BottomNavigationBarType.fixed,
    items: [
      new BottomNavigationBarItem(
        icon: Icon(Icons.storage),
        title: Text('Jobs'),
      ),
      new BottomNavigationBarItem(
        icon: Icon(Icons.timer),
        title: Text('Timer'),
      ),
      new BottomNavigationBarItem(
        icon: Icon(Icons.pie_chart_outlined),
        title: Text('Overview'),
      ),
      new BottomNavigationBarItem(
          icon: Icon(Icons.supervisor_account), title: Text('Clients'))
    ],
  ),
);
}

   void onTabTapped(int index) {
     setState(() {
     _currentIndex = index;
      switch(index) { 
       case 0: { _title = 'Jobs'; } 
       break; 
       case 1: { _title = 'Timer'; } 
       break;
       case 2: { _title = 'Overview'; } 
       break;
       case 3: { _title = 'Clients'; } 
       break; 
      } 
     });
   }
}

3
投票

感谢您的解决方案,是否可以将底部导航放在自己的 .dart 文件中,例如

bottomNavigationBar: BottomNavBar(),

并获取所选选项卡索引

class _HomeScreen2State extends State<HomeScreen2> {
  //Hold current Tab Index
  int _selectTab = 0;
  final _pageOptions = [
    HomeScreen(),
    NewOrderScreen(),
    OrderHistoryScreen(),
    ContactScreen(),
  ];
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Gift Shop Dashboard'),
      ),
      body: _pageOptions[_selectTab],
      bottomNavigationBar: BottomNavBar(),
    );
  }
}

0
投票

要将

BottomNavigationBar
分离到不同的
.dart
文件中,例如在
config.dart
中:

import 'package:flutter/material.dart';

class Config {

  static List<BottomNavigationBarItem> navigationBarItems = [
    BottomNavigationBarItem(
      icon: Icon(
        Icons.date_range,
      ),
      title: Text(
        "Calendar",
      ),
    ),
    BottomNavigationBarItem(
      icon: Icon(
        Icons.list, // event_note
      ),
      title: Text(
        "List",
      ),
    ),
    BottomNavigationBarItem(
      icon: Icon(
        Icons.bookmark_border, // grid_on 
      ),
      title: Text(
        "Bookmarks",
      ),
    ),
    BottomNavigationBarItem(
      icon: Icon(
        Icons.account_circle,
      ),
      title: Text(
        "Me",
      ),
    ),
  ];

  static BottomNavigationBar navigationBar = BottomNavigationBar(
    items: navigationBarItems,
    type: BottomNavigationBarType.fixed,
    fixedColor: Colors.red,
  );

}

main.dart

import 'package:flutter/material.dart';
import 'config.dart';

void main() => runApp(App());

class App extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Hello',
      theme: ThemeData(
        primarySwatch: Colors.blueGrey,
      ),
      home: HomePage(),
    );
  }
}

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

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

class _HomePageState extends State<HomePage> {

  int _index = 0;
  Text _title;

  _onTap(int index) {
    setState(() {
      _index = index;
      _title = Config.navigationBarItems[_index].title;
    });
  }

  @override
  void initState() {
    _title = Config.navigationBarItems[_index].title;
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: _title,
      ),
      body: Container(
      ),
      bottomNavigationBar: BottomNavigationBar(
        currentIndex: _index,
        type: Config.navigationBar.type,
        fixedColor: Config.navigationBar.fixedColor,
        items: Config.navigationBar.items,
        onTap: _onTap,
      ),
    );
  }
}

0
投票

只需在ontap中设置条件即可

class _MyStatefulWidgetState extends State<MyStatefulWidget> {
int _selectedIndex = 1;
String appbarTitleString = "Home";
var appBarTitleText = new Text("Home");
static const TextStyle optionStyle =
TextStyle(fontSize: 30, fontWeight: FontWeight.bold);
static const List<Widget> _widgetOptions = <Widget>[
Text(
  'Index 0: Profile',
  style: optionStyle,
),
Text(
  'Index 1: Home',
  style: optionStyle,
),
Text(
  'Index 2: More',
  style: optionStyle,
),
 ];

@override
Widget build(BuildContext context) {
return Scaffold(

  appBar: AppBar(
    title: appBarTitleText,
  ),
  body: Center(
    child: _widgetOptions.elementAt(_selectedIndex),
  ),
  bottomNavigationBar: BottomNavigationBar(
    items: const <BottomNavigationBarItem>[
      BottomNavigationBarItem(
        icon: Icon(Icons.business),
        title: Text('Profile'),
      ),
      BottomNavigationBarItem(
        icon: Icon(Icons.home),
        title: Text('Home'),
      ),
      BottomNavigationBarItem(
        icon: Icon(Icons.school),
        title: Text('More'),
      ),
    ],
    currentIndex: _selectedIndex,
    selectedItemColor: Colors.amber[800],
    onTap: _onItemTapped,
  ),
);
}
void _onItemTapped(int index) {
setState(() {
  _selectedIndex = index;
  if (index == 0){
    appbarTitleString = "Profile" ;
    appBarTitleText = new Text(appbarTitleString);
  }else if (index == 1){
    appbarTitleString = "Home" ;
    appBarTitleText = new Text(appbarTitleString);
  }else if(index == 2){
    appbarTitleString = "More" ;
    appBarTitleText = new Text(appbarTitleString);
  }
});
}
}

0
投票

如果您对不同的页面也有不同的操作、引导等,您可以在单独的文件中拥有不同的应用栏并像页面一样导入它们。

static final List<Widget> _pages = [
  const HomeScreen(),
  const BookingScreen(),
  const AccountScreen(),
];

static final List<Widget> _appBars = [
  const HomeAppBar(),
  const BookingAppBar(),
  const AccountAppBar(),
];

然后你可以有变量:

int _selectedIndex = 0;

您的 onTapped 函数将类似于:

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

你的构建将是这样的:

@override
Widget build(BuildContext context) {
  return Scaffold(
    appBar: PreferredSize(
      preferredSize: const Size.fromHeight(56), // 56 is default height
      child: _appBars[_selectedIndex],
    ), // PreferredSize

    body: _pages[_selectedIndex],

    bottomNavigationBar: BottomNavigationBar(
      currentIndex: _selectedIndex,
      onTap: _onItemTapped,
      items: const [
        BottomNavigationBarItem(
          icon: Icon(Icons.home_rounded),
          label: "Home",
        ), // BottomNavigationBarItem
        BottomNavigationBarItem(
          icon: Icon(Icons.schedule_rounded),
          label: "Bookings",
        ), // BottomNavigationBarItem
        BottomNavigationBarItem(
          icon: Icon(Icons.person_rounded),
          label: "Account",
        ), // BottomNavigationBarItem
      ],
    ), // BottomNavigationBar
  ); // Scaffold
}

0
投票

太简单了,只用两个变量就可以处理了。

取两个变量,例如:

   int _selectedIndex = 0;
   String _page_title = "DashBoard";

并替换每个更改的索引上的页面标题。就像下面这样,

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

  if (index == 0) {
    _page_title = "DashBoard";
  } else if (index == 1) {
    _page_title = "Search";
  } else if (index == 2) {
    _page_title = "Setting";
  } else if (index == 3) {
    _page_title = "Profile";
  }
});

制作一个列表,决定从选定的选项卡执行任务。

 static const List<Widget> _widgetOptions = <Widget>[
    Text(
      'Home 1',
      style: optionStyle,
    ),
    Text(
      'Home 2',
      style: optionStyle,
    ),
    Text(
      'Home 3',
      style: optionStyle,
    ),
    Profile(),
  ];

并调整 Build() 函数中的代码如下。

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: AppBar(
        title: Text(_page_title),
        automaticallyImplyLeading: false, // hide back arrow from appbar
      ),
      body: Center(
        child: _widgetOptions.elementAt(_selectedIndex),
      ),
      bottomNavigationBar: BottomNavigationBar(
        items: const <BottomNavigationBarItem>[
          BottomNavigationBarItem(
            icon: Icon(
              Icons.home,
              color: Colors.grey,
            ),
            label: 'Home',
          ),
          BottomNavigationBarItem(
            icon: Icon(
              Icons.search,
              color: Colors.grey,
            ),
            label: 'Search',
          ),
          BottomNavigationBarItem(
            icon: Icon(
              Icons.settings,
              color: Colors.grey,
            ),
            label: 'Setting',
          ),
          BottomNavigationBarItem(
            icon: Icon(
              Icons.face_retouching_natural_sharp,
              color: Colors.grey,
            ),
            label: 'Profile',
          ),
        ],
        currentIndex: _selectedIndex,
        selectedItemColor: Colors.blue,
        onTap: _onItemTapped,
      ),
    );
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.