You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中Android系统返回键直接退出应用而非返回上页问题求助

解决Flutter GoRouter下Android返回键直接退出应用的问题

检查路由跳转方式

GoRouter的go()方法会替换整个路由栈,这是导致返回键直接退出的常见原因。从设置页跳转到支付设置页时,必须使用push()方法将页面添加到现有路由栈中:

// 正确跳转方式
context.push('/payment-settings');

// 错误跳转方式(会清空路由栈)
// context.go('/payment-settings');

自定义返回键行为(Flutter 3.14+)

使用PopScope组件手动控制返回逻辑,确保返回操作回到上一页而非退出应用:

class PaymentSettingsPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return PopScope(
      canPop: true,
      onPopInvoked: (bool didPop) {
        if (!didPop) {
          context.pop();
        }
      },
      child: Scaffold(
        appBar: AppBar(title: const Text('支付设置')),
        // 页面内容
      ),
    );
  }
}

若使用低于3.14的Flutter版本,替换为WillPopScope:

class PaymentSettingsPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        return true;
      },
      child: Scaffold(
        appBar: AppBar(title: const Text('支付设置')),
        // 页面内容
      ),
    );
  }
}

修正路由配置

确保路由采用嵌套结构,让支付设置页作为设置页的子路由存在,这样路由栈会自动保留父页面:

final GoRouter _router = GoRouter(
  initialLocation: '/settings',
  routes: [
    GoRoute(
      path: '/settings',
      builder: (context, state) => const SettingsPage(),
      // 定义嵌套子路由
      routes: [
        GoRoute(
          path: 'payment-settings',
          builder: (context, state) => const PaymentSettingsPage(),
        ),
      ],
    ),
  ],
  // 避免错误的redirect逻辑清空路由栈
  redirect: (context, state) => null,
);

跳转时使用完整的嵌套路由路径:context.push('/settings/payment-settings')

验证路由栈状态

在支付设置页中打印当前路由栈,确认页面是否正确加入栈中:

// 在PaymentSettingsPage的build方法中添加
print('当前路由栈: ${GoRouter.of(context).routerDelegate.currentConfiguration}');

若栈中仅存在支付设置页,说明跳转方式错误,需调整为push()或嵌套路由跳转。


内容的提问来源于stack exchange,提问作者Jena.T

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 14:07:06