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

Flutter按钮点击可检测但页面不切换的问题排查

Flutter页面切换失败问题修复

点击按钮能触发点击事件,但页面就是不切换?给你揪出代码里的两个关键问题:

问题根源

  • 错误1:Context层级错误
    你把MaterialApp放在了MyHomePage的build方法里,而调用Navigator.pushNamed(context, '/secondPage')时用的是MyHomePage的context——这个context在MaterialApp的层级之外,根本找不到导航器实例,自然没法跳转页面。

  • 错误2:路由配置不匹配
    你设置了initialRoute: '/',但routes里没有'/'对应的页面,只有'/first'指向MyHomePage,这会导致路由初始化逻辑混乱。

修正后的完整代码

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

// 将MaterialApp抽为独立根组件
class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter layout demo',
      theme: ThemeData(
        primarySwatch: Colors.grey,
        scaffoldBackgroundColor: Colors.white24,
      ),
      // 初始化路由与路由表匹配
      initialRoute: '/',
      routes: {
        '/': (context) => const MyHomePage(),
        '/secondPage': (context) => const SecondPage(),
      },
    );
  }
}

class MyHomePage extends StatelessWidget {
  const MyHomePage({super.key});
  @override
  Widget build(BuildContext context) {
    Widget titleSection = Container(
      padding: const EdgeInsets.all(32),
      child: Row(
        children: [
          Expanded(
            child: Column(
              children: [
                Container(
                  padding: const EdgeInsets.only(bottom: 8),
                  child: const Text(
                    'blabla',
                    style: TextStyle(
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),
                Text(
                  'Sous texte',
                  style: TextStyle(
                    color: Colors.green[500],
                  ),
                ),
              ],
            ),
          ),
          Icon(
            Icons.square_foot,
            color: Colors.yellow[500],
            size: 10,
          ),
          const Text('30°C'),
        ],
      ),
    );

    Column _buildButtonColumn(Color color, IconData icon, String label) {
      return Column(
        mainAxisSize: MainAxisSize.min,
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(icon, color: Colors.blue),
          Container(
            margin: const EdgeInsets.only(top: 8),
            child: Text(label,
                style: TextStyle(
                  fontSize: 12,
                  fontWeight: FontWeight.w600,
                  color: color,
                )),
          )
        ],
      );
    }

    Color color = Theme.of(context).primaryColor;
    Widget buttonSection = Row(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      children: [
        _buildButtonColumn(color, Icons.dialpad_sharp, 'dialpad sharp'),
        _buildButtonColumn(color, Icons.airplanemode_on_rounded, 'airplane'),
        _buildButtonColumn(color, Icons.assistant_photo_rounded, 'assistant'),
      ],
    );

    Widget textSection = const Padding(
      padding: EdgeInsets.all(32),
      child: Text(
        'Lake Oeschinen lies at the foot of the Blüemlisalp in the Bernese '
        'Alps. Situated 1,578 meters above sea level, it is one of the '
        'larger Alpine Lakes. A gondola ride from Kandersteg, followed by a '
        'half-hour walk through pastures and pine forest, leads you to the '
        'lake, which warms to 20 degrees Celsius in the summer. Activities '
        'enjoyed here include rowing, and riding the summer toboggan run.',
        softWrap: true,
      ),
    );

    Widget secondSection = Container(
      padding: const EdgeInsets.all(32),
      child: Column(
        children: [
          Container(
            padding: const EdgeInsets.all(38),
            child: const Text(
              'texte ea inséré la',
              style: TextStyle(
                color: Colors.lightBlueAccent,
                fontSize: 10,
                fontStyle: FontStyle.italic,
                decoration: TextDecoration.underline,
              ),
            ),
          ),
          Text(
            'hehehehehehe',
            style: TextStyle(
              color: Colors.yellowAccent,
            ),
          ),
        ],
      ),
    );

    Widget button = Container(
      child: ElevatedButton(
        onPressed: () {
          // 当前context属于MaterialApp子树,可正确调用导航器
          Navigator.pushNamed(context, '/secondPage');
        },
        child: const Text('Launch screen'),
      ),
    );

    return Scaffold(
      body: ListView(
        children: [
          titleSection,
          Image.asset(
            'images/lake.jpg',
            width: 600,
            height: 230,
            fit: BoxFit.cover,
          ),
          buttonSection,
          textSection,
          Image.asset(
            'images/lala.jpg',
            width: 200,
            height: 200,
            fit: BoxFit.cover,
          ),
          secondSection,
          button
        ],
      ),
    );
  }
}

class SecondPage extends StatelessWidget {
  const SecondPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('secondPage'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            Navigator.pop(context);
          },
          child: const Text('Go back!'),
        ),
      ),
    );
  }
}

核心修改说明

  1. 新增MyApp作为根组件,将MaterialApp移至此处,确保所有页面都处于导航器的管辖范围内。
  2. 修正路由配置,让initialRoute: '/'与路由表中的'/'对应MyHomePage保持一致。
  3. MyHomePage现在仅返回页面内容(Scaffold),调用Navigator时使用的context属于MaterialApp子树,能正确找到导航器实例。

内容的提问来源于stack exchange,提问作者Liffy

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 13:50:20