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

如何在点击事件中切换Flutter渲染的Widget?

解决Flutter点击返回按钮切换页面的问题

你的代码存在几个关键问题导致页面切换失效,按以下步骤修改即可实现需求:

  1. 添加状态变量跟踪当前页面
    在_MyAppState类里定义变量记录当前显示的页面,并在初始化时设置为首页:
late Widget currentPage;

@override
void initState() {
  super.initState();
  currentPage = _buildHomePage(); // 将首页布局抽为单独方法,便于维护
}
  1. 实现页面切换逻辑
    替换BackButton的onPressed占位代码,通过setState更新当前页面:
onPressed: () {
  setState(() {
    currentPage = const SecondPage();
  });
},
  1. 让MaterialApp根据状态渲染页面
    将MaterialApp的home属性改为currentPage,使其随状态变化更新UI:
home: currentPage,
  1. 修正类名规范
    Dart要求类名首字母大写,将secondPage改为SecondPage。

修改后的完整代码

import 'package:flutter/material.dart';

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

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  late Widget currentPage;

  @override
  void initState() {
    super.initState();
    currentPage = _buildHomePage();
  }

  Widget _buildHomePage() {
    return Scaffold(
      appBar: AppBar(
        leading: BackButton(
          onPressed: () {
            setState(() {
              currentPage = const SecondPage();
            });
          },
        ),
        centerTitle: true,
        title: const Text('demo'),
        backgroundColor: const Color.fromARGB(255, 77, 222, 255),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      child: MaterialApp(
        debugShowCheckedModeBanner: false,
        home: currentPage,
      ),
    );
  }
}

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

  @override
  Widget build(BuildContext context) {
    return const Scaffold(
      body: Center(
        child: Text('这是第二个页面'),
      ),
    );
  }
}

额外建议

如果是实际项目,更推荐使用Flutter自带的路由管理(Navigator)实现页面切换,这种方式更符合Flutter的页面栈设计逻辑。只需将BackButton的onPressed替换为以下代码即可,无需维护currentPage变量:

onPressed: () {
  Navigator.pushReplacement(
    context,
    MaterialPageRoute(builder: (context) => const SecondPage()),
  );
},

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 14:02:39