flutter AppBar中的自定义BackButton即使在屏幕无法弹出时也会显示

tyky79it  于 2023-05-23  发布在  Flutter
关注(0)|答案(1)|浏览(156)

我遇到了一个问题,添加一个自定义的后退引导按钮到AppBar。添加按钮是容易的部分,但当我添加它时,它一直显示。不管是否有一个屏幕可以返回,它显示自定义的返回按钮。
AppBar的默认后退按钮不会出现此问题。
我添加了这个逻辑,以检查当前屏幕是否可以弹出,以决定是否应该显示按钮。由于我使用persistent_bottom_nav_bar作为底部栏导航,使用Get作为路由,因此必须检查这两个导航器。

AppBar(
       backgroundColor: Colors.transparent,
       automaticallyImplyLeading: true,
       toolbarHeight: 70.0,
       elevation: 0.0,
       leading:
         Navigator.canPop(context) || Get.key.currentState!.canPop() ? ClipOval(
              child: Material(
                color: Theme.of(context).primaryColor,
                child: InkWell(
                  // Splash color
                  onTap: () {
                    if (Navigator.canPop(context)) {
                      Navigator.pop(context);
                    } else if (Get.key.currentState!.canPop()) {
                      // if (isBackControl) {
                      Get.back();
                      // }
                    }
                  },
                  child: const SizedBox(
                      width: 40,
                      height: 40,
                      child: Icon(
                        Icons.arrow_back_ios_new_outlined,
                        color: Colors.white,
                        size: 25.0,
                      )),
                ),
              ),
            ): SizedBox(),
    )

这个技术很好,但我遇到了一个奇怪的问题。
如果我在底部导航页面上有一个屏幕Screen A,我希望它不会显示后退按钮,它的工作和预期的一样,但是当我从另一个屏幕Screen B按下相同的Screen A,然后导航回到绑定到底部导航的Screen A时,它开始显示后退按钮。
你可以通过这个了解我的应用程序中的路由。

Persistent Bottom Navigation Bar

Screen A (No Back Button)✅
Screen B (No Back Button)✅
Screen C (No Back Button)✅

Pushing another instance of Screen A from Screen B,

Pushed Screen A (Shows Back Button)✅

Then navigate back to Screen B and then to Screen A using the bottom navigation.

Persistent Bottom Navigation Bar

Screen A (Shows Back Button)❌
Screen B (No Back Button)✅
Screen C (No Back Button)✅

意外行为
预期行为
我无法追踪这个问题的原因,所以我决定使用默认的后退按钮,但我想定义一个自定义后退按钮,同时保持它的可选性,我正在努力使它工作。

scyqe7ek

scyqe7ek1#

在单独的dart文件中创建全局导航键。
my_navigator.dart

import 'package:flutter/material.dart';

class MyNavigator {
  static GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();
}

将globalkey设置为GetMaterialApp的默认导航键
main.dart

import 'my_navigator.dart';
...
  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      navigatorKey: MyNavigator.navigatorKey,
      ...
    );
  }

现在在您的AppBar中,使用
MyNavigator.navigatorKey.currentState!.canPop()
而不是
Navigator.canPop(context)

相关问题