Flutter android 默认后退按钮最小化每个小部件上的应用程序

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

这是我的 ymal 文件,

name: dtlive
description: A new Flutter project.

# The following line prevents the package from being accidentally published to
# pub.dev using `flutter pub publish`. This is preferred for private packages.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev

# The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in flutter
# build by specifying --build-name and --build-number, respectively.
# In Android, build-name is used as versionName while build-number used as versionCode.
# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
# In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion.
# Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
version: 1.0.0+1

environment:
  sdk: '>=3.1.3 <4.0.0'
  flutter: ">=1.10.0"

# Dependencies specify other packages that your package needs in order to work.
# To automatically upgrade your package dependencies to the latest versions
# consider running `flutter pub upgrade --major-versions`. Alternatively,
# dependencies can be manually updated by changing the version numbers below to
# the latest version available on pub.dev. To see which dependencies have newer
# versions available, run `flutter pub outdated`.
dependencies:
  flutter:
    sdk: flutter
  chewie:
    path: packages/chewie/
  vimeo_video_player:
    path: packages/vimeo/

  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^1.0.3
  google_fonts: ^4.0.0
  buttons_tabbar: ^1.3.7
  # Players
  youtube_player_iframe: ^4.0.4
  video_player: ^2.7.0
  video_player_web_hls: ^1.0.0+3
  subtitle_wrapper_package: ^2.1.1
  # Players
  # Payment Gateways
  razorpay_web: ^1.3.5
  paytm_allinonesdk: ^1.2.1
  flutter_stripe: ^9.2.2
  flutter_dotenv: ^5.1.0
  http_auth: ^1.0.2
  flutter_paypal: ^0.2.0
  flutterwave_standard: ^1.0.4
  uuid: ^4.0.0
  payu_checkoutpro_flutter: ^1.0.4
  pay_with_paystack: ^1.0.6
  # Payment Gateways
  # Firebase - OneSignal
  sign_in_with_apple: ^5.0.0
  crypto: ^3.0.3
  google_sign_in: ^6.1.5
  firebase_core: ^2.15.1
  firebase_auth: ^4.9.0
  firebase_auth_platform_interface: ^6.18.0
  onesignal_flutter: ^5.0.0
  firebase_messaging: ^14.6.7
  google_mobile_ads: ^3.0.0
  # Firebase - OneSignal
  intl_phone_field: ^3.2.0
  http: ^0.13.6
  pinput: ^2.2.31
  intl: ^0.18.0
  flutter_locales: ^3.0.1
  image_picker: ^1.0.0
  fluttertoast: ^8.2.2
  shared_preferences: ^2.0.15
  smooth_page_indicator: ^1.1.0
  percent_indicator: ^4.2.3
  dio: ^5.2.1+1
  pretty_dio_logger: ^1.3.1
  provider: ^6.0.5
  progress_dialog_null_safe: ^1.0.7
  expandable_text: ^2.3.0
  flutter_staggered_grid_view: ^0.6.2
  expandable: ^5.0.1
  flutter_inappwebview: ^5.7.2+3
  flutter_html: ^3.0.0-alpha.3
  url_launcher: ^6.1.11
  bottom_navy_bar: ^6.0.0
  shimmer: ^3.0.0
  shimmer_animation: ^2.1.0+1
  speech_to_text: ^6.1.1
  avatar_glow: ^2.0.2
  flutter_share: ^2.0.0
  path_provider: ^2.0.15
  path: ^1.8.2
  html: ^0.15.4
  social_share: ^2.3.1
  cached_network_image: ^3.2.3
  carousel_slider: ^4.2.1
  carousel_indicator: ^1.0.6
  scrollable_positioned_list: ^0.3.8
  pull_to_refresh: ^2.0.0
  permission_handler: ^10.4.1
  responsive_framework: ^1.0.0
  dropdown_button2: ^2.0.0
  universal_html: ^2.0.9
  js: ^0.6.5
  responsive_grid_list: ^1.3.2
  flutter_cors: ^1.4.0
  device_info_plus: ^8.1.0
  flutter_downloader: ^1.10.2
  random_string: ^2.3.1
  flutter_secure_storage: ^8.0.0
  scrollview_observer: ^1.14.0
  flutter_pagewise: ^2.0.4
  connectivity_plus: ^4.0.1
  marquee: ^2.2.3
  numeral: ^2.0.1
  gradient_borders: ^1.0.0
  screen_protector: ^1.2.0
  flutter_launcher_icons: ^0.13.1
  change_app_package_name: ^1.1.0
  flutter_native_splash: ^2.3.2
  back_button_interceptor: ^7.0.0

dependency_overrides:
  webview_flutter_wkwebview: '3.5.0'

flutter_launcher_icons:
  android: "launcher_icon"
  ios: true
  image_path: "assets/images/launcher.png"

flutter_native_splash:
  image: assets/images/appicon.png
  color: "#0d0907"
  android_12:
    image: assets/images/appicon.png
    color: "#0d0907"


dev_dependencies:
  flutter_test:
    sdk: flutter

  # The "flutter_lints" package below contains a set of recommended lints to
  # encourage good coding practices. /The lint set provided by the package is
  # activated in the `analysis_options.yaml` file located at the root of your
  # package. See that file for information about deactivating specific lint
  # rules and activating additional ones.
  flutter_lints: ^2.0.0

# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec

# The following section is specific to Flutter packages.
flutter:
  assets: 
    - assets/
    - assets/images/
    - assets/locales/en.json
    - assets/locales/af.json
    - assets/locales/ar.json
    - assets/locales/de.json
    - assets/locales/es.json
    - assets/locales/fr.json
    - assets/locales/gu.json
    - assets/locales/hi.json
    - assets/locales/id.json
    - assets/locales/nl.json
    - assets/locales/pt.json
    - assets/locales/sq.json
    - assets/locales/tr.json
    - assets/locales/vi.json

  # The following line ensures that the Material Icons font is
  # included with your application, so that you can use the icons in
  # the material Icons class.
  uses-material-design: true

  # To add assets to your application, add an assets section, like this:
  # assets:
  #   - images/a_dot_burr.jpeg
  #   - images/a_dot_ham.jpeg

  # An image asset can refer to one or more resolution-specific "variants", see
  # https://flutter.dev/assets-and-images/#resolution-aware

  # For details regarding adding assets from package dependencies, see
  # https://flutter.dev/assets-and-images/#from-packages

  # To add custom fonts to your application, add a fonts section here,
  # in this "flutter" section. Each entry in this list should have a
  # "family" key with the font family name, and a "fonts" key with a
  # list giving the asset and other descriptors for the font. For
  # example:
  # fonts:
  #   - family: Schyler
  #     fonts:
  #       - asset: fonts/Schyler-Regular.ttf
  #       - asset: fonts/Schyler-Italic.ttf
  #         style: italic
  #   - family: Trajan Pro
  #     fonts:
  #       - asset: fonts/TrajanPro.ttf
  #       - asset: fonts/TrajanPro_Bold.ttf
  #         weight: 700
  #
  # For details regarding fonts from package dependencies,
  # see https://flutter.dev/custom-fonts/#from-packages

这是我在 Main.dart 文件中的材质应用程序实现


  @override
  Widget build(BuildContext context) {
    return Shortcuts(
      shortcuts: <LogicalKeySet, Intent>{
        LogicalKeySet(LogicalKeyboardKey.select): const ActivateIntent(),
        LogicalKeySet(LogicalKeyboardKey.enter): const ActivateIntent(),
      },
      child: LocaleBuilder(
        builder: (locale) => MaterialApp(
          // navigatorKey: navigatorKey,
          debugShowCheckedModeBanner: false,
          navigatorObservers: [routeObserver], //HERE
          theme: ThemeData(
            primaryColor: colorPrimary,
            primaryColorDark: colorPrimaryDark,
            primaryColorLight: primaryLight,
            scaffoldBackgroundColor: appBgColor,
          ).copyWith(
            scrollbarTheme: const ScrollbarThemeData().copyWith(
              thumbColor: MaterialStateProperty.all(white),
              trackVisibility: MaterialStateProperty.all(true),
              trackColor: MaterialStateProperty.all(whiteTransparent),
            ),
          ),
          title: Constant.appName,
          localizationsDelegates: Locales.delegates,
          supportedLocales: Locales.supportedLocales,
          locale: locale,
          localeResolutionCallback:
              (Locale? locale, Iterable<Locale> supportedLocales) {
            return locale;
          },
          builder: (context, child) {
            return ResponsiveBreakpoints.builder(
              child: child!,
              breakpoints: [
                const Breakpoint(start: 0, end: 360, name: MOBILE),
                const Breakpoint(start: 361, end: 800, name: TABLET),
                const Breakpoint(start: 801, end: 1000, name: DESKTOP),
                const Breakpoint(start: 1001, end: double.infinity, name: '4K'),
              ],
            );
          },
          home: BottomBar(),
          scrollBehavior: const MaterialScrollBehavior().copyWith(
            dragDevices: {
              PointerDeviceKind.mouse,
              PointerDeviceKind.touch,
              PointerDeviceKind.stylus,
              PointerDeviceKind.unknown,
              PointerDeviceKind.trackpad
            },
          ),
        ),
      ),
    );

final RouteObserver<ModalRoute<void>> routeObserver =
    RouteObserver<ModalRoute<void>>();
final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();


这是底部栏的代码

import 'package:back_button_interceptor/back_button_interceptor.dart';
import 'package:dtlive/pages/channels.dart';
import 'package:dtlive/pages/find.dart';
import 'package:dtlive/pages/home.dart';
import 'package:dtlive/pages/setting.dart';
import 'package:dtlive/pages/rentstore.dart';
import 'package:dtlive/provider/generalprovider.dart';
import 'package:dtlive/provider/profileprovider.dart';
import 'package:dtlive/utils/adhelper.dart';
import 'package:dtlive/utils/color.dart';
import 'package:dtlive/utils/constant.dart';
import 'package:dtlive/utils/sharedpre.dart';
import 'package:dtlive/utils/strings.dart';
import 'package:dtlive/utils/utils.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:provider/provider.dart';



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

  @override
  State<Bottombar> createState() => BottombarState();
}

class BottombarState extends State<Bottombar> {

  int selectedIndex = 0;
  DateTime? currentBackPressTime;

  static List<Widget> widgetOptions = <Widget>[
    const Home(
      pageName: "",
      key: Key("Home"),
    ),
    const Find(
      key: Key("Find"),
    ),
    const Channels(
      key: Key("Channels"),
    ),
    const RentStore(
      key: Key("Rent"),
    ),
    const Setting(
      key: Key("Settings"),
    ),
  ];

  @override
  void initState() {
    super.initState();
  }

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

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: onBackPressed,
      child: Scaffold(
        backgroundColor: Colors.white,
        resizeToAvoidBottomInset: false,
        body: IndexedStack(
          index: selectedIndex,
          children: widgetOptions,
        ),
        bottomNavigationBar: BottomAppBar(
          color: appBgColor,
          padding: const EdgeInsets.fromLTRB(3, 5, 3, 5),
          elevation: 5,
          child: BottomNavigationBar(
            backgroundColor: appBgColor,
            selectedLabelStyle: GoogleFonts.montserrat(
              fontSize: 10,
              fontStyle: FontStyle.normal,
              fontWeight: FontWeight.w500,
              color: colorPrimary,
            ),
            unselectedLabelStyle: GoogleFonts.montserrat(
              fontSize: 10,
              fontStyle: FontStyle.normal,
              fontWeight: FontWeight.w500,
              color: colorPrimary,
            ),
            selectedFontSize: 12,
            unselectedFontSize: 12,
            elevation: 5,
            currentIndex: selectedIndex,
            unselectedItemColor: gray,
            selectedItemColor: colorPrimary,
            type: BottomNavigationBarType.fixed,
            items: [
              BottomNavigationBarItem(
                backgroundColor: black,
                label: bottomView1,
                activeIcon: _buildBottomNavIcon(
                    iconName: 'ic_home', iconColor: colorPrimary),
                icon: _buildBottomNavIcon(iconName: 'ic_home', iconColor: gray),
              ),
              BottomNavigationBarItem(
                backgroundColor: black,
                label: bottomView2,
                activeIcon: _buildBottomNavIcon(
                    iconName: 'ic_find', iconColor: colorPrimary),
                icon: _buildBottomNavIcon(iconName: 'ic_find', iconColor: gray),
              ),
              BottomNavigationBarItem(
                backgroundColor: black,
                label: bottomView3,
                activeIcon: _buildBottomNavIcon(
                    iconName: 'ic_channels', iconColor: colorPrimary),
                icon: _buildBottomNavIcon(
                    iconName: 'ic_channels', iconColor: gray),
              ),
              BottomNavigationBarItem(
                backgroundColor: black,
                label: bottomView4,
                activeIcon: _buildBottomNavIcon(
                    iconName: 'ic_store', iconColor: colorPrimary),
                icon:
                    _buildBottomNavIcon(iconName: 'ic_store', iconColor: gray),
              ),
              BottomNavigationBarItem(
                backgroundColor: black,
                label: bottomView5,
                activeIcon: _buildBottomNavIcon(
                    iconName: 'ic_stuff', iconColor: colorPrimary),
                icon:
                    _buildBottomNavIcon(iconName: 'ic_stuff', iconColor: gray),
              ),
            ],
            onTap: _onItemTapped,
          ),
        ),
      ),
    );
  }

  Widget _buildBottomNavIcon(
      {required String iconName, required Color? iconColor}) {
    return Align(
      alignment: Alignment.center,
      child: Padding(
        padding: const EdgeInsets.all(7),
        child: Image.asset(
          "assets/images/$iconName.png",
          width: 22,
          height: 22,
          color: iconColor,
        ),
      ),
    );
  }

  Future<bool> onBackPressed() async {
    if (selectedIndex == 0) {
      DateTime now = DateTime.now();
      if (currentBackPressTime == null ||
          now.difference(currentBackPressTime!) > const Duration(seconds: 2)) {
        currentBackPressTime = now;
        Utils.showSnackbar(context, "", "exit_warning", true);
        return Future.value(false);
      }
      SystemNavigator.pop();
      return Future.value(true);
    } else {
      _onItemTapped(0);
      return Future.value(false);
    }
  }
}

我不知道,但在每个小部件上,应用程序的默认后按都会最小化应用程序。 它没有在任何页面中调用 WillPopScope 方法。

android flutter navigation back-button materialpageroute
1个回答
0
投票

每个小部件都可能与应用程序中处理导航堆栈的方式相关。您可以确保正确处理导航堆栈。这是一个如何做到这一点的示例 -

return WillPopScope(
  onWillPop: () async {
    // Implement your custom back button behavior here
    // Return true to allow popping the route, or false to prevent it.
    return true;
  },
  child: MaterialApp(
    // ... your MaterialApp configuration ...
  ),
);

通过使用 WillPopScope,您可以实现自定义逻辑来控制按下后退按钮时会发生什么。

© www.soinside.com 2019 - 2024. All rights reserved.