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

Flutter Windows应用WebViewWidget报错‘WebViewPlatform.instance != null’求助

解决Windows平台WebView实例化‘WebViewPlatform.instance != null’错误

问题根源

webview_flutter核心包仅提供跨平台通用接口,Windows平台没有内置WebView实现,必须额外添加对应平台的适配包才能正常使用。

解决步骤

  1. 添加Windows平台WebView依赖
    在项目的pubspec.yaml中添加webview_flutter_windows依赖,注意和webview_flutter版本保持兼容:

    dependencies:
      flutter:
        sdk: flutter
      webview_flutter: ^4.4.0 # 请根据实际使用版本调整
      webview_flutter_windows: ^0.3.0 # 对应webview_flutter的兼容版本
    

    执行flutter pub get拉取依赖包。

  2. 初始化Windows平台WebView
    在main()函数中加入Windows平台的初始化代码,仅在Windows编译时执行:

    if (defaultTargetPlatform == TargetPlatform.windows) {
      WebViewPlatform.instance = WebViewWindowsPlatform();
    }
    
  3. 清理缓存并重新运行
    执行flutter clean清除旧编译缓存,再运行flutter run -d windows启动Windows应用。

修改后的完整代码示例

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:webview_flutter_windows/webview_flutter_windows.dart';

void main() {
  if (defaultTargetPlatform == TargetPlatform.windows) {
    WebViewPlatform.instance = WebViewWindowsPlatform();
  }
  runApp(
    const MaterialApp(
      theme: ThemeData(useMaterial3: true),
      home: WebViewApp(),
    ),
  );
}

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

  @override
  State<WebViewApp> createState() => _WebViewAppState();
}

class _WebViewAppState extends State<WebViewApp> {
  late final WebViewController controller;

  @override
  void initState() {
    super.initState();
    controller = WebViewController()
      ..loadRequest(
        Uri.parse('https://flutter.dev'),
      );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Flutter WebView'),
      ),
      body: WebViewWidget(
        controller: controller,
      ),
    );
  }
}

注意事项

  • 版本匹配:务必保证webview_flutter和webview_flutter_windows的版本兼容,可查看pub.dev上的包说明确认对应版本。
  • 仅Windows初始化:通过defaultTargetPlatform判断平台,避免影响Android等其他平台的正常运行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 05:33:17