Flutter中Navigator无法切换页面问题求助
问题原因与修复方案
核心问题
你遇到的页面切换无响应问题,根源是重复嵌套MaterialApp导致导航上下文失效。main函数中已经创建了根MaterialApp,而MyApp的build方法里又嵌套了一层MaterialApp,此时调用Navigator.push使用的context属于MyApp,而非根MaterialApp的导航上下文,因此无法触发页面跳转,且不会抛出错误。
修复步骤
1. 移除重复的MaterialApp
修改主页面代码,删除MyApp中嵌套的MaterialApp,直接返回Scaffold组件:
import 'package:flutter/material.dart'; import 'package:testing/SecondPage.dart'; void main() { runApp(const MaterialApp( title: 'MyApp', home: MyApp(), )); } class MyApp extends StatefulWidget { const MyApp({Key? key}) : super(key: key); @override State<MyApp> createState() => _MyAppState(); } class _MyAppState extends State<MyApp> { @override Widget build(BuildContext context) { return DefaultTabController( length: 5, child: Scaffold( body: const Icon(Icons.rice_bowl, size: 100, color: Colors.blue), floatingActionButton: FloatingActionButton( hoverElevation: 50, onPressed: () {}, child: const Icon(Icons.mic), ), floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked, bottomNavigationBar: BottomAppBar( notchMargin: 10, shape: const CircularNotchedRectangle(), child: Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: [ IconButton( onPressed: () {}, icon: const Icon(Icons.contact_mail_outlined, color: Colors.grey), ), IconButton( onPressed: () {}, icon: const Icon(Icons.local_activity, color: Colors.grey), ), const SizedBox(width: 1), // 替换空Container为SizedBox,更符合规范 IconButton( onPressed: () { Navigator.push( context, MaterialPageRoute(builder: (context) => const secondPage()), ); }, icon: const Icon(Icons.safety_check, color: Colors.grey), ), IconButton( onPressed: () {}, icon: const Icon(Icons.read_more, color: Colors.grey), ), ], ), ), ), ); } }
2. 规范第二个页面的结构
将第二个页面的Container替换为Scaffold,确保页面拥有正确的Material上下文,避免渲染异常:
import 'package:flutter/material.dart'; class secondPage extends StatefulWidget { const secondPage({Key? key}) : super(key: key); @override State<secondPage> createState() => _secondPageState(); } class _secondPageState extends State<secondPage> { @override Widget build(BuildContext context) { return Scaffold( body: Center( child: Icon(Icons.rice_bowl, size: 200), ), ); } }
补充说明
Navigator组件依赖于MaterialApp提供的导航上下文,使用错误的context调用Navigator.push不会触发任何行为,也不会报错,这是你无法定位问题的关键。- 页面使用
Scaffold包裹是Flutter的标准页面结构,能确保导航栏、状态栏等组件正常工作。
内容的提问来源于stack exchange,提问作者exadur
相关产品推荐
相关产品推荐

