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

Flutter中Navigator.push跳转失效求助:无法从页面B跳转到C

问题描述

这段代码在DartPad中无法正常工作,我通常用命名路由结合Navigator的push/pop方法实现多次跳转,但这次仅能成功从A页面跳转到B页面,之后点击B页面的跳转按钮无法进入C页面,路由功能完全失效。

import 'package:flutter/material.dart';

void main() {
  runApp(MaterialApp(
      // onGenerateRoute: TestRouter.generateRoute,
      home:A()));
}


class A extends StatefulWidget {
  const A({ super.key });
  State createState() => AState();
}
class AState extends State {
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text("A"),
        ),
        body:
    ListView(children: [
      GestureDetector(
        onTap: (){
          Navigator.push(context, MaterialPageRoute(builder: (context){
            return B();
          },
          ));
        },
      child:Container(
        color: Colors.blue,
        height: 100, width: 100, child: Center(child:Text("B")),)),
    ],)
    );
  }
}


class B extends StatefulWidget {
  const B({ super.key });
  State createState() => BState();
}
class BState extends State {
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text("B"),
        ),
        body:
    ListView(children: [
      GestureDetector(
          onTap: (){
            Navigator.push(context, MaterialPageRoute(builder: (context){
              return C();
            }));
          },
          child:Container(
            color: Colors.red,
            height: 100, width: 100, child: Center(child:Text("C")),)),
    ],)
    );
  }
}


class C extends StatefulWidget {
  const C({ super.key });
  State createState() => BState();
}
class CState extends State {
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text("C"),
        ),
        body:
        ListView(children: [
          GestureDetector(
              onTap: (){
                Navigator.push(context, MaterialPageRoute(builder: (context){
                  return A();
                }));
              },
              child:Container(
                color: Colors.green,
                height: 100, width: 100, child: Center(child:Text("A")),)),
        ],)
    );
  }
}
问题修复

问题出在C组件的createState方法中,你错误地返回了BState(),而非对应的CState()。这种状态类与组件不匹配的错误,会导致Flutter无法正确初始化C页面,进而引发路由跳转失败。

只需要修改C组件的createState方法即可:

class C extends StatefulWidget {
  const C({ super.key });
  State createState() => CState(); // 将返回值改为CState
}

另外建议给所有State类添加泛型约束,比如class AState extends State<A>、class BState extends State<B>、class CState extends State<C>,这样编辑器能提前检测到类型不匹配的问题,避免同类错误再次发生。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 10:37:32