A case study of the combination of flutter WebView and Vue

wesin 2021-05-03 18:20:34
case study combination flutter webview


12.png tip: use Flutter Realize the general framework function , Then use the business function Vue To achieve , Can solve the company's mobile development resource shortage , But every business group has H5 Development scenarios .

and H5 Development doesn't need management trouble app shelves , Native hardware call and other mobile terminal knowledge .

So recently we used Flutter_inappwebview Made a app Built in browser to achieve this function .

Let's talk about the implementation scheme :

introduce Vue Resource file

use webview Open the web page directly is obviously experience card , So we need to Vue Good page build Resource file , Pack to Flutter In Engineering .

stay pubspec.yaml The configuration file introduces the resource file .

 assets:
- assets/
- assets/fonts/
- assets/css/
- assets/home/
- assets/js/
- assets/test/
 Copy code 

If I introduce two Vue The page of . One test、 One home.

Get ready Flutter_inappwebview

Flutter_inappwebview The examples used in official cases are in the most primitive way , No progress bar , Any change in page status will be re created rebuild webview. This is obviously not in line with the current Flutter Development philosophy .webview After loading the web page, it should be fixed without re loading build Of .

Used at that time Flutter_bloc Framework to solve ,( The recent discovery GetX Simpler framework , I recommend it here ) It's easy to add a progress bar at the top of the page , There's one in the middle load Animation .

Construct a HPWebViewPage, Core code

 InAppWebView webviewInit(BuildContext context) {
HPWebViewBloc vbloc = BlocProvider.of<HPWebViewBloc>(context);
print("view init: ${this.viewInfo.url}");
return InAppWebView(
key: const Key("in_app_webview"),
initialUrlRequest: this.viewInfo.url.startsWith(HPWebViewConst.filePath)
? null
: URLRequest(url: Uri.parse(this.viewInfo.url)),
onWebViewCreated: (controller) {
if (jsHandler != null) {
jsHandler!(controller, context);
}
},
onLoadStart: (controller, uri) =>
vbloc.add(HPWebViewLoadStartEvent(controller, uri)),
onLoadError: (controller, uri, code, message) =>
vbloc.add(HPWebViewLoadErrorEvent(controller, uri, code, message)),
onLoadHttpError: (controller, uri, code, message) =>
vbloc.add(HPWebViewLoadErrorEvent(controller, uri, code, message)),
onLoadStop: (controller, uri) =>
vbloc.add(WebViewLoadStopEvent(controller, uri)),
onProgressChanged: (controller, progress) =>
vbloc.add(WebViewProgressEvent(controller, progress)),
initialUserScripts: this.injectJSList);
}
 Copy code 

jsHandler、injectJSList It's from the outside .Flutter And H5 Interactive code . This is defined by different businesses .

build Code

 @override
Widget build(BuildContext context) {
return Stack(
alignment: Alignment.center,
fit: StackFit.expand,
children: [
webviewInit(context),
Positioned(
top: 0,
child: BlocBuilder<HPWebViewBloc, HPWebViewState>(
builder: (context, state) {
print(state);
if (state is HPWebViewLoadStartState) {
return Container(
child: LinearProgressIndicator(value: 0), height: 2);
}
if (state is HPWebViewProgressState) {
return Container(
child:
LinearProgressIndicator(value: state.progress / 100),
height: 2);
}
return Container(height: 0, width: 0);
},
),
left: 0,
right: 0),
Center(
child: BlocBuilder<HPWebViewBloc, HPWebViewState>(
builder: (context, state) {
if (state is HPWebViewLoadStartState ||
state is HPWebViewProgressState) {
return CircularProgressIndicator();
}
return Container(height: 0, width: 0);
},
),
)
],
);
}
 Copy code 

open Webview

open webview Need to inject interactive code , If you don't need to add .

class WebViewUtil {
static void openWebView(WebViewModel viewInfo, BuildContext context) async {
String injectJS = await rootBundle.loadString("assets/files/inject.js");
Navigator.of(context).push(MaterialPageRoute(builder: (context) {
return HPWebViewPage(
viewInfo: viewInfo,
injectJSList: UnmodifiableListView<UserScript>([
UserScript(
source: injectJS,
injectionTime: UserScriptInjectionTime.AT_DOCUMENT_END),
]),
jsHandler: _addJSHandler);
}));
}
static void _addJSHandler(
InAppWebViewController controller, BuildContext context) {
controller.addJavaScriptHandler(
handlerName: JSHandlerConst.close,
callback: (_) {
Navigator.of(context).pop();
});
controller.addJavaScriptHandler(
handlerName: JSHandlerConst.openUrl,
callback: (args) {
var url = args[0]['url'];
var title = args[0]['title'];
var filterUrl = args[0]['filterurl'];
var filterTitle = args[0]['filtertitle'];
Navigator.of(context).pushNamed(HPWebViewPage.routeName,
arguments: WebViewModel(url,
title: title,
filterUrl: filterUrl,
filterTitle: filterTitle));
// bloc.add(JSHandlerOpenUrlEvent(args));
});
controller.addJavaScriptHandler(
handlerName: JSHandlerConst.back,
callback: (args) {
Navigator.of(context).pop();
});
}
}
 Copy code 

inject.js Just define a set of window.js.handler Interface

// Slip back
handler.back = function() {
window.flutter_inappwebview.callHandler('back');
}
 Copy code 

The current code can only open one url, Instead of opening the local vue page

void _openWebPage(WebViewModel viewInfo, BuildContext context) {
WebViewUtil.openWebView(viewInfo, context);
}
_openWebPage(
WebViewModel("https://github.com/wesin/hp_webview",
title: "github"),
context);
 Copy code 

Load local web page

To load a local web page, you need to app Start a proxy service in , When loading through a proxy url when , Intercept request . return H5 Resource file . In this way , We can download it from the server html file , You can also load the html file .

stay main Start the local agent service in , Designated port

final HPWebViewProxy localhostServer = new HPWebViewProxy(port: 8765);
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await localhostServer.start();
print(localhostServer.isRunning());
 Copy code 

So you can open the local page

ElevatedButton(
onPressed: () => _openWebPage(
WebViewModel("http://localhost:8765/home/"), context),
child: Text(" Open a local page ")),
 Copy code 

The code of the proxy service and all the code can be found in my github Look up . Portal

版权声明
本文为[wesin]所创,转载请带上原文链接,感谢
https://qdmana.com/2021/05/20210503181828225p.html

  1. 浅谈 React 中的 XSS 攻击
  2. XSS attack in react
  3. 自学前端教程整理,附不容错过的前端100篇文章合集
  4. Self taught front-end tutorial collation, with a collection of 100 front-end articles that can not be missed
  5. 使用OpenTracing跟踪Go中的HTTP请求延迟
  6. Using opentracing to track HTTP request latency in go
  7. Encapsulating databinding allows you to write less than 10000 lines of code
  8. 03-HTML5标签-HTML5极速入门
  9. 03-html5 tag-html5 quick start
  10. LayUI - 极易上手拿来即用的前端 UI 框架
  11. Layui - easy to use front end UI framework
  12. Interpretation of lodash source code (1)
  13. Why is the first parameter of node family callback error?
  14. 报告:JavaScript 开发者达1380 万,C#超越 PHP,Rust 增长最快
  15. Report: Javascript developers reach 13.8 million, C surpasses PHP, and rust grows fastest
  16. 小白前端入门笔记(10),怎么设置网站内部的超链接?
  17. How to set up hyperlinks inside the website?
  18. Using node and socket to realize online chat room
  19. The core competitiveness of Vue: data bidirectional binding
  20. React configuration agent
  21. CSS layout
  22. Application scenario explanation of Vue dynamic component
  23. Redux learning notes 04 -- using multiple reducers to manage data
  24. After three months of typescript writing, what have I learned?
  25. Node family - what is a callback?
  26. React -- a simple implementation of render & create element
  27. JS learning simple usage of jquery
  28. Seamless love
  29. 小白前端入门笔记(12),设置哑链接
  30. Small white front-end entry notes (12), set dumb links
  31. Vue2. X opens composition API and TSX
  32. Interview record and thinking of social recruitment for one and a half years (Alibaba, Tencent, baidu offer)
  33. Flex learning notes
  34. The most essential closure article in the eastern hemisphere
  35. 2021-05-03 hot news
  36. Sword finger offer -- reverse order pair in array (JS Implementation)
  37. Working process of scaffold
  38. Use decorator mode to strengthen your fetch
  39. [JS] scope (Introduction)
  40. Employment information statistics network (interface document)
  41. Analysis of MVC
  42. [middle stage] please stay and join me in the backstage
  43. Understanding front end garbage collection
  44. [continuous update] front end special style implementation
  45. Flutter product analysis and package reduction scheme
  46. XPath positioning
  47. 前端开发css中的flex布局的使用
  48. The use of flex layout in front end development CSS
  49. JQuery核心函数和静态方法
  50. JQuery core functions and static methods
  51. Node family - understanding of blocking and non blocking
  52. 热点微前端Microfrontend的讨论:谷歌AdWords是真实的微前端
  53. Vue source code analysis (2) initproxy initialization proxy
  54. What's TM called react diff
  55. Summary of common front end data structure
  56. Useeffect in hooks
  57. [encapsulation 02 design pattern] Command pattern, share meta pattern, combination pattern, proxy pattern, strategy pattern
  58. Front end notes: virtual Dom and diff of vue2. X
  59. The best code scanning plug-in of flutter
  60. The simplest plug-in for rights management of flutter