所选项目未在 BottomNavigationBar Flutter 中更新

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

当我在预订屏幕上,然后按顺序切换到团队、亮点或任何其他选项时,在按回这些屏幕时,底部导航栏中的所选项目保持固定,并且当屏幕返回时不会改变。

例如,当我按底部导航栏中的统计项目,然后导航到统计屏幕时,按后退按钮后,屏幕将更改为上一个屏幕。但是,在底部导航栏中,统计项目仍然显示为绿色,而不是指示当前屏幕。

下面是 HomeView 小部件的代码:

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:sportifan_user/screens/main/bookings.dart';
import 'package:sportifan_user/screens/main/choose_match.dart';
import 'package:sportifan_user/screens/main/create_team.dart';
import 'package:sportifan_user/screens/main/edit_team.dart';
import 'package:sportifan_user/screens/main/highlights.dart';
import 'package:sportifan_user/screens/main/stats.dart';
import 'package:sportifan_user/screens/main/venue_screen.dart';
import 'package:sportifan_user/screens/main/your_teams.dart';
import 'package:sportifan_user/widgets/highlights_widget.dart';
import 'package:sportifan_user/widgets/sidebar.dart';
import 'package:sportifan_user/widgets/top_navigation_bar.dart';

class HomeView extends StatefulWidget {
  const HomeView({super.key});

  @override
  State<HomeView> createState() => _HomeViewState();
}

class _HomeViewState extends State<HomeView> with RouteAware {
  int currentIndex = 0;

  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();

  void onTap(int index) {
    setState(() {
      currentIndex = index;
    });
    switch (index) {
      case 0:
        navigatorKey.currentState?.pushNamed('/');
        break;
      case 1:
        navigatorKey.currentState?.pushNamed('/teams');
        break;
      case 2:
        navigatorKey.currentState?.pushNamed('/highlights');
        break;
      case 3:
        navigatorKey.currentState?.pushNamed('/stats');
        break;
    }
  }

  final RouteObserver<PageRoute> routeObserver = RouteObserver<PageRoute>();

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    routeObserver.subscribe(this, ModalRoute.of(context) as PageRoute);
  }

  @override
  void dispose() {
    routeObserver.unsubscribe(this);
    super.dispose();
  }

  @override
  void didPopNext() {
    _updateCurrentIndex();
  }

  void _updateCurrentIndex() {
    // Define this method to update currentIndex based on the current route
    switch (ModalRoute.of(context)?.settings.name) {
      case '/':
        setState(() {
          currentIndex = 0;
        });
        break;
      case '/teams':
        setState(() {
          currentIndex = 1;
        });
        break;
      case '/highlights':
        setState(() {
          currentIndex = 2;
        });
        break;
      case '/stats':
        setState(() {
          currentIndex = 3;
        });
        break;
    }
  }

  @override
  Widget build(BuildContext context) {
    TextEditingController teamController = TextEditingController();
    TextEditingController uidController = TextEditingController();
    TextEditingController controller = TextEditingController();
    return WillPopScope(
      onWillPop: () async {
        if (navigatorKey.currentState?.canPop() ?? false) {
          navigatorKey.currentState?.pop();
          Future.delayed(Duration.zero, () {
            _updateCurrentIndex(); // Add this line
          });
          return false; // Prevent the default back button behavior
        }
        return true; // Allow the default back button behavior if there's no route to pop
      },
      child: Container(
        color: Color(0xFF238F20),
        child: SafeArea(
          child: Scaffold(
            key: _scaffoldKey,
            appBar: PreferredSize(
              preferredSize: Size.fromHeight(72.0), // Set the height here
              child: TopNavigationBar(
                controller: controller,
                onNotificationIconTapped: () {
                  _scaffoldKey.currentState?.openDrawer();
                },
              ),
            ),
            drawer: SideBar(
              notificationExists: true,
            ),
            body: NotificationListener<PopNavigatorNotification>(
              onNotification: (notification) {
                _updateCurrentIndex();
                return true;
              },
              child: Navigator(
                key: navigatorKey,
                initialRoute: '/',
                onGenerateRoute: (RouteSettings settings) {
                  WidgetBuilder builder;
                  switch (settings.name) {
                    case '/':
                      builder = (BuildContext _) => BookingView();
                      break;
                    case '/teams':
                      builder = (BuildContext _) => YourTeams();
                      break;
                    case '/highlights':
                      builder = (BuildContext _) =>
                          HighlightsView(highlightsExists: true);
                      break;
                    case '/stats':
                      builder =
                          (BuildContext _) => StatsView(statsExists: true);
                      break;
                    default:
                      throw Exception('Invalid route: ${settings.name}');
                  }
                  return MaterialPageRoute(
                      builder: builder, settings: settings);
                },
              ),
            ),
            bottomNavigationBar: Theme(
              data: Theme.of(context).copyWith(
                canvasColor: Colors.white,
                primaryColor: Color(0xFF238F20),
                textTheme: Theme.of(context).textTheme.copyWith(
                      caption: TextStyle(color: Colors.grey),
                    ),
                bottomNavigationBarTheme: BottomNavigationBarThemeData(
                  backgroundColor: Colors.white,
                  elevation: 0,
                ),
              ),
              child: BottomNavigationBar(
                currentIndex: currentIndex,
                onTap: onTap,
                items: [
                  BottomNavigationBarItem(
                    icon: Icon(
                      Icons.book,
                    ),
                    label: 'Booking',
                  ),
                  BottomNavigationBarItem(
                    icon: Icon(Icons.people),
                    label: 'Teams',
                  ),
                  BottomNavigationBarItem(
                    icon: Icon(Icons.sports_cricket),
                    label: 'Highlights',
                  ),
                  BottomNavigationBarItem(
                    icon: Icon(Icons.graphic_eq),
                    label: 'Stats',
                  ),
                ],
                selectedItemColor:
                    Color(0xFF238F20), // change this to your preferred color
                unselectedItemColor: Colors.grey,
                showSelectedLabels: true,
                showUnselectedLabels: true,
              ),
            ),
          ),
        ),
      ),
    );
  }
}

class PopNavigatorNotification extends Notification {}

我付出了很多努力,正如你在阅读代码时看到的那样,但不幸的是,我没有得到任何回报。如果有人可以帮忙,请帮忙。

android ios iphone flutter dart
1个回答
0
投票

我会尝试在 onWillPop 函数中交换这些行:

          Future.delayed(Duration.zero, () {
            _updateCurrentIndex(); 
          });
          navigatorKey.currentState?.pop();
© www.soinside.com 2019 - 2024. All rights reserved.