在 flutter 中为每个单击的按钮更改 appBar

Change appBar in for each button clicked in flutter

有什么方法可以更改 AppBar 的 'title:' 以我的 BottomNavigationBar 的按钮标签为基础?我正在构建一个应用程序,导航栏将在单击按钮时调用每个 类',

也许像这样?

appbar: AppBar(
title: SelectedIndex(label/tile),
),

这是源代码:

import 'package:flutter/material.dart';

import 'BoosterCommunity_Page.dart';
import 'Diary_Page.dart';
import 'GradeTracker_Page.dart';
import 'CalendarView_Page.dart';
import 'QuotesPage.dart';
import 'ListView_Page.dart';

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

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

class _HomePageState extends State<HomePage> {
  PageController _pageController = PageController();
  List<Widget> _screens = [
    QuotesPage(), ListViewPage(), CalendarViewPage(), GradeTrackerPage(), DiaryPage(), BoosterCommunityPage(),
  ];

  void _onPageChanged(int index) {}
  void _onItemsTapped(int selectedIndex) {
    _pageController.jumpToPage(selectedIndex);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,

        //I want it to be implemented in this line

        title: (BottomNavBar selected index title or label),
      ),
      body: PageView(
        controller: _pageController,
        children: _screens,
        onPageChanged: _onPageChanged,
        physics: NeverScrollableScrollPhysics(),
      ),
      bottomNavigationBar: BottomNavigationBar(
        onTap: _onItemsTapped,
        items: [
          BottomNavigationBarItem(
            icon: Icon(Icons.home, color: Colors.grey,),
            label: 'Home',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.list, color: Colors.grey,),
            label: 'Task List',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.calendar_view_month, color: Colors.grey,),
            label: 'Calendar View',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.grade, color: Colors.grey,),
            label: 'Grade Tracker',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.book, color: Colors.grey,),
            label: 'Diary Page',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.business, color: Colors.grey,),
            label: 'Booster Community',
          ),                                                
        ],
      ),
            drawer: Drawer(
        child: ListView(
          padding: EdgeInsets.zero,
          children: [
            Container(
              height: 100.0,
              child: const DrawerHeader(
              decoration: BoxDecoration(
              color: Colors.orange,
              ),
              child: Text('Sign in first'),
            ),
            ),
            ListTile(
              title: const Text('Account'),
              onTap: () {
                Navigator.pop(context);
              },
            ),
            ListTile(
              title: const Text('Settings'),
              onTap: () {
                Navigator.pop(context);
              },
            ),
            ListTile(
              title: const Text('Help and Support'),
              onTap: (){
                Navigator.pop(context);
              },
            ),
          ],
        ),
      ),  
    );
  }
}

是否可行或者有简单的方法吗?请让我知道,提前谢谢你。

是的,很容易。只需在变量中定义 NavigationBarItems,用 setState 更新 onTap 中的选择索引,并根据选择设置 appBar 标题。像这样:

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const HomePage(),
    );
  }
}

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

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

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

  static const _navigationBarItems = <BottomNavigationBarItem>[
    BottomNavigationBarItem(
      icon: Icon(Icons.home),
      label: 'Home',
    ),
    BottomNavigationBarItem(
      icon: Icon(Icons.message),
      label: 'Message',
    ),
    BottomNavigationBarItem(
      icon: Icon(Icons.person),
      label: 'Person',
    ),
  ];

  static const List<Widget> _pages = <Widget>[
    Text('home'),
    Text('message'),
    Text('person'),
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(_navigationBarItems[_currentIndex].label!),
      ),
      body: Center(
        child: _pages.elementAt(_currentIndex),
      ),
      bottomNavigationBar: BottomNavigationBar(
        items: _navigationBarItems,
        currentIndex: _currentIndex,
        selectedItemColor: Colors.amber[800],
        onTap: (int index) {
          setState(() {
            _currentIndex = index;
          });
        },
      ),
    );
  }
}

试试这个,这里我使用 currentPage 保存所选底部导航项的索引,使用 pageTitle 在应用栏上显示标题。现在,每当用户点击底部栏中的项目时,您所要做的就是通过获取地图 bottomNavigateData 中索引处的特定键来更新 currentIndex 和 pageTitle。

    import 'package:flutter/material.dart';

    void main() =>
        runApp(MaterialApp(debugShowCheckedModeBanner: false, home: 
    HomePage()));
    
    class HomePage extends StatefulWidget {
      @override
      _HomePageState createState() => _HomePageState();
    }

class _HomePageState extends State<HomePage> {
  static int currentPage = 0;
  static Map<String, Icon> bottomNavigateData = {
    'Home': const Icon(
      Icons.home,
      color: Colors.grey,
    ),
    'Task List': const Icon(
      Icons.list,
      color: Colors.grey,
    ),
  };
  String pageTitle = bottomNavigateData.keys.first;

  final PageController _pageController = PageController();
  final List<Widget> _screens = [
    QuotesPage(),
    ListViewPage(),
  ];

      void _onPageChanged(int index) {}
      void _onItemsTapped(int selectedIndex) {
        setState(() {
          currentPage = selectedIndex;
          pageTitle = bottomNavigateData.keys.elementAt(selectedIndex);
    });
    _pageController.jumpToPage(selectedIndex);
  }

  @override
  Widget build(BuildContext context) {
    List<BottomNavigationBarItem> navigations = [];
    bottomNavigateData
        .forEach((k, v) => navigations.add(BottomNavigationBarItem(
              icon: v,
              label: k,
            )));
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: Text(pageTitle),
      ),
      body: PageView(
        controller: _pageController,
        children: _screens,
        onPageChanged: _onPageChanged,
        physics: const NeverScrollableScrollPhysics(),
      ),
      bottomNavigationBar: BottomNavigationBar(
          currentIndex: currentPage, onTap: _onItemsTapped, items: navigations),
      drawer: Drawer(
        child: ListView(
          padding: EdgeInsets.zero,
          children: [
            Container(
              height: 100.0,
              child: const DrawerHeader(
                decoration: BoxDecoration(
                  color: Colors.orange,
                ),
                child: Text('Sign in first'),
              ),
            ),
            ListTile(
              title: const Text('Account'),
              onTap: () {
                Navigator.pop(context);
              },
            ),
            ListTile(
              title: const Text('Settings'),
              onTap: () {
                Navigator.pop(context);
              },
            ),
            ListTile(
              title: const Text('Help and Support'),
              onTap: () {
                Navigator.pop(context);
              },
            ),
          ],
        ),
      ),
    );
  }
}

Widget QuotesPage() {
  return Container(color: Colors.white, child: const Text("Page1"));
}

Widget ListViewPage() {
  return Container(color: Colors.white, child: const Text("Page2"));
}