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

Flutter页面跳转报错:BottomToTopPageRoute无法赋值给Widget类型参数

解决Flutter页面跳转从下到上动画的类型不匹配问题

问题场景

需要实现从页面A跳转到页面B,且页面B以从下到上的动画效果展示,但出现类型不匹配错误:

参数类型‘BottomToTopPageRoute’无法赋值给参数类型‘Widget?’

错误原因

原代码中,_createInvoiceScreenRoute方法返回MaterialPageRoute,并在其builder里将BottomToTopPageRoute作为BlocProvider的child。但BottomToTopPageRoute是PageRouteBuilder的子类(属于Route类型),而builder要求返回Widget类型,导致类型不匹配。

修正方案

直接将BottomToTopPageRoute作为路由返回,无需嵌套MaterialPageRoute,同时在BottomToTopPageRoute的page参数中传入包含BlocProvider的Widget树。

修正后的代码

页面A

Navigator.pushNamed(context, InvoiceRoutes.createInvoiceScreen);

(注:原代码中InvoiceRoutes.createInvoiceScreen.dart是错误写法,常量定义的是"/createInvoiceScreen",直接使用InvoiceRoutes.createInvoiceScreen即可)

InvoiceRoutes

class InvoiceRoutes {
  
  static const createInvoiceScreen = "/createInvoiceScreen";
    
  static Route<dynamic> _createInvoiceScreenRoute() {
    return BottomToTopPageRoute(
      page: BlocProvider(
        create: (_) => sl<OwnerInvoiceListCubit>(),
        child: PageB(),
      ),
    );
  }

  Route<dynamic>? getRoutes(RouteSettings settings) {
    if (settings.name == createInvoiceScreen) {
      return _createInvoiceScreenRoute();
    }

    return null;
  }
}

BottomToTopPageRoute(保持不变)

import 'package:flutter/material.dart';

class BottomToTopPageRoute<T> extends PageRouteBuilder<T> {
  final Widget page;

  BottomToTopPageRoute({required this.page})
      : super(
          pageBuilder: (context, animation, secondaryAnimation) => page,
          transitionsBuilder: (context, animation, secondaryAnimation, child) {
            const begin = Offset(0.0, 1.0);
            const end = Offset.zero;
            const curve = Curves.fastOutSlowIn;

            var tween =
                Tween(begin: begin, end: end).chain(CurveTween(curve: curve));
            var offsetAnimation = animation.drive(tween);

            return SlideTransition(
              position: offsetAnimation,
              child: child,
            );
          },
        );
}

说明

修正后,路由直接返回自定义的BottomToTopPageRoute,其page参数接收包含BlocProvider和PageB的Widget,既满足了路由类型要求,又实现了从下到上的滑动动画效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 13:21:30