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

Flutter InAppWebView点击刷新按钮报错:_webViewController未初始化

解决Flutter中点击刷新按钮提示“_webViewController has not been initialized.”的问题

问题原因

  • 初始状态下_webViewVisible为false,页面body显示的是Container,InAppWebView并未被渲染到界面上,导致onWebViewCreated回调不会执行,_webViewController始终未完成初始化。
  • 点击刷新按钮调用updateWebView时,直接访问未初始化的_webViewController,触发错误。

解决方案

通过调整界面渲染逻辑,确保InAppWebView能被提前创建并触发初始化回调,同时在使用控制器前增加空判断,避免直接访问未初始化的对象。

修改后的代码

import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      home: MyHomePage(),
    );
  }
}

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

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  // 改为可空类型,避免late修饰符的未初始化风险
  InAppWebViewController? _webViewController;
  late InAppWebView _webView;
  bool _webViewVisible = false;

  @override
  void initState() {
    super.initState();
    _webView = _buildWebView();
  }

  InAppWebView _buildWebView() {
    return InAppWebView(
      initialUrlRequest: URLRequest(url: Uri.parse("https://example.com")),
      onWebViewCreated: (controller) {
        print("WebView created");
        _webViewController = controller;
      },
    );
  }

  void updateWebView() {
    // 使用前先检查控制器是否已初始化
    if (_webViewController != null) {
      _webViewController!.loadUrl(
          urlRequest: URLRequest(url: Uri.parse("https://example.com/new-url")));
    }
    setState(() {
      _webViewVisible = true;
    });
  }

  @override
  Widget build(BuildContext context) {
    print("Building widget tree");
    return Scaffold(
      appBar: AppBar(
        title: const Text('InAppWebView Example'),
      ),
      // 用Visibility组件隐藏WebView,而非直接替换成Container,确保WebView始终被创建
      body: Visibility(
        visible: _webViewVisible,
        child: _webView,
        replacement: const Center(child: Text("点击刷新加载页面")),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: updateWebView,
        child: const Icon(Icons.refresh),
      ),
    );
  }
}

关键修改点

  1. 将_webViewController改为可空类型,避免late修饰符导致的未初始化访问错误。
  2. 使用Visibility组件替代条件渲染,确保InAppWebView始终被创建并触发onWebViewCreated回调,完成控制器初始化。
  3. 在updateWebView方法中增加空判断,确保只有控制器初始化完成后才执行加载操作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 20:00:15