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

Flutter中Expanded包裹InAppWebView报空值检查错误求助

解决方案

1. 解决「Null check operator used on a null value」错误

这个问题大概率是你直接用!强制解包了未初始化的InAppWebViewController。处理方式如下:

  • 避免使用非空断言!,改用可空类型或延迟初始化:
    // 方式1:延迟初始化
    late final InAppWebViewController webViewController;
    
    @override
    void initState() {
      super.initState();
      // 也可在onWebViewCreated回调中完成赋值
    }
    
    // 方式2:可空类型
    InAppWebViewController? webViewController;
    
  • 通过InAppWebView的onWebViewCreated回调确保控制器就绪后再执行相关操作:
    InAppWebView(
      initialUrlRequest: URLRequest(url: Uri.parse("https://example.com")),
      onWebViewCreated: (controller) {
        webViewController = controller;
        // 在这里执行需要控制器的逻辑,比如注入JS代码
      },
    )
    

2. 解决移除Expanded后应用崩溃的问题

崩溃核心原因是InAppWebView没有明确的高度约束,Flutter无法计算其布局尺寸。你需要给它指定高度:

  • 用Container包裹并设置固定高度(或按屏幕比例适配):
    Container(
      height: MediaQuery.of(context).size.height * 0.7, // 占屏幕70%高度
      child: InAppWebView(
        initialUrlRequest: URLRequest(url: Uri.parse("https://example.com")),
      ),
    )
    
  • 如果是在ListView.builder的列表项中使用,必须确保该item有确定高度,否则列表无法正常滚动:
    ListView.builder(
      itemCount: 10,
      itemBuilder: (context, index) {
        if (index == 2) { // 假设第3个列表项展示网页
          return Container(
            height: 400,
            child: InAppWebView(
              initialUrlRequest: URLRequest(url: Uri.parse("https://example.com")),
            ),
          );
        }
        return ListTile(title: Text("列表项 $index"));
      },
    )
    

3. NestedScrollView中完整嵌套示例

结合你的需求,完整布局结构参考:

NestedScrollView(
  headerSliverBuilder: (context, innerBoxIsScrolled) {
    return [
      SliverAppBar(
        title: const Text("我的页面"),
        floating: true,
        snap: true,
      ),
    ];
  },
  body: ListView.builder(
    itemCount: 10,
    itemBuilder: (context, index) {
      if (index == 2) {
        return Container(
          height: MediaQuery.of(context).size.height * 0.6,
          child: InAppWebView(
            initialUrlRequest: URLRequest(url: Uri.parse("https://example.com")),
            onWebViewCreated: (controller) {
              // 初始化控制器逻辑
            },
          ),
        );
      }
      return ListTile(title: Text("列表项 $index"));
    },
  ),
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 08:52:50