我有一个 webView 页面的代码,我想创建一个代码,在其中我在 appBar 的输入中输入一些内容,当我单击搜索图标时,它会重定向到该 url,但由于某种原因,loadRequest 方法不起作用它没有显示任何错误,这是我的代码
import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';
import '../components/bottom_navbar.dart';
class WebViewContainer extends StatelessWidget {
final TextEditingController _searchController = TextEditingController();
get controller => WebViewController()
..setJavaScriptMode(JavaScriptMode.unrestricted)
..setBackgroundColor(const Color(0x00000000))
..setNavigationDelegate(
NavigationDelegate(
onProgress: (int progress) {
// Update loading bar.
},
onPageStarted: (String url) {},
onPageFinished: (String url) {},
onWebResourceError: (WebResourceError error) {},
onNavigationRequest: (NavigationRequest request) {
return NavigationDecision.navigate;
},
),
)
..loadRequest(Uri.parse('https://www.google.com'));
onSearch() {
// Get the text from the search input.
String url = _searchController.text;
// Check if the URL has a scheme, and if not, prepend "https://".
if (!url.startsWith('http://') && !url.startsWith('https://')) {
url = 'https://' + url;
}
WebViewController().loadRequest(Uri.parse(url));
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: const Color(0xFF0f3443),
actions: [
PopupMenuButton(
itemBuilder: (context) {
return [
const PopupMenuItem(child: Text("Settings")),
const PopupMenuItem(child: Text("profile")),
const PopupMenuItem(child: Text('Log Out')),
];
},
)
],
automaticallyImplyLeading: false,
// The search area here
title: Container(
width: double.infinity,
height: 40,
decoration: BoxDecoration(
color: Colors.white, borderRadius: BorderRadius.circular(5)),
child: Center(
child: TextField(
controller: _searchController,
decoration: InputDecoration(
prefixIcon: IconButton(
icon: const Icon(Icons.search),
onPressed: onSearch,
),
suffixIcon: IconButton(
icon: const Icon(Icons.clear),
onPressed: () {
/* Clear the search field */
},
),
hintText: 'Search...',
border: InputBorder.none,
contentPadding: const EdgeInsets.symmetric(vertical: 13.5)),
),
),
)),
body: WebViewWidget(controller: controller),
bottomNavigationBar: const BottomNavigationBarExample(),
);
}
}
我希望如果我在搜索输入中输入 google,我的网络视图会带我去 google
每次尝试访问或修改 WebView 时,都会创建一个新的 WebViewController。您需要引用附加到 WebView 小部件的同一 WebViewController 实例。
创建一个
WebViewController
实例变量。
WebViewController? _webViewController;
将创建的控制器分配给
onWebViewCreated
回调。
WebView(
onWebViewCreated: (WebViewController controller) {
_webViewController = controller;
},
);
修改您的
onSearch
以使用 WebViewController instance
void _onSearch() {
String url = _searchController.text;
if (!url.startsWith('http://') && !url.startsWith('https://')) {
url = 'https://' + url;
}
_webViewController?.loadUrl(url);
}