在 flutter 中下拉刷新 WebView 页面
Pull down to refresh WebView Page in flutter
我用 WebView 创建了一个 flutter 应用程序
有什么办法可以向下扫刷新网页
我正在使用 "webview_flutter_plugin" 插件
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Stack(
children: <Widget>[
Container(
child: Center(
child: Text(_title),
),
),
],
)),
body: SafeArea(
child: WebView(
key: _key,
javascriptMode: JavascriptMode.unrestricted,
initialUrl: _url)),
);
}
}
SwipeDetectore 做到了。
在 pubspec.yaml 中:
dependencies:
flutter:
sdk: flutter
flutter_webview_plugin: ^0.3.0+2
swipedetector: ^1.2.0
进口:
import 'package:flutter/material.dart';
import 'package:flutter_webview_plugin/flutter_webview_plugin.dart';
import 'package:swipedetector/swipedetector.dart';
在州 Class:
final flutterWebviewPlugin = new FlutterWebviewPlugin();
@override
Widget build(BuildContext context) {
return SwipeDetector(
child: WebviewScaffold(
url: _url,
withJavascript: true,
withZoom: false,
appBar: AppBar(
title: Stack(
children: <Widget>[
Container(child: Center(child: Text(_title))),
],
),
elevation: 1,
),
),
onSwipeDown: () {
flutterWebviewPlugin.reload();
},
swipeConfiguration: SwipeConfiguration(
verticalSwipeMinVelocity: 100.0,
verticalSwipeMinDisplacement: 50.0,
verticalSwipeMaxWidthThreshold: 100.0,
horizontalSwipeMaxHeightThreshold: 50.0,
horizontalSwipeMinDisplacement: 50.0,
horizontalSwipeMinVelocity: 200.0),
);
这个问题不好解决,你可以试试这个方法
import 'dart:io';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:fluttertoast/fluttertoast.dart';
int scheck;
WebViewController controllerGlobal;
void main() {
WidgetsFlutterBinding.ensureInitialized();
SystemChrome.setEnabledSystemUIOverlays([]);
runApp(
new MaterialApp(
debugShowCheckedModeBanner: false,
home: new WebViewEx(),
),
);
}
class WebViewEx extends StatefulWidget {
@override
WebViewExampleState createState() => WebViewExampleState();
}
class WebViewExampleState extends State<WebViewEx> {
bool check, check1;
ScrollController _scrollController;
@override
void initState() {
_scrollController = ScrollController();
_scrollController.addListener(_scrollListener);
super.initState();
check = false;
check1 = false;
}
_scrollListener() {
if (_scrollController.offset <=
_scrollController.position.minScrollExtent &&
!_scrollController.position.outOfRange) {
controllerGlobal.reload();
}
}
@override
Widget build(BuildContext context) {
return WillPopScope(
onWillPop: () => controllerGlobal.goBack(),
child: ListView(
physics: ClampingScrollPhysics(),
shrinkWrap: true,
children: [
Container(
padding: EdgeInsets.all(10),
height: MediaQuery.of(context).size.height,
child: WebView(
initialUrl: '...............',
gestureNavigationEnabled: true,
debuggingEnabled: true,
gestureRecognizers: [
Factory(() => PlatformViewVerticalGestureRecognizer()),
].toSet(),
javascriptMode: JavascriptMode.unrestricted,
onPageFinished: (String url) {
setState(() {
bool temp = check;
check = true;
if (!temp) controllerGlobal.scrollBy(0, 10);
});
},
onWebViewCreated: (WebViewController webViewController) {
controllerGlobal = webViewController;
},
),
),
],
),
);
}
@override
void dispose() {
super.dispose();
}
}
class PlatformViewVerticalGestureRecognizer
extends VerticalDragGestureRecognizer {
PlatformViewVerticalGestureRecognizer({PointerDeviceKind kind})
: super(kind: kind);
Offset _dragDistance = Offset.zero;
@override
void addPointer(PointerEvent event) {
startTrackingPointer(event.pointer);
}
@override
void handleEvent(PointerEvent event) {
_dragDistance = _dragDistance + event.delta;
controllerGlobal.getScrollY().then((value) {
print(value);
if (value < 5) {
Fluttertoast.showToast(
msg: "RELOADING",
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.BOTTOM,
timeInSecForIosWeb: 1,
backgroundColor: Colors.amber[800],
textColor: Colors.black,
fontSize: 16.0);
controllerGlobal.reload();
}
});
// if (event is PointerMoveEvent) {
// final double dy = _dragDistance.dy.abs();
// final double dx = _dragDistance.dx.abs();
// if (dy > dx && dy > kTouchSlop) {
// // vertical drag - accept
// resolve(GestureDisposition.accepted);
// _dragDistance = Offset.zero;
// } else if (dx > kTouchSlop && dx > dy) {
// // horizontal drag - stop tracking
// stopTrackingPointer(event.pointer);
// _dragDistance = Offset.zero;
// }
// }
}
@override
String get debugDescription => 'horizontal drag (platform view)';
@override
void didStopTrackingLastPointer(int pointer) {}
}
我找到了使用手势识别器来刷新 webview 的解决方法,只需在您的 webview 小部件中添加以下代码
WebView(
key: UniqueKey(),
initialUrl: 'https://summachar.app',
javascriptMode: JavascriptMode.unrestricted,
onWebViewCreated: (WebViewController webViewController) {
_controller = webViewController;
},
onPageFinished: (String str) {
myModel.stopLoading();
},
onPageStarted: (String str) {
myModel.startLoading();
},
gestureRecognizers: Set()
..add(Factory<VerticalDragGestureRecognizer>(
() => VerticalDragGestureRecognizer()
..onDown = (DragDownDetails dragDownDetails) {
_controller.getScrollY().then((value) {
if (value == 0 &&
dragDownDetails.globalPosition.direction < 1) {
_controller.reload();
}
});
})),
),
在AppWebView中使用flutter
flutter_inappwebview: ^5.0.5+2
这是一个例子
late PullToRefreshController pullToRefreshController;
final MyInAppBrowser browser = MyInAppBrowser();
@override
void initState() {
super.initState();
pullToRefreshController = PullToRefreshController(
options: PullToRefreshOptions(
color: Colors.black,
),
onRefresh: () async {
if (Platform.isAndroid) {
browser.webViewController.reload();
} else if (Platform.isIOS) {
browser.webViewController.loadUrl(
urlRequest: URLRequest(url: await browser.webViewController.getUrl()));
}
},
);
browser.pullToRefreshController = pullToRefreshController;
}
InAppWebView(
initialUrlRequest: URLRequest(
url: Uri.parse(widget.url)
),
initialOptions: InAppWebViewGroupOptions(
crossPlatform: InAppWebViewOptions(
),
ios: IOSInAppWebViewOptions(
),
android: AndroidInAppWebViewOptions(
useHybridComposition: true
)
),
onWebViewCreated: (InAppWebViewController controller) {
webView = controller;
},
onLoadStart: (controller, url) {
setState(() {
this.url = url?.toString() ?? '';
});
},
onLoadStop: (controller, url) async {
setState(() {
this.url = url?.toString() ?? '';
});
},
onProgressChanged: (controller, progress) {
setState(() {
this.progress = progress / 100;
if(progress == 100){
_isRefreshing = false;
}
});
},
),
我用 WebView 创建了一个 flutter 应用程序
有什么办法可以向下扫刷新网页
我正在使用 "webview_flutter_plugin" 插件
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Stack(
children: <Widget>[
Container(
child: Center(
child: Text(_title),
),
),
],
)),
body: SafeArea(
child: WebView(
key: _key,
javascriptMode: JavascriptMode.unrestricted,
initialUrl: _url)),
);
}
}
SwipeDetectore 做到了。
在 pubspec.yaml 中:
dependencies:
flutter:
sdk: flutter
flutter_webview_plugin: ^0.3.0+2
swipedetector: ^1.2.0
进口:
import 'package:flutter/material.dart';
import 'package:flutter_webview_plugin/flutter_webview_plugin.dart';
import 'package:swipedetector/swipedetector.dart';
在州 Class:
final flutterWebviewPlugin = new FlutterWebviewPlugin();
@override
Widget build(BuildContext context) {
return SwipeDetector(
child: WebviewScaffold(
url: _url,
withJavascript: true,
withZoom: false,
appBar: AppBar(
title: Stack(
children: <Widget>[
Container(child: Center(child: Text(_title))),
],
),
elevation: 1,
),
),
onSwipeDown: () {
flutterWebviewPlugin.reload();
},
swipeConfiguration: SwipeConfiguration(
verticalSwipeMinVelocity: 100.0,
verticalSwipeMinDisplacement: 50.0,
verticalSwipeMaxWidthThreshold: 100.0,
horizontalSwipeMaxHeightThreshold: 50.0,
horizontalSwipeMinDisplacement: 50.0,
horizontalSwipeMinVelocity: 200.0),
);
这个问题不好解决,你可以试试这个方法
import 'dart:io';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:fluttertoast/fluttertoast.dart';
int scheck;
WebViewController controllerGlobal;
void main() {
WidgetsFlutterBinding.ensureInitialized();
SystemChrome.setEnabledSystemUIOverlays([]);
runApp(
new MaterialApp(
debugShowCheckedModeBanner: false,
home: new WebViewEx(),
),
);
}
class WebViewEx extends StatefulWidget {
@override
WebViewExampleState createState() => WebViewExampleState();
}
class WebViewExampleState extends State<WebViewEx> {
bool check, check1;
ScrollController _scrollController;
@override
void initState() {
_scrollController = ScrollController();
_scrollController.addListener(_scrollListener);
super.initState();
check = false;
check1 = false;
}
_scrollListener() {
if (_scrollController.offset <=
_scrollController.position.minScrollExtent &&
!_scrollController.position.outOfRange) {
controllerGlobal.reload();
}
}
@override
Widget build(BuildContext context) {
return WillPopScope(
onWillPop: () => controllerGlobal.goBack(),
child: ListView(
physics: ClampingScrollPhysics(),
shrinkWrap: true,
children: [
Container(
padding: EdgeInsets.all(10),
height: MediaQuery.of(context).size.height,
child: WebView(
initialUrl: '...............',
gestureNavigationEnabled: true,
debuggingEnabled: true,
gestureRecognizers: [
Factory(() => PlatformViewVerticalGestureRecognizer()),
].toSet(),
javascriptMode: JavascriptMode.unrestricted,
onPageFinished: (String url) {
setState(() {
bool temp = check;
check = true;
if (!temp) controllerGlobal.scrollBy(0, 10);
});
},
onWebViewCreated: (WebViewController webViewController) {
controllerGlobal = webViewController;
},
),
),
],
),
);
}
@override
void dispose() {
super.dispose();
}
}
class PlatformViewVerticalGestureRecognizer
extends VerticalDragGestureRecognizer {
PlatformViewVerticalGestureRecognizer({PointerDeviceKind kind})
: super(kind: kind);
Offset _dragDistance = Offset.zero;
@override
void addPointer(PointerEvent event) {
startTrackingPointer(event.pointer);
}
@override
void handleEvent(PointerEvent event) {
_dragDistance = _dragDistance + event.delta;
controllerGlobal.getScrollY().then((value) {
print(value);
if (value < 5) {
Fluttertoast.showToast(
msg: "RELOADING",
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.BOTTOM,
timeInSecForIosWeb: 1,
backgroundColor: Colors.amber[800],
textColor: Colors.black,
fontSize: 16.0);
controllerGlobal.reload();
}
});
// if (event is PointerMoveEvent) {
// final double dy = _dragDistance.dy.abs();
// final double dx = _dragDistance.dx.abs();
// if (dy > dx && dy > kTouchSlop) {
// // vertical drag - accept
// resolve(GestureDisposition.accepted);
// _dragDistance = Offset.zero;
// } else if (dx > kTouchSlop && dx > dy) {
// // horizontal drag - stop tracking
// stopTrackingPointer(event.pointer);
// _dragDistance = Offset.zero;
// }
// }
}
@override
String get debugDescription => 'horizontal drag (platform view)';
@override
void didStopTrackingLastPointer(int pointer) {}
}
我找到了使用手势识别器来刷新 webview 的解决方法,只需在您的 webview 小部件中添加以下代码
WebView(
key: UniqueKey(),
initialUrl: 'https://summachar.app',
javascriptMode: JavascriptMode.unrestricted,
onWebViewCreated: (WebViewController webViewController) {
_controller = webViewController;
},
onPageFinished: (String str) {
myModel.stopLoading();
},
onPageStarted: (String str) {
myModel.startLoading();
},
gestureRecognizers: Set()
..add(Factory<VerticalDragGestureRecognizer>(
() => VerticalDragGestureRecognizer()
..onDown = (DragDownDetails dragDownDetails) {
_controller.getScrollY().then((value) {
if (value == 0 &&
dragDownDetails.globalPosition.direction < 1) {
_controller.reload();
}
});
})),
),
在AppWebView中使用flutter
flutter_inappwebview: ^5.0.5+2
这是一个例子
late PullToRefreshController pullToRefreshController;
final MyInAppBrowser browser = MyInAppBrowser();
@override
void initState() {
super.initState();
pullToRefreshController = PullToRefreshController(
options: PullToRefreshOptions(
color: Colors.black,
),
onRefresh: () async {
if (Platform.isAndroid) {
browser.webViewController.reload();
} else if (Platform.isIOS) {
browser.webViewController.loadUrl(
urlRequest: URLRequest(url: await browser.webViewController.getUrl()));
}
},
);
browser.pullToRefreshController = pullToRefreshController;
}
InAppWebView(
initialUrlRequest: URLRequest(
url: Uri.parse(widget.url)
),
initialOptions: InAppWebViewGroupOptions(
crossPlatform: InAppWebViewOptions(
),
ios: IOSInAppWebViewOptions(
),
android: AndroidInAppWebViewOptions(
useHybridComposition: true
)
),
onWebViewCreated: (InAppWebViewController controller) {
webView = controller;
},
onLoadStart: (controller, url) {
setState(() {
this.url = url?.toString() ?? '';
});
},
onLoadStop: (controller, url) async {
setState(() {
this.url = url?.toString() ?? '';
});
},
onProgressChanged: (controller, progress) {
setState(() {
this.progress = progress / 100;
if(progress == 100){
_isRefreshing = false;
}
});
},
),