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

Flutter新手求助:点击ElevatedButton无法加载WebView页面

解决方案:点击ElevatedButton后WebView未加载的问题

问题根源

你的WebViewApp类中包含了独立应用的main函数,这会导致组件结构异常,无法作为普通页面被Navigator正确加载。同时需确保已正确安装webview_flutter依赖。

修改步骤

  1. 移除WebViewApp中的main函数
    WebViewApp是页面组件,不需要独立的应用入口,删除文件中的main函数即可。

  2. 修改后的WebViewApp代码

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

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()
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..loadRequest(
        Uri.parse('https://www.instagram.com'),
      );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Flutter WebView'),
      ),
      body: WebViewWidget(
        controller: controller,
      ),
    );
  }
}
  1. 调整Navigator跳转逻辑(可选)
    如果需要保留原页面的返回功能,将pushReplacement替换为push:
ElevatedButton(
  onPressed: (){
    Navigator.of(context).push(MaterialPageRoute(builder: (context)=> WebViewApp()));
  },
  style: ElevatedButton.styleFrom(
    backgroundColor: Colors.yellow,
  ),
  child: const Text(
    'Entrar em Contato',
    style: TextStyle(fontSize: 15, color: Colors.black),
  ),
),
  1. 确认依赖安装
    检查pubspec.yaml中是否添加了webview_flutter依赖,执行flutter pub get完成安装:
dependencies:
  flutter:
    sdk: flutter
  webview_flutter: ^4.4.0 # 使用最新稳定版本

完成以上操作后,点击按钮即可正常加载WebView页面。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 11:32:49