我开始接触flutter,并且对“WebView”很感兴趣。如何使用小部件“ElevatedButton”打开“WebView”?
** 带有“ElevatedButton”的小部件**
ElevatedButton(
onPressed: () {
print('Pressed');
},
//onPressed: WebViewScreen(),
style: ElevatedButton.styleFrom(
backgroundColor: Colors.yellow, // Background color
),
child: const Text(
'Entrar em Contato',
style: TextStyle(fontSize: 15, color: Colors.black),
),
)
我创建了一个具有以下功能的 webview 类:打开、后退、下一页。
WebView类:
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
class WebViewScreen extends StatefulWidget {
const WebViewScreen ({Key? key}) : super(key: key);
@override
State<WebViewScreen> createState() => _WebViewScreen ();
}
class _WebViewScreen extends State<WebViewScreen> {
double _progress = 0;
late InAppWebViewController inAppWebViewController;
@override
Widget build(BuildContext context) {
return WillPopScope(
onWillPop: ()async{
var isLastPage = await inAppWebViewController.canGoBack();
if(isLastPage){
inAppWebViewController.goBack();
return false;
}
return true;
},
child: SafeArea(
child: Scaffold(
body: Stack(
children: [
InAppWebView(
initialUrlRequest: URLRequest(
url: Uri.parse("https://portal.linkpj.com.br/contato")
),
onWebViewCreated: (InAppWebViewController controller){
inAppWebViewController = controller;
},
onProgressChanged: (InAppWebViewController controller , int progress){
setState(() {
_progress = progress / 100;
});
},
),
_progress < 1 ? Container(
child: LinearProgressIndicator(
value: _progress,
),
):SizedBox()
],
),
),
),
);
}
}
我尝试在小部件中调用 webview 类levedButton 但出现错误。但是,我希望能轻松解决这个问题。
要在用户按下 ElevatedButton 时在 Flutter 中打开 WebView,您可以使用
the webview_flutter
包。
以下是实现此目标的步骤:
dependencies:
flutter:
sdk: flutter
webview_flutter: ^2.0.13 # Use the latest version of webview_flutter
import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';
class WebViewExample extends StatefulWidget {
@override
_WebViewExampleState createState() => _WebViewExampleState();
}
class _WebViewExampleState extends State<WebViewExample> {
final webViewKey = GlobalKey<WebViewState>();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("WebView Example"),
),
body: Column(
children: [
ElevatedButton(
onPressed: () {
// Navigate to a URL when the button is pressed
webViewKey.currentState!.loadUrl("https://example.com");
},
child: Text("Open WebView"),
),
Expanded(
child: WebView(
key: webViewKey,
javascriptMode: JavascriptMode.unrestricted,
),
),
],
),
);
}
}
在此示例中,我们创建一个名为 WebViewExample 的 StatefulWidget。它包含一个 ElevatedButton,按下该按钮时,将使用 WebView 的 loadUrl 方法导航到特定 URL(在本例中为“https://example.com”)。 WebView 被包装在 Expanded 小部件中以占用列中的剩余空间。
void main() {
runApp(MaterialApp(
home: WebViewExample(),
));
}
这只是一般性的回答,希望对你有帮助!