如何通过自定义AppBar返回按钮实现PageView页面导航?
实现PageView内的返回导航
要让AppBar的返回按钮控制PageView回退到上一页,核心是让父组件能调用子组件(Body)里的PageController相关逻辑,具体修改如下:
1. 修改body.dart,添加回退方法
给Body组件添加全局key并暴露回退方法,同时在其State中实现具体的回退逻辑:
class Body extends StatefulWidget { const Body({Key? key}) : super(key: key); final GlobalKey<_BodyState> _key = GlobalKey<_BodyState>(); // 暴露给父组件调用的回退方法 void goBack() { _key.currentState?.handleBackNavigation(); } @override _BodyState createState() => _BodyState(); } class _BodyState extends State<Body> { int currentPage = 0; final PageController controller = PageController(); @override void dispose() { controller.dispose(); super.dispose(); } // 处理回退逻辑 void handleBackNavigation() { if (currentPage > 0) { // 平滑滚动到上一页 controller.previousPage( duration: const Duration(milliseconds: 300), curve: Curves.easeInOut, ); } else { // 已是第一页,退出当前页面 Navigator.pop(context); } } @override Widget build(BuildContext context) { final List<Widget> formPages = <Widget>[ ExampleContent01(controller: controller), ExampleContent02(controller: controller), ExampleContent03(controller: controller), ExampleContent04(controller: controller), ]; return SafeArea( child: SizedBox( child: Column( children: [ const SizedBox(height: 6), AppStepper( currentPage: currentPage, length: formPages.length, noSkip: true, ), Expanded( child: Padding( padding: EdgeInsets.symmetric( horizontal: getProportionateScreenWidth(20), ), child: PageView( controller: controller, onPageChanged: (value) => setState(() => currentPage = value), children: formPages, ), ), ), ], ), ), ); } }
2. 修改screen1.dart,绑定返回按钮事件
在父组件中创建Body实例,点击返回按钮时调用其暴露的回退方法:
import 'package:app/src/features/examples/components/body.dart'; class OnboardingExampleFlowPage extends StatelessWidget { static String routeName = "/onboarding_example_flow"; const OnboardingExampleFlowPage({Key? key}) : super(key: key); final Body _body = const Body(); @override Widget build(BuildContext context) { return Scaffold( resizeToAvoidBottomInset: false, extendBodyBehindAppBar: true, appBar: AppBar( elevation: 1, backgroundColor: AppColors.monochromeWhite, title: Text(context.l10n.buttonBack), leading: IconButton( icon: const Icon(Icons.arrow_back), onPressed: () => _body.goBack(), // 触发回退逻辑 ), ), body: _body, ); } }
逻辑说明
- 当当前页面索引
currentPage > 0时,调用PageController.previousPage实现平滑回退到上一页,onPageChanged会自动更新currentPage的值。 - 当处于第一页(
currentPage == 0)时,执行Navigator.pop(context)退出当前路由页面,符合常规返回逻辑。
内容的提问来源于stack exchange,提问作者user18315843
相关产品推荐
相关产品推荐

