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

Flutter页面跳转报错:'Null'不是'BuildContext'的子类型

错误原因分析

这个错误的核心问题是传递给wallpapersList函数的context参数为null,导致调用Navigator.push时使用了无效的空值,而Navigator必须依赖有效的BuildContext才能完成页面跳转。

看你定义的wallpapersList函数:

Widget wallpapersList({required List<WallpaperModel> wallpapers, context}) {

这里的context参数既没有标记为必填,也没有指定BuildContext类型,这意味着调用该函数时可以不传上下文,或者传入null值。你实际调用时应该就是没传递有效的BuildContext,才会触发这个类型转换错误。

修复方案

1. 修正参数定义

修改wallpapersList的参数,把context标记为必填并指定类型:

Widget wallpapersList({required List<WallpaperModel> wallpapers, required BuildContext context}) {

这样编译器会强制要求你调用时必须传递有效的上下文,从根源避免null的情况。

2. 确保调用时传递有效上下文

检查调用wallpapersList的位置,确保传递当前widget的context,比如在某个组件的build方法里:

@override
Widget build(BuildContext context) {
  return wallpapersList(wallpapers: yourWallpapersData, context: context);
}
额外优化建议

可以把wallpapersList改成独立的StatelessWidget,这样内部能直接获取上下文,无需手动传递参数,更符合Flutter组件设计规范:

class WallpapersList extends StatelessWidget {
  final List<WallpaperModel> wallpapers;

  const WallpapersList({super.key, required this.wallpapers});

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16),
      child: GridView.count(
        shrinkWrap: true,
        physics: ClampingScrollPhysics(),
        crossAxisCount: 2,
        childAspectRatio: 0.6,
        mainAxisSpacing: 6.0,
        crossAxisSpacing: 6.0,
        children: wallpapers.map((wallpaper) {
          return GridTile(
              child: GestureDetector(
            onTap: () {
              print(wallpaper.src!.portrait);
              Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) => ImageView(wallpaper.src!.portrait),
                  ));
            },
            child: Hero(
              tag: wallpaper.src?.portrait ??
                  "https://www.pexels.com/photo/brown-grass-field-near-body-of-water-under-white-clouds-14491698/",
              child: Container(
                child: ClipRRect(
                  borderRadius: BorderRadius.circular(16),
                  child: Image.network(
                    wallpaper.src?.portrait ??
                        "https://www.pexels.com/photo/brown-grass-field-near-body-of-water-under-white-clouds-14491698/",
                    fit: BoxFit.cover,
                  ),
                ),
              ),
            ),
          ));
        }).toList(),
      ),
    );
  }
}

调用时只需传入壁纸数据:

WallpapersList(wallpapers: yourWallpapersData)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 13:00:46