새 프로젝트를 만듭니다.
flutter create webapp1
pubspec.yaml 을 아래와 같이 수정합니다.
dependencies:
webview_flutter: ^2.0.9
home.dart 를 추가하고, webview를 추가합니다. (예제는 webview_flutter 의 기본 sample에 주석 달은 부분을 추가했습니다. https://pub.dev/packages/webview_flutter/example)
import 'dart:async';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';
class HomeWidget extends StatefulWidget {
HomeWidget({Key key}) : super(key: key);
@override
_HomeWidgetState createState() => _HomeWidgetState();
}
class _HomeWidgetState extends State<HomeWidget> {
final Completer<WebViewController> _controller =
Completer<WebViewController>();
// WebViewController를 선언합니다.
WebViewController _webViewController;
@override
void initState() {
super.initState();
// Enable hybrid composition.
if (Platform.isAndroid) WebView.platform = SurfaceAndroidWebView();
}
@override
Widget build(BuildContext context) {
return Column(
children: [
RaisedButton(
child: Text('Youtube'),
onPressed: _onYoutubePressed,
),
RaisedButton(
child: Text('Google'),
onPressed: _onGooglePressed,
),
SizedBox(
width: 600,
height: 400,
child: _buildWebView(),
),
],
);
}
Widget _buildWebView() {
return WebView(
initialUrl: 'https://flutter.dev',
javascriptMode: JavascriptMode.unrestricted,
onWebViewCreated: (WebViewController webViewController) {
_controller.complete(webViewController);
// WebView가 생성될 때 controller를 멤버에 담아 둡니다.
_webViewController = webViewController;
},
onProgress: (int progress) {
print("WebView is loading (progress : $progress%)");
},
javascriptChannels: <JavascriptChannel>{
// _toasterJavascriptChannel(context),
},
navigationDelegate: (NavigationRequest request) {
if (request.url.startsWith('https://www.youtube.com/')) {
print('blocking navigation to $request}');
return NavigationDecision.prevent;
}
print('allowing navigation to $request');
return NavigationDecision.navigate;
},
onPageStarted: (String url) {
print('Page started loading: $url');
},
onPageFinished: (String url) {
print('Page finished loading: $url');
},
gestureNavigationEnabled: true,
);
}
void _onGooglePressed() {
// loadUrl()을 사용해서 다른 URL로 이동합니다.
_webViewController.loadUrl('https://www.google.com');
}
void _onYoutubePressed() {
// loadUrl()을 사용해서 다른 URL로 이동합니다.
_webViewController.loadUrl('https://m.youtube.com');
}
}
main.dart 를 아래와 같이 수정합니다.
...
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
...
return Scaffold(
body: Center(
child: Column(
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
// 아래를 추가합니다.
HomeWidget(
key: Key('1'),
),
],
),
),
...
);
}
}
실행하면 아래와 같이 나옵니다.