Flutter无网络时跳转新页面遇到报错如何解决
报错根因
lib/main.dart:5:8: Error: Not found: 'dart:js':dart:js是Flutter Web专属的JS互操作库,移动端、桌面端环境不存在该库,属于代码里的多余导入,直接删除即可。The argument type 'Context' can't be assigned to the parameter type 'BuildContext':你传入Navigator.of()的context是path依赖包提供的路径操作类Context,不是Flutter导航所需的控件上下文BuildContext,本质是当前监听逻辑的位置拿不到合法的控件上下文,直接调用导航必然报错。
修复方案
- 删除
main.dart顶部无用的import 'dart:js';语句,解决第一个编译报错。 - 不要依赖零散的局部context做全局网络状态触发的导航,使用全局导航Key实现无context跳转,避免上下文不合法问题,同时加防重复跳转逻辑,避免网络波动时重复压入页面:
第一步,在main.dart顶层定义全局导航Key:
第二步,在根import 'package:flutter/material.dart'; final GlobalKey<NavigatorState> rootNavigatorKey = GlobalKey<NavigatorState>();MaterialApp上绑定该Key:
第三步,修改网络监听逻辑,把监听放在void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( navigatorKey: rootNavigatorKey, // 保留你原有的路由、主题、初始页配置 initialRoute: '/', routes: { '/': (context) => const HomePage(), '/downloads': (context) => const DownloadsPage(), }, ); } }initState生命周期中注册,页面销毁时取消监听避免内存泄漏,同时通过全局Key获取导航实例做跳转:import 'dart:async'; import 'package:internet_connection_checker/internet_connection_checker.dart'; class HomePage extends StatefulWidget { const HomePage({super.key}); @override State<HomePage> createState() => _HomePageState(); } class _HomePageState extends State<HomePage> { StreamSubscription<InternetConnectionStatus>? _connectionSub; bool _isOnDownloadPage = false; @override void initState() { super.initState(); InternetConnectionChecker().checkInterval = const Duration(seconds: 10); _connectionSub = InternetConnectionChecker().onStatusChange.listen((status) { switch (status) { case InternetConnectionStatus.connected: print('Data connection is available.'); // 联网后如果当前在下载页,自动返回 if (_isOnDownloadPage) { rootNavigatorKey.currentState?.pop(); _isOnDownloadPage = false; } break; case InternetConnectionStatus.disconnected: // 已经在下载页时不重复跳转 if (_isOnDownloadPage) return; _isOnDownloadPage = true; rootNavigatorKey.currentState?.pushNamed('/downloads'); break; } }); } @override void dispose() { _connectionSub?.cancel(); super.dispose(); } @override Widget build(BuildContext context) { // 你的原有页面布局 return Scaffold(); } }
注意事项
- 不要把网络监听注册逻辑写在
build方法里,否则每次页面重绘都会重复注册监听,导致多次触发跳转、内存泄漏问题。 - 如果你的应用确实是Flutter Web项目,才需要保留
dart:js导入,纯移动端/桌面端项目不需要该依赖。
内容的提问来源于stack exchange,提问作者Techno Hub
相关产品推荐
相关产品推荐

