├── LICENSE ├── CHANGELOG.md ├── example ├── ios │ ├── Runner │ │ ├── Runner-Bridging-Header.h │ │ ├── Assets.xcassets │ │ │ ├── LaunchImage.imageset │ │ │ │ ├── LaunchImage.png │ │ │ │ ├── LaunchImage@2x.png │ │ │ │ ├── LaunchImage@3x.png │ │ │ │ ├── README.md │ │ │ │ └── Contents.json │ │ │ └── AppIcon.appiconset │ │ │ │ ├── Icon-App-20x20@1x.png │ │ │ │ ├── Icon-App-20x20@2x.png │ │ │ │ ├── Icon-App-20x20@3x.png │ │ │ │ ├── Icon-App-29x29@1x.png │ │ │ │ ├── Icon-App-29x29@2x.png │ │ │ │ ├── Icon-App-29x29@3x.png │ │ │ │ ├── Icon-App-40x40@1x.png │ │ │ │ ├── Icon-App-40x40@2x.png │ │ │ │ ├── Icon-App-40x40@3x.png │ │ │ │ ├── Icon-App-60x60@2x.png │ │ │ │ ├── Icon-App-60x60@3x.png │ │ │ │ ├── Icon-App-76x76@1x.png │ │ │ │ ├── Icon-App-76x76@2x.png │ │ │ │ ├── Icon-App-1024x1024@1x.png │ │ │ │ ├── Icon-App-83.5x83.5@2x.png │ │ │ │ └── Contents.json │ │ ├── AppDelegate.swift │ │ ├── Base.lproj │ │ │ ├── Main.storyboard │ │ │ └── LaunchScreen.storyboard │ │ └── Info.plist │ ├── Flutter │ │ ├── Debug.xcconfig │ │ ├── Release.xcconfig │ │ └── AppFrameworkInfo.plist │ ├── Runner.xcodeproj │ │ ├── project.xcworkspace │ │ │ ├── contents.xcworkspacedata │ │ │ └── xcshareddata │ │ │ │ ├── WorkspaceSettings.xcsettings │ │ │ │ └── IDEWorkspaceChecks.plist │ │ ├── xcshareddata │ │ │ └── xcschemes │ │ │ │ └── Runner.xcscheme │ │ └── project.pbxproj │ ├── Runner.xcworkspace │ │ ├── contents.xcworkspacedata │ │ └── xcshareddata │ │ │ ├── WorkspaceSettings.xcsettings │ │ │ └── IDEWorkspaceChecks.plist │ ├── .gitignore │ ├── Podfile.lock │ └── Podfile ├── web │ ├── favicon.png │ ├── icons │ │ ├── Icon-192.png │ │ ├── Icon-512.png │ │ ├── Icon-maskable-192.png │ │ └── Icon-maskable-512.png │ ├── manifest.json │ └── index.html ├── android │ ├── gradle.properties │ ├── app │ │ ├── src │ │ │ ├── main │ │ │ │ ├── res │ │ │ │ │ ├── mipmap-hdpi │ │ │ │ │ │ └── ic_launcher.png │ │ │ │ │ ├── mipmap-mdpi │ │ │ │ │ │ └── ic_launcher.png │ │ │ │ │ ├── mipmap-xhdpi │ │ │ │ │ │ └── ic_launcher.png │ │ │ │ │ ├── mipmap-xxhdpi │ │ │ │ │ │ └── ic_launcher.png │ │ │ │ │ ├── mipmap-xxxhdpi │ │ │ │ │ │ └── ic_launcher.png │ │ │ │ │ ├── drawable │ │ │ │ │ │ └── launch_background.xml │ │ │ │ │ ├── drawable-v21 │ │ │ │ │ │ └── launch_background.xml │ │ │ │ │ ├── values │ │ │ │ │ │ └── styles.xml │ │ │ │ │ └── values-night │ │ │ │ │ │ └── styles.xml │ │ │ │ ├── kotlin │ │ │ │ │ └── com │ │ │ │ │ │ └── example │ │ │ │ │ │ └── example │ │ │ │ │ │ └── MainActivity.kt │ │ │ │ └── AndroidManifest.xml │ │ │ ├── debug │ │ │ │ └── AndroidManifest.xml │ │ │ └── profile │ │ │ │ └── AndroidManifest.xml │ │ └── build.gradle │ ├── gradle │ │ └── wrapper │ │ │ └── gradle-wrapper.properties │ ├── .gitignore │ ├── settings.gradle │ └── build.gradle ├── .metadata ├── README.md ├── test │ └── widget_test.dart ├── .gitignore ├── lib │ ├── tools │ │ └── local_server_webview_manager.dart │ ├── main.dart │ └── web_page.dart ├── analysis_options.yaml ├── pubspec.yaml └── pubspec.lock ├── analysis_options.yaml ├── .metadata ├── lib ├── tools │ ├── local_server_status_handler.dart │ ├── local_server_config_cache.dart │ ├── local_server_binder.dart │ ├── local_server_manager.dart │ └── local_server_downloader.dart ├── local_server_for_webview.dart └── src │ ├── model │ ├── local_server_client_config_item.dart │ ├── download_service_total_asset_item.dart │ ├── download_service_item.dart │ └── local_server_client_config.dart │ └── services │ ├── local_server_configuration.dart │ └── local_server_service.dart ├── test └── local_server_for_webview_test.dart ├── .gitignore ├── pubspec.yaml └── README.md /LICENSE: -------------------------------------------------------------------------------- 1 | TODO: Add your license here. 2 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | ## 0.0.1 2 | 3 | * TODO: Describe initial release. 4 | -------------------------------------------------------------------------------- /example/ios/Runner/Runner-Bridging-Header.h: -------------------------------------------------------------------------------- 1 | #import "GeneratedPluginRegistrant.h" 2 | -------------------------------------------------------------------------------- /example/web/favicon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EchoPuda/local_server_webview/HEAD/example/web/favicon.png -------------------------------------------------------------------------------- /example/android/gradle.properties: -------------------------------------------------------------------------------- 1 | org.gradle.jvmargs=-Xmx1536M 2 | android.useAndroidX=true 3 | android.enableJetifier=true 4 | -------------------------------------------------------------------------------- /example/web/icons/Icon-192.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EchoPuda/local_server_webview/HEAD/example/web/icons/Icon-192.png -------------------------------------------------------------------------------- /example/web/icons/Icon-512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EchoPuda/local_server_webview/HEAD/example/web/icons/Icon-512.png -------------------------------------------------------------------------------- /example/web/icons/Icon-maskable-192.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EchoPuda/local_server_webview/HEAD/example/web/icons/Icon-maskable-192.png -------------------------------------------------------------------------------- /example/web/icons/Icon-maskable-512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EchoPuda/local_server_webview/HEAD/example/web/icons/Icon-maskable-512.png -------------------------------------------------------------------------------- /example/ios/Flutter/Debug.xcconfig: -------------------------------------------------------------------------------- 1 | #include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig" 2 | #include "Generated.xcconfig" 3 | -------------------------------------------------------------------------------- /example/ios/Flutter/Release.xcconfig: -------------------------------------------------------------------------------- 1 | #include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig" 2 | #include "Generated.xcconfig" 3 | -------------------------------------------------------------------------------- /example/android/app/src/main/res/mipmap-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EchoPuda/local_server_webview/HEAD/example/android/app/src/main/res/mipmap-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /example/android/app/src/main/res/mipmap-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EchoPuda/local_server_webview/HEAD/example/android/app/src/main/res/mipmap-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /example/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EchoPuda/local_server_webview/HEAD/example/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /analysis_options.yaml: -------------------------------------------------------------------------------- 1 | include: package:flutter_lints/flutter.yaml 2 | 3 | # Additional information about this file can be found at 4 | # https://dart.dev/guides/language/analysis-options 5 | -------------------------------------------------------------------------------- /example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EchoPuda/local_server_webview/HEAD/example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EchoPuda/local_server_webview/HEAD/example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EchoPuda/local_server_webview/HEAD/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png -------------------------------------------------------------------------------- /example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EchoPuda/local_server_webview/HEAD/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png -------------------------------------------------------------------------------- /example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EchoPuda/local_server_webview/HEAD/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png -------------------------------------------------------------------------------- /example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EchoPuda/local_server_webview/HEAD/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png -------------------------------------------------------------------------------- /example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EchoPuda/local_server_webview/HEAD/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png -------------------------------------------------------------------------------- /example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EchoPuda/local_server_webview/HEAD/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png -------------------------------------------------------------------------------- /example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EchoPuda/local_server_webview/HEAD/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png -------------------------------------------------------------------------------- /example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EchoPuda/local_server_webview/HEAD/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png -------------------------------------------------------------------------------- /example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EchoPuda/local_server_webview/HEAD/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png -------------------------------------------------------------------------------- /example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EchoPuda/local_server_webview/HEAD/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png -------------------------------------------------------------------------------- /example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EchoPuda/local_server_webview/HEAD/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png -------------------------------------------------------------------------------- /example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EchoPuda/local_server_webview/HEAD/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png -------------------------------------------------------------------------------- /example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EchoPuda/local_server_webview/HEAD/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png -------------------------------------------------------------------------------- /example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EchoPuda/local_server_webview/HEAD/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png -------------------------------------------------------------------------------- /example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EchoPuda/local_server_webview/HEAD/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png -------------------------------------------------------------------------------- /example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EchoPuda/local_server_webview/HEAD/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png -------------------------------------------------------------------------------- /example/android/app/src/main/kotlin/com/example/example/MainActivity.kt: -------------------------------------------------------------------------------- 1 | package com.example.example 2 | 3 | import io.flutter.embedding.android.FlutterActivity 4 | 5 | class MainActivity: FlutterActivity() { 6 | } 7 | -------------------------------------------------------------------------------- /example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EchoPuda/local_server_webview/HEAD/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png -------------------------------------------------------------------------------- /example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EchoPuda/local_server_webview/HEAD/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png -------------------------------------------------------------------------------- /example/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /example/android/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Fri Jun 23 08:50:38 CEST 2017 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-6.7-all.zip 7 | -------------------------------------------------------------------------------- /example/ios/Runner.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /example/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | PreviewsEnabled 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /example/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | IDEDidComputeMac32BitWarning 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /example/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | PreviewsEnabled 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /example/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | IDEDidComputeMac32BitWarning 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /.metadata: -------------------------------------------------------------------------------- 1 | # This file tracks properties of this Flutter project. 2 | # Used by Flutter tool to assess capabilities and perform upgrades etc. 3 | # 4 | # This file should be version controlled and should not be manually edited. 5 | 6 | version: 7 | revision: 7e9793dee1b85a243edd0e06cb1658e98b077561 8 | channel: stable 9 | 10 | project_type: package 11 | -------------------------------------------------------------------------------- /example/.metadata: -------------------------------------------------------------------------------- 1 | # This file tracks properties of this Flutter project. 2 | # Used by Flutter tool to assess capabilities and perform upgrades etc. 3 | # 4 | # This file should be version controlled and should not be manually edited. 5 | 6 | version: 7 | revision: 7e9793dee1b85a243edd0e06cb1658e98b077561 8 | channel: stable 9 | 10 | project_type: app 11 | -------------------------------------------------------------------------------- /example/android/.gitignore: -------------------------------------------------------------------------------- 1 | gradle-wrapper.jar 2 | /.gradle 3 | /captures/ 4 | /gradlew 5 | /gradlew.bat 6 | /local.properties 7 | GeneratedPluginRegistrant.java 8 | 9 | # Remember to never publicly share your keystore. 10 | # See https://flutter.dev/docs/deployment/android#reference-the-keystore-from-the-app 11 | key.properties 12 | **/*.keystore 13 | **/*.jks 14 | -------------------------------------------------------------------------------- /example/android/app/src/debug/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 3 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /example/android/app/src/profile/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 3 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /example/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md: -------------------------------------------------------------------------------- 1 | # Launch Screen Assets 2 | 3 | You can customize the launch screen with your own desired assets by replacing the image files in this directory. 4 | 5 | You can also do it by opening your Flutter project's Xcode project with `open ios/Runner.xcworkspace`, selecting `Runner/Assets.xcassets` in the Project Navigator and dropping in the desired images. -------------------------------------------------------------------------------- /lib/tools/local_server_status_handler.dart: -------------------------------------------------------------------------------- 1 | abstract class LocalServerStatusHandler { 2 | /// server创建成功 3 | createServerSuccess(int port,String localAddress); 4 | /// server创建失败 5 | createServerFailure(dynamic err); 6 | /// server将要关闭 7 | serverWillCancel(); 8 | /// server关闭 9 | serverDidCancel(); 10 | /// server 请求失败 11 | requestServerFailure(String path,Object error); 12 | /// server 获取返回资源 13 | dynamic fetchRespondsSources(String path); 14 | } -------------------------------------------------------------------------------- /example/ios/Runner/AppDelegate.swift: -------------------------------------------------------------------------------- 1 | import UIKit 2 | import Flutter 3 | 4 | @UIApplicationMain 5 | @objc class AppDelegate: FlutterAppDelegate { 6 | override func application( 7 | _ application: UIApplication, 8 | didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? 9 | ) -> Bool { 10 | GeneratedPluginRegistrant.register(with: self) 11 | return super.application(application, didFinishLaunchingWithOptions: launchOptions) 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /example/android/settings.gradle: -------------------------------------------------------------------------------- 1 | include ':app' 2 | 3 | def localPropertiesFile = new File(rootProject.projectDir, "local.properties") 4 | def properties = new Properties() 5 | 6 | assert localPropertiesFile.exists() 7 | localPropertiesFile.withReader("UTF-8") { reader -> properties.load(reader) } 8 | 9 | def flutterSdkPath = properties.getProperty("flutter.sdk") 10 | assert flutterSdkPath != null, "flutter.sdk not set in local.properties" 11 | apply from: "$flutterSdkPath/packages/flutter_tools/gradle/app_plugin_loader.gradle" 12 | -------------------------------------------------------------------------------- /example/android/app/src/main/res/drawable/launch_background.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 12 | 13 | -------------------------------------------------------------------------------- /example/android/app/src/main/res/drawable-v21/launch_background.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 12 | 13 | -------------------------------------------------------------------------------- /example/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "images" : [ 3 | { 4 | "idiom" : "universal", 5 | "filename" : "LaunchImage.png", 6 | "scale" : "1x" 7 | }, 8 | { 9 | "idiom" : "universal", 10 | "filename" : "LaunchImage@2x.png", 11 | "scale" : "2x" 12 | }, 13 | { 14 | "idiom" : "universal", 15 | "filename" : "LaunchImage@3x.png", 16 | "scale" : "3x" 17 | } 18 | ], 19 | "info" : { 20 | "version" : 1, 21 | "author" : "xcode" 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /test/local_server_for_webview_test.dart: -------------------------------------------------------------------------------- 1 | import 'package:flutter_test/flutter_test.dart'; 2 | 3 | import 'package:local_server_for_webview/local_server_for_webview.dart'; 4 | 5 | void main() { 6 | test('start local server', () async { 7 | var server = await LocalServerService.instance.startServer('127.0.0.1', 0); 8 | String res = LocalServerService.instance.getLocalServerWebUrl('', '/test/index.html'); 9 | expect(res, 'http://127.0.0.1:${server.port}/test/index.html'); 10 | }); 11 | 12 | test('close local server', () { 13 | LocalServerService.instance.closeServer(); 14 | }); 15 | } 16 | -------------------------------------------------------------------------------- /example/README.md: -------------------------------------------------------------------------------- 1 | # example 2 | 3 | A new Flutter project. 4 | 5 | ## Getting Started 6 | 7 | This project is a starting point for a Flutter application. 8 | 9 | A few resources to get you started if this is your first Flutter project: 10 | 11 | - [Lab: Write your first Flutter app](https://flutter.dev/docs/get-started/codelab) 12 | - [Cookbook: Useful Flutter samples](https://flutter.dev/docs/cookbook) 13 | 14 | For help getting started with Flutter, view our 15 | [online documentation](https://flutter.dev/docs), which offers tutorials, 16 | samples, guidance on mobile development, and a full API reference. 17 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Miscellaneous 2 | *.class 3 | *.log 4 | *.pyc 5 | *.swp 6 | .DS_Store 7 | .atom/ 8 | .buildlog/ 9 | .history 10 | .svn/ 11 | 12 | # IntelliJ related 13 | *.iml 14 | *.ipr 15 | *.iws 16 | .idea/ 17 | 18 | # The .vscode folder contains launch configuration and tasks you configure in 19 | # VS Code which you may wish to be included in version control, so this line 20 | # is commented out by default. 21 | #.vscode/ 22 | 23 | # Flutter/Dart/Pub related 24 | # Libraries should not include pubspec.lock, per https://dart.dev/guides/libraries/private-files#pubspeclock. 25 | /pubspec.lock 26 | **/doc/api/ 27 | .dart_tool/ 28 | .packages 29 | build/ 30 | -------------------------------------------------------------------------------- /example/test/widget_test.dart: -------------------------------------------------------------------------------- 1 | // This is a basic Flutter widget test. 2 | // 3 | // To perform an interaction with a widget in your test, use the WidgetTester 4 | // utility that Flutter provides. For example, you can send tap and scroll 5 | // gestures. You can also use WidgetTester to find child widgets in the widget 6 | // tree, read text, and verify that the values of widget properties are correct. 7 | 8 | import 'package:example/tools/local_server_webview_manager.dart'; 9 | 10 | import 'package:flutter_test/flutter_test.dart'; 11 | 12 | void main() { 13 | test('test init download', () { 14 | LocalServerWebViewManager.instance.initSetting(); 15 | }); 16 | } 17 | -------------------------------------------------------------------------------- /example/ios/.gitignore: -------------------------------------------------------------------------------- 1 | **/dgph 2 | *.mode1v3 3 | *.mode2v3 4 | *.moved-aside 5 | *.pbxuser 6 | *.perspectivev3 7 | **/*sync/ 8 | .sconsign.dblite 9 | .tags* 10 | **/.vagrant/ 11 | **/DerivedData/ 12 | Icon? 13 | **/Pods/ 14 | **/.symlinks/ 15 | profile 16 | xcuserdata 17 | **/.generated/ 18 | Flutter/App.framework 19 | Flutter/Flutter.framework 20 | Flutter/Flutter.podspec 21 | Flutter/Generated.xcconfig 22 | Flutter/ephemeral/ 23 | Flutter/app.flx 24 | Flutter/app.zip 25 | Flutter/flutter_assets/ 26 | Flutter/flutter_export_environment.sh 27 | ServiceDefinitions.json 28 | Runner/GeneratedPluginRegistrant.* 29 | 30 | # Exceptions to above rules. 31 | !default.mode1v3 32 | !default.mode2v3 33 | !default.pbxuser 34 | !default.perspectivev3 35 | -------------------------------------------------------------------------------- /example/android/build.gradle: -------------------------------------------------------------------------------- 1 | buildscript { 2 | ext.kotlin_version = '1.6.10' 3 | repositories { 4 | google() 5 | mavenCentral() 6 | } 7 | 8 | dependencies { 9 | classpath 'com.android.tools.build:gradle:4.1.0' 10 | classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" 11 | } 12 | } 13 | 14 | allprojects { 15 | repositories { 16 | google() 17 | mavenCentral() 18 | } 19 | } 20 | 21 | rootProject.buildDir = '../build' 22 | subprojects { 23 | project.buildDir = "${rootProject.buildDir}/${project.name}" 24 | } 25 | subprojects { 26 | project.evaluationDependsOn(':app') 27 | } 28 | 29 | task clean(type: Delete) { 30 | delete rootProject.buildDir 31 | } 32 | -------------------------------------------------------------------------------- /example/ios/Flutter/AppFrameworkInfo.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | en 7 | CFBundleExecutable 8 | App 9 | CFBundleIdentifier 10 | io.flutter.flutter.app 11 | CFBundleInfoDictionaryVersion 12 | 6.0 13 | CFBundleName 14 | App 15 | CFBundlePackageType 16 | FMWK 17 | CFBundleShortVersionString 18 | 1.0 19 | CFBundleSignature 20 | ???? 21 | CFBundleVersion 22 | 1.0 23 | MinimumOSVersion 24 | 9.0 25 | 26 | 27 | -------------------------------------------------------------------------------- /example/.gitignore: -------------------------------------------------------------------------------- 1 | # Miscellaneous 2 | *.class 3 | *.log 4 | *.pyc 5 | *.swp 6 | .DS_Store 7 | .atom/ 8 | .buildlog/ 9 | .history 10 | .svn/ 11 | 12 | # IntelliJ related 13 | *.iml 14 | *.ipr 15 | *.iws 16 | .idea/ 17 | 18 | # The .vscode folder contains launch configuration and tasks you configure in 19 | # VS Code which you may wish to be included in version control, so this line 20 | # is commented out by default. 21 | #.vscode/ 22 | 23 | # Flutter/Dart/Pub related 24 | **/doc/api/ 25 | **/ios/Flutter/.last_build_id 26 | .dart_tool/ 27 | .flutter-plugins 28 | .flutter-plugins-dependencies 29 | .packages 30 | .pub-cache/ 31 | .pub/ 32 | /build/ 33 | 34 | # Web related 35 | lib/generated_plugin_registrant.dart 36 | 37 | # Symbolication related 38 | app.*.symbols 39 | 40 | # Obfuscation related 41 | app.*.map.json 42 | 43 | # Android Studio will place build artifacts here 44 | /android/app/debug 45 | /android/app/profile 46 | /android/app/release 47 | -------------------------------------------------------------------------------- /lib/local_server_for_webview.dart: -------------------------------------------------------------------------------- 1 | library local_server_for_webview; 2 | 3 | export 'package:local_server_for_webview/src/services/local_server_configuration.dart'; 4 | export 'package:local_server_for_webview/src/services/local_server_service.dart'; 5 | export 'package:local_server_for_webview/tools/local_server_status_handler.dart'; 6 | export 'package:local_server_for_webview/tools/local_server_binder.dart'; 7 | export 'package:local_server_for_webview/tools/local_server_config_cache.dart'; 8 | export 'package:local_server_for_webview/tools/local_server_downloader.dart'; 9 | export 'package:local_server_for_webview/tools/local_server_manager.dart'; 10 | export 'package:local_server_for_webview/src/model/download_service_item.dart'; 11 | export 'package:local_server_for_webview/src/model/download_service_total_asset_item.dart'; 12 | export 'package:local_server_for_webview/src/model/local_server_client_config.dart'; 13 | export 'package:local_server_for_webview/src/model/local_server_client_config_item.dart'; -------------------------------------------------------------------------------- /example/web/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "example", 3 | "short_name": "example", 4 | "start_url": ".", 5 | "display": "standalone", 6 | "background_color": "#0175C2", 7 | "theme_color": "#0175C2", 8 | "description": "A new Flutter project.", 9 | "orientation": "portrait-primary", 10 | "prefer_related_applications": false, 11 | "icons": [ 12 | { 13 | "src": "icons/Icon-192.png", 14 | "sizes": "192x192", 15 | "type": "image/png" 16 | }, 17 | { 18 | "src": "icons/Icon-512.png", 19 | "sizes": "512x512", 20 | "type": "image/png" 21 | }, 22 | { 23 | "src": "icons/Icon-maskable-192.png", 24 | "sizes": "192x192", 25 | "type": "image/png", 26 | "purpose": "maskable" 27 | }, 28 | { 29 | "src": "icons/Icon-maskable-512.png", 30 | "sizes": "512x512", 31 | "type": "image/png", 32 | "purpose": "maskable" 33 | } 34 | ] 35 | } 36 | -------------------------------------------------------------------------------- /example/android/app/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 9 | 15 | 18 | 19 | -------------------------------------------------------------------------------- /example/android/app/src/main/res/values-night/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 9 | 15 | 18 | 19 | -------------------------------------------------------------------------------- /example/ios/Podfile.lock: -------------------------------------------------------------------------------- 1 | PODS: 2 | - Flutter (1.0.0) 3 | - path_provider_ios (0.0.1): 4 | - Flutter 5 | - shared_preferences_ios (0.0.1): 6 | - Flutter 7 | - webview_flutter_wkwebview (0.0.1): 8 | - Flutter 9 | 10 | DEPENDENCIES: 11 | - Flutter (from `Flutter`) 12 | - path_provider_ios (from `.symlinks/plugins/path_provider_ios/ios`) 13 | - shared_preferences_ios (from `.symlinks/plugins/shared_preferences_ios/ios`) 14 | - webview_flutter_wkwebview (from `.symlinks/plugins/webview_flutter_wkwebview/ios`) 15 | 16 | EXTERNAL SOURCES: 17 | Flutter: 18 | :path: Flutter 19 | path_provider_ios: 20 | :path: ".symlinks/plugins/path_provider_ios/ios" 21 | shared_preferences_ios: 22 | :path: ".symlinks/plugins/shared_preferences_ios/ios" 23 | webview_flutter_wkwebview: 24 | :path: ".symlinks/plugins/webview_flutter_wkwebview/ios" 25 | 26 | SPEC CHECKSUMS: 27 | Flutter: 50d75fe2f02b26cc09d224853bb45737f8b3214a 28 | path_provider_ios: 14f3d2fd28c4fdb42f44e0f751d12861c43cee02 29 | shared_preferences_ios: 548a61f8053b9b8a49ac19c1ffbc8b92c50d68ad 30 | webview_flutter_wkwebview: b7e70ef1ddded7e69c796c7390ee74180182971f 31 | 32 | PODFILE CHECKSUM: aafe91acc616949ddb318b77800a7f51bffa2a4c 33 | 34 | COCOAPODS: 1.11.2 35 | -------------------------------------------------------------------------------- /lib/src/model/local_server_client_config_item.dart: -------------------------------------------------------------------------------- 1 | /// local server options 配置model 2 | class LocalServerClientConfigItem { 3 | /// H5 路径标识 4 | String? key; 5 | 6 | /// 该路径是否下载完毕 7 | bool? isAssetsDone; 8 | 9 | /// 该路径优先级 10 | int priority = 0; 11 | 12 | /// 版本 13 | String? version; 14 | 15 | LocalServerClientConfigItem({this.key, this.isAssetsDone, this.version, this.priority = 0}); 16 | 17 | static LocalServerClientConfigItem? parse(Map json) { 18 | if (json['open'] == null || json['open'] == 0) { 19 | return null; 20 | } 21 | return LocalServerClientConfigItem() 22 | ..isAssetsDone = false 23 | ..key = json['key'] 24 | ..priority = json['priority'] ?? 0 25 | ..version = json['version']; 26 | } 27 | 28 | LocalServerClientConfigItem.fromJson(Map json) { 29 | isAssetsDone = json['isAssetsDone']; 30 | key = json['key']; 31 | priority = json['priority'] ?? 0; 32 | version = json['version']; 33 | } 34 | 35 | Map toJson() { 36 | Map data = {}; 37 | data['isAssetsDone'] = isAssetsDone; 38 | data['key'] = key; 39 | data['priority'] = priority; 40 | data['version'] = version; 41 | return data; 42 | } 43 | 44 | } -------------------------------------------------------------------------------- /example/lib/tools/local_server_webview_manager.dart: -------------------------------------------------------------------------------- 1 | import 'package:local_server_for_webview/local_server_for_webview.dart'; 2 | 3 | class LocalServerWebViewManager extends LocalServerClientManager { 4 | 5 | factory LocalServerWebViewManager() => _getInstance(); 6 | 7 | static LocalServerWebViewManager get instance => _getInstance(); 8 | static LocalServerWebViewManager? _instance; 9 | 10 | static LocalServerWebViewManager _getInstance() { 11 | _instance ??= LocalServerWebViewManager._internal(); 12 | return _instance!; 13 | } 14 | 15 | LocalServerWebViewManager._internal(); 16 | 17 | /// 测试的配置 18 | void initSetting() { 19 | init(); 20 | LocalServerCacheBinderSetting.instance.setBaseHost('https://jomin-web.web.app'); 21 | Map baCache = {'common': {'compress': '/local-server/common.zip', "version": "20220503"}}; 22 | LocalServerClientConfig localServerClientConfig = LocalServerClientConfig.fromJson({ 23 | 'option': [{'key': 'test-one', 'open': 1, 'priority': 0, "version": "20220503"}], 24 | 'assets': { 25 | 'test-one': {'compress': '/local-server/test-one.zip'} 26 | }, 27 | 'basics': baCache, 28 | }); 29 | prepareManager(localServerClientConfig); 30 | startLocalServer(); 31 | } 32 | 33 | } -------------------------------------------------------------------------------- /example/ios/Podfile: -------------------------------------------------------------------------------- 1 | # Uncomment this line to define a global platform for your project 2 | # platform :ios, '9.0' 3 | 4 | # CocoaPods analytics sends network stats synchronously affecting flutter build latency. 5 | ENV['COCOAPODS_DISABLE_STATS'] = 'true' 6 | 7 | project 'Runner', { 8 | 'Debug' => :debug, 9 | 'Profile' => :release, 10 | 'Release' => :release, 11 | } 12 | 13 | def flutter_root 14 | generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'Generated.xcconfig'), __FILE__) 15 | unless File.exist?(generated_xcode_build_settings_path) 16 | raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure flutter pub get is executed first" 17 | end 18 | 19 | File.foreach(generated_xcode_build_settings_path) do |line| 20 | matches = line.match(/FLUTTER_ROOT\=(.*)/) 21 | return matches[1].strip if matches 22 | end 23 | raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Generated.xcconfig, then run flutter pub get" 24 | end 25 | 26 | require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root) 27 | 28 | flutter_ios_podfile_setup 29 | 30 | target 'Runner' do 31 | use_frameworks! 32 | use_modular_headers! 33 | 34 | flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__)) 35 | end 36 | 37 | post_install do |installer| 38 | installer.pods_project.targets.each do |target| 39 | flutter_additional_ios_build_settings(target) 40 | end 41 | end 42 | -------------------------------------------------------------------------------- /example/analysis_options.yaml: -------------------------------------------------------------------------------- 1 | # This file configures the analyzer, which statically analyzes Dart code to 2 | # check for errors, warnings, and lints. 3 | # 4 | # The issues identified by the analyzer are surfaced in the UI of Dart-enabled 5 | # IDEs (https://dart.dev/tools#ides-and-editors). The analyzer can also be 6 | # invoked from the command line by running `flutter analyze`. 7 | 8 | # The following line activates a set of recommended lints for Flutter apps, 9 | # packages, and plugins designed to encourage good coding practices. 10 | include: package:flutter_lints/flutter.yaml 11 | 12 | linter: 13 | # The lint rules applied to this project can be customized in the 14 | # section below to disable rules from the `package:flutter_lints/flutter.yaml` 15 | # included above or to enable additional rules. A list of all available lints 16 | # and their documentation is published at 17 | # https://dart-lang.github.io/linter/lints/index.html. 18 | # 19 | # Instead of disabling a lint rule for the entire project in the 20 | # section below, it can also be suppressed for a single line of code 21 | # or a specific dart file by using the `// ignore: name_of_lint` and 22 | # `// ignore_for_file: name_of_lint` syntax on the line or in the file 23 | # producing the lint. 24 | rules: 25 | # avoid_print: false # Uncomment to disable the `avoid_print` rule 26 | # prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule 27 | 28 | # Additional information about this file can be found at 29 | # https://dart.dev/guides/language/analysis-options 30 | -------------------------------------------------------------------------------- /example/ios/Runner/Base.lproj/Main.storyboard: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /lib/src/model/download_service_total_asset_item.dart: -------------------------------------------------------------------------------- 1 | import 'package:local_server_for_webview/local_server_for_webview.dart'; 2 | 3 | class DownloadServiceTotalAssetItem { 4 | String h5Path = ''; 5 | bool isAssetsDone = false; 6 | List assets = []; 7 | 8 | DownloadServiceTotalAssetItem.fromConfigCenter(Map json, String keyPath) { 9 | h5Path = keyPath; 10 | DownloadServiceItem _createItem(String url, bool isCom) { 11 | return DownloadServiceItem() 12 | ..h5Path = h5Path 13 | ..zipUrl = LocalServerConfiguration.downloadUrl(url) 14 | ..downloadCount = 0 15 | ..loadState = LoadStateType.unLoad 16 | ..isCompress = isCom 17 | ..filePath = []; 18 | } 19 | 20 | List tmPAssets = []; 21 | if (json['compress'] != null) { 22 | tmPAssets.add(_createItem(json['compress'], true)); 23 | } 24 | if (json['deps'] != null) { 25 | List deps = json['deps']; 26 | var tempDeps = deps.toList().map((e) => _createItem(e, false)).toList(); 27 | tmPAssets.addAll(tempDeps); 28 | } 29 | assets = tmPAssets; 30 | } 31 | 32 | DownloadServiceTotalAssetItem.fromJson(Map json) { 33 | h5Path = json['h5Path']; 34 | isAssetsDone = json['isAssetsDone']; 35 | if (json['assets'] != null) { 36 | List tmpAssets = json['assets']; 37 | assets = tmpAssets.map((e) => DownloadServiceItem.fromJson(e)).toList(); 38 | } 39 | } 40 | 41 | Map toJson() { 42 | Map data = {}; 43 | data['h5Path'] = h5Path; 44 | data['isAssetsDone'] = isAssetsDone; 45 | if (assets.isNotEmpty) { 46 | data['assets'] = assets.map((e) => e.toJson()).toList(); 47 | } 48 | return data; 49 | } 50 | } -------------------------------------------------------------------------------- /example/android/app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 3 | 8 | 16 | 20 | 24 | 25 | 26 | 27 | 28 | 29 | 31 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /example/ios/Runner/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | $(DEVELOPMENT_LANGUAGE) 7 | CFBundleDisplayName 8 | Example 9 | CFBundleExecutable 10 | $(EXECUTABLE_NAME) 11 | CFBundleIdentifier 12 | $(PRODUCT_BUNDLE_IDENTIFIER) 13 | CFBundleInfoDictionaryVersion 14 | 6.0 15 | CFBundleName 16 | example 17 | CFBundlePackageType 18 | APPL 19 | CFBundleShortVersionString 20 | $(FLUTTER_BUILD_NAME) 21 | CFBundleSignature 22 | ???? 23 | CFBundleVersion 24 | $(FLUTTER_BUILD_NUMBER) 25 | LSRequiresIPhoneOS 26 | 27 | NSAppTransportSecurity 28 | 29 | NSAllowsArbitraryLoads 30 | 31 | 32 | UILaunchStoryboardName 33 | LaunchScreen 34 | UIMainStoryboardFile 35 | Main 36 | UISupportedInterfaceOrientations 37 | 38 | UIInterfaceOrientationPortrait 39 | UIInterfaceOrientationLandscapeLeft 40 | UIInterfaceOrientationLandscapeRight 41 | 42 | UISupportedInterfaceOrientations~ipad 43 | 44 | UIInterfaceOrientationPortrait 45 | UIInterfaceOrientationPortraitUpsideDown 46 | UIInterfaceOrientationLandscapeLeft 47 | UIInterfaceOrientationLandscapeRight 48 | 49 | UIViewControllerBasedStatusBarAppearance 50 | 51 | 52 | 53 | -------------------------------------------------------------------------------- /pubspec.yaml: -------------------------------------------------------------------------------- 1 | name: local_server_for_webview 2 | description: flutter local server for webview 3 | version: 0.0.1 4 | homepage: '' 5 | 6 | environment: 7 | sdk: ">=2.12.0 <3.0.0" 8 | flutter: ">=1.17.0" 9 | 10 | dependencies: 11 | flutter: 12 | sdk: flutter 13 | 14 | path: ^1.8.0 15 | http: ^0.13.4 16 | path_provider: ^2.0.9 17 | dio: ^4.0.6 18 | archive: ^3.3.0 19 | shared_preferences: ^2.0.13 20 | mime: ^1.0.1 21 | uuid: ^3.0.6 22 | 23 | dev_dependencies: 24 | flutter_test: 25 | sdk: flutter 26 | flutter_lints: ^1.0.0 27 | 28 | # For information on the generic Dart part of this file, see the 29 | # following page: https://dart.dev/tools/pub/pubspec 30 | 31 | # The following section is specific to Flutter. 32 | flutter: 33 | 34 | # To add assets to your package, add an assets section, like this: 35 | # assets: 36 | # - images/a_dot_burr.jpeg 37 | # - images/a_dot_ham.jpeg 38 | # 39 | # For details regarding assets in packages, see 40 | # https://flutter.dev/assets-and-images/#from-packages 41 | # 42 | # An image asset can refer to one or more resolution-specific "variants", see 43 | # https://flutter.dev/assets-and-images/#resolution-aware. 44 | 45 | # To add custom fonts to your package, add a fonts section here, 46 | # in this "flutter" section. Each entry in this list should have a 47 | # "family" key with the font family name, and a "fonts" key with a 48 | # list giving the asset and other descriptors for the font. For 49 | # example: 50 | # fonts: 51 | # - family: Schyler 52 | # fonts: 53 | # - asset: fonts/Schyler-Regular.ttf 54 | # - asset: fonts/Schyler-Italic.ttf 55 | # style: italic 56 | # - family: Trajan Pro 57 | # fonts: 58 | # - asset: fonts/TrajanPro.ttf 59 | # - asset: fonts/TrajanPro_Bold.ttf 60 | # weight: 700 61 | # 62 | # For details regarding fonts in packages, see 63 | # https://flutter.dev/custom-fonts/#from-packages 64 | -------------------------------------------------------------------------------- /example/lib/main.dart: -------------------------------------------------------------------------------- 1 | import 'package:example/tools/local_server_webview_manager.dart'; 2 | import 'package:example/web_page.dart'; 3 | import 'package:flutter/material.dart'; 4 | 5 | void main() { 6 | runApp(const MyApp()); 7 | } 8 | 9 | class MyApp extends StatelessWidget { 10 | const MyApp({Key? key}) : super(key: key); 11 | 12 | // This widget is the root of your application. 13 | @override 14 | Widget build(BuildContext context) { 15 | return MaterialApp( 16 | title: 'Flutter Demo', 17 | theme: ThemeData( 18 | primarySwatch: Colors.blue, 19 | ), 20 | home: const MyHomePage(title: 'Flutter Demo Home Page'), 21 | ); 22 | } 23 | } 24 | 25 | class MyHomePage extends StatefulWidget { 26 | const MyHomePage({Key? key, required this.title}) : super(key: key); 27 | 28 | final String title; 29 | 30 | @override 31 | State createState() => _MyHomePageState(); 32 | } 33 | 34 | class _MyHomePageState extends State { 35 | 36 | final String testUrl = "https://jomin-web.web.app/test-one/index.html"; 37 | 38 | @override 39 | void initState() { 40 | super.initState(); 41 | LocalServerWebViewManager.instance.initSetting(); 42 | } 43 | 44 | @override 45 | void dispose() { 46 | 47 | super.dispose(); 48 | } 49 | 50 | @override 51 | Widget build(BuildContext context) { 52 | return Scaffold( 53 | appBar: AppBar( 54 | title: Text(widget.title), 55 | ), 56 | body: Center( 57 | child: GestureDetector( 58 | onTap: () { 59 | Navigator.push( 60 | context, 61 | MaterialPageRoute( 62 | builder: (_) => WebPage( 63 | url: testUrl, 64 | ), 65 | ), 66 | ); 67 | }, 68 | child: const Text( 69 | 'Open The WebView', 70 | style: TextStyle( 71 | fontSize: 20, 72 | ), 73 | ), 74 | ), 75 | ), 76 | ); 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /example/android/app/build.gradle: -------------------------------------------------------------------------------- 1 | def localProperties = new Properties() 2 | def localPropertiesFile = rootProject.file('local.properties') 3 | if (localPropertiesFile.exists()) { 4 | localPropertiesFile.withReader('UTF-8') { reader -> 5 | localProperties.load(reader) 6 | } 7 | } 8 | 9 | def flutterRoot = localProperties.getProperty('flutter.sdk') 10 | if (flutterRoot == null) { 11 | throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.") 12 | } 13 | 14 | def flutterVersionCode = localProperties.getProperty('flutter.versionCode') 15 | if (flutterVersionCode == null) { 16 | flutterVersionCode = '1' 17 | } 18 | 19 | def flutterVersionName = localProperties.getProperty('flutter.versionName') 20 | if (flutterVersionName == null) { 21 | flutterVersionName = '1.0' 22 | } 23 | 24 | apply plugin: 'com.android.application' 25 | apply plugin: 'kotlin-android' 26 | apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle" 27 | 28 | android { 29 | compileSdkVersion flutter.compileSdkVersion 30 | 31 | compileOptions { 32 | sourceCompatibility JavaVersion.VERSION_1_8 33 | targetCompatibility JavaVersion.VERSION_1_8 34 | } 35 | 36 | kotlinOptions { 37 | jvmTarget = '1.8' 38 | } 39 | 40 | sourceSets { 41 | main.java.srcDirs += 'src/main/kotlin' 42 | } 43 | 44 | defaultConfig { 45 | // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). 46 | applicationId "com.example.example" 47 | minSdkVersion 21 48 | targetSdkVersion flutter.targetSdkVersion 49 | versionCode flutterVersionCode.toInteger() 50 | versionName flutterVersionName 51 | } 52 | 53 | buildTypes { 54 | release { 55 | // TODO: Add your own signing config for the release build. 56 | // Signing with the debug keys for now, so `flutter run --release` works. 57 | signingConfig signingConfigs.debug 58 | } 59 | } 60 | } 61 | 62 | flutter { 63 | source '../..' 64 | } 65 | 66 | dependencies { 67 | implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" 68 | } 69 | -------------------------------------------------------------------------------- /lib/src/model/download_service_item.dart: -------------------------------------------------------------------------------- 1 | 2 | import 'package:local_server_for_webview/local_server_for_webview.dart'; 3 | 4 | /// zip下载状态 5 | enum LoadStateType { 6 | // 未下载 7 | unLoad, 8 | // 加载中 9 | loading, 10 | // 已下载 11 | success, 12 | // 下载失败 13 | failure, 14 | } 15 | 16 | class DownloadServiceItem { 17 | 18 | /// H5路径 19 | String h5Path = ''; 20 | 21 | /// zip 压缩 url 22 | String zipUrl = ''; 23 | 24 | /// 下载次数 25 | int downloadCount = 0; 26 | 27 | /// 下载状态 28 | LoadStateType loadState = LoadStateType.unLoad; 29 | 30 | /// file path 31 | List filePath = []; 32 | 33 | /// 是否为Compress路径 34 | bool isCompress = false; 35 | 36 | String? version; 37 | 38 | DownloadServiceItem(); 39 | 40 | DownloadServiceItem.fromJson(Map json) { 41 | h5Path = json['h5Path']; 42 | zipUrl = LocalServerConfiguration.downloadUrl(json['zipUrl']); 43 | isCompress = json['isCompress']; 44 | downloadCount = json['downloadCount']; 45 | loadState = LoadStateType.values[json['loadState'] ?? 0]; 46 | if (json['filePath'] != null && json['filePath'] is List) { 47 | filePath = json['filePath'].cast(); 48 | } 49 | version = json['version']; 50 | } 51 | 52 | void replaceLoadState(DownloadServiceItem oldItem) { 53 | downloadCount = oldItem.downloadCount; 54 | filePath = oldItem.filePath; 55 | loadState = oldItem.loadState; 56 | version = oldItem.version; 57 | } 58 | 59 | void replaceFull(DownloadServiceItem oldItem) { 60 | downloadCount = oldItem.downloadCount; 61 | filePath = oldItem.filePath; 62 | loadState = oldItem.loadState; 63 | h5Path = oldItem.h5Path; 64 | zipUrl = LocalServerConfiguration.downloadUrl(oldItem.zipUrl); 65 | downloadCount = oldItem.downloadCount; 66 | filePath = oldItem.filePath; 67 | isCompress = oldItem.isCompress; 68 | version = oldItem.version; 69 | } 70 | 71 | Map toJson() { 72 | Map data = {}; 73 | data['h5Path'] = h5Path; 74 | data['zipUrl'] = LocalServerConfiguration.downloadUrl(zipUrl); 75 | data['downloadCount'] = downloadCount; 76 | data['loadState'] = loadState.index; 77 | data['filePath'] = filePath; 78 | data['isCompress'] = isCompress; 79 | data['version'] = version; 80 | return data; 81 | } 82 | 83 | } -------------------------------------------------------------------------------- /example/lib/web_page.dart: -------------------------------------------------------------------------------- 1 | import 'dart:developer'; 2 | 3 | import 'package:example/tools/local_server_webview_manager.dart'; 4 | import 'package:flutter/material.dart'; 5 | import 'package:local_server_for_webview/local_server_for_webview.dart'; 6 | import 'package:webview_flutter/webview_flutter.dart'; 7 | 8 | class WebPage extends StatefulWidget { 9 | const WebPage({Key? key, required this.url}) : super(key: key); 10 | final String url; 11 | 12 | @override 13 | State createState() => _WebPageState(); 14 | 15 | } 16 | 17 | class _WebPageState extends State { 18 | 19 | // Local server 管理 20 | late LocalServerCacheBinder _localServerBuilder; 21 | WebViewController? webViewController; 22 | String _innerUrl = ''; 23 | String _title = ''; 24 | 25 | @override 26 | void initState() { 27 | super.initState(); 28 | log('页面开始加载:${DateTime.now()}', name: 'web-time'); 29 | _localServerBuilder = LocalServerCacheBinder()..initBinder(); 30 | LocalServerWebViewManager.instance.registerBuilder(_localServerBuilder); 31 | _innerUrl = _localServerBuilder.convertH5Url2LocalServerUrl(widget.url); 32 | } 33 | 34 | @override 35 | void dispose() { 36 | LocalServerWebViewManager.instance.resignBuilder(_localServerBuilder); 37 | _localServerBuilder.dispose(); 38 | super.dispose(); 39 | } 40 | 41 | @override 42 | Widget build(BuildContext context) { 43 | return Scaffold( 44 | appBar: AppBar( 45 | title: Text( 46 | _title, 47 | ), 48 | ), 49 | body: WebView( 50 | initialUrl: _innerUrl, 51 | debuggingEnabled: true, 52 | onPageStarted: (url) { 53 | print("onPageStarted($url) ----------------------"); 54 | log('Web开始加载:${DateTime.now()}', name: 'web-time'); 55 | }, 56 | onPageFinished: (url) { 57 | print("onPageFinished($url) ----------------------"); 58 | log('Web加载完成:${DateTime.now()}', name: 'web-time'); 59 | }, 60 | onWebViewCreated: (controller) async { 61 | webViewController = controller; 62 | webViewController!.getTitle().then((value) { 63 | setState(() { 64 | _title = value ?? ''; 65 | }); 66 | }); 67 | }, 68 | javascriptMode: JavascriptMode.unrestricted, 69 | ), 70 | ); 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /example/ios/Runner/Base.lproj/LaunchScreen.storyboard: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | -------------------------------------------------------------------------------- /example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "images" : [ 3 | { 4 | "size" : "20x20", 5 | "idiom" : "iphone", 6 | "filename" : "Icon-App-20x20@2x.png", 7 | "scale" : "2x" 8 | }, 9 | { 10 | "size" : "20x20", 11 | "idiom" : "iphone", 12 | "filename" : "Icon-App-20x20@3x.png", 13 | "scale" : "3x" 14 | }, 15 | { 16 | "size" : "29x29", 17 | "idiom" : "iphone", 18 | "filename" : "Icon-App-29x29@1x.png", 19 | "scale" : "1x" 20 | }, 21 | { 22 | "size" : "29x29", 23 | "idiom" : "iphone", 24 | "filename" : "Icon-App-29x29@2x.png", 25 | "scale" : "2x" 26 | }, 27 | { 28 | "size" : "29x29", 29 | "idiom" : "iphone", 30 | "filename" : "Icon-App-29x29@3x.png", 31 | "scale" : "3x" 32 | }, 33 | { 34 | "size" : "40x40", 35 | "idiom" : "iphone", 36 | "filename" : "Icon-App-40x40@2x.png", 37 | "scale" : "2x" 38 | }, 39 | { 40 | "size" : "40x40", 41 | "idiom" : "iphone", 42 | "filename" : "Icon-App-40x40@3x.png", 43 | "scale" : "3x" 44 | }, 45 | { 46 | "size" : "60x60", 47 | "idiom" : "iphone", 48 | "filename" : "Icon-App-60x60@2x.png", 49 | "scale" : "2x" 50 | }, 51 | { 52 | "size" : "60x60", 53 | "idiom" : "iphone", 54 | "filename" : "Icon-App-60x60@3x.png", 55 | "scale" : "3x" 56 | }, 57 | { 58 | "size" : "20x20", 59 | "idiom" : "ipad", 60 | "filename" : "Icon-App-20x20@1x.png", 61 | "scale" : "1x" 62 | }, 63 | { 64 | "size" : "20x20", 65 | "idiom" : "ipad", 66 | "filename" : "Icon-App-20x20@2x.png", 67 | "scale" : "2x" 68 | }, 69 | { 70 | "size" : "29x29", 71 | "idiom" : "ipad", 72 | "filename" : "Icon-App-29x29@1x.png", 73 | "scale" : "1x" 74 | }, 75 | { 76 | "size" : "29x29", 77 | "idiom" : "ipad", 78 | "filename" : "Icon-App-29x29@2x.png", 79 | "scale" : "2x" 80 | }, 81 | { 82 | "size" : "40x40", 83 | "idiom" : "ipad", 84 | "filename" : "Icon-App-40x40@1x.png", 85 | "scale" : "1x" 86 | }, 87 | { 88 | "size" : "40x40", 89 | "idiom" : "ipad", 90 | "filename" : "Icon-App-40x40@2x.png", 91 | "scale" : "2x" 92 | }, 93 | { 94 | "size" : "76x76", 95 | "idiom" : "ipad", 96 | "filename" : "Icon-App-76x76@1x.png", 97 | "scale" : "1x" 98 | }, 99 | { 100 | "size" : "76x76", 101 | "idiom" : "ipad", 102 | "filename" : "Icon-App-76x76@2x.png", 103 | "scale" : "2x" 104 | }, 105 | { 106 | "size" : "83.5x83.5", 107 | "idiom" : "ipad", 108 | "filename" : "Icon-App-83.5x83.5@2x.png", 109 | "scale" : "2x" 110 | }, 111 | { 112 | "size" : "1024x1024", 113 | "idiom" : "ios-marketing", 114 | "filename" : "Icon-App-1024x1024@1x.png", 115 | "scale" : "1x" 116 | } 117 | ], 118 | "info" : { 119 | "version" : 1, 120 | "author" : "xcode" 121 | } 122 | } 123 | -------------------------------------------------------------------------------- /example/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme: -------------------------------------------------------------------------------- 1 | 2 | 5 | 8 | 9 | 15 | 21 | 22 | 23 | 24 | 25 | 30 | 31 | 37 | 38 | 39 | 40 | 41 | 42 | 52 | 54 | 60 | 61 | 62 | 63 | 69 | 71 | 77 | 78 | 79 | 80 | 82 | 83 | 86 | 87 | 88 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | HttpServer 对于Webview预加载、拦截替换资源的Flutter实现。优化Webview的首次加载时间、白屏时间。 2 | 3 | ## Pub get 4 | ```yaml 5 | local_server_for_webview: 6 | git: 7 | url: https://github.com/EchoPuda/local_server_webview.git 8 | ``` 9 | ## Usage 10 | 11 | 继承LocalServerClientManager, 初始化并配置载入LocalServerClientConfig,最后在合适的时机startLocalServer() 12 | ```dart 13 | import 'package:local_server_for_webview/local_server_for_webview.dart'; 14 | 15 | class LocalServerWebViewManager extends LocalServerClientManager { 16 | 17 | factory LocalServerWebViewManager() => _getInstance(); 18 | 19 | static LocalServerWebViewManager get instance => _getInstance(); 20 | static LocalServerWebViewManager? _instance; 21 | 22 | static LocalServerWebViewManager _getInstance() { 23 | _instance ??= LocalServerWebViewManager._internal(); 24 | return _instance!; 25 | } 26 | 27 | LocalServerWebViewManager._internal(); 28 | 29 | /// 测试的配置 30 | void initSetting() { 31 | init(); 32 | LocalServerCacheBinderSetting.instance.setBaseHost('https://jomin-web.web.app'); 33 | Map baCache = {'common': {'compress': '/local-server/common.zip', "version": "20220503"}}; 34 | LocalServerClientConfig localServerClientConfig = LocalServerClientConfig.fromJson({ 35 | 'option': [{'key': 'test-one', 'open': 1, 'priority': 0, "version": "20220503"}], 36 | 'assets': { 37 | 'test-one': {'compress': '/local-server/test-one.zip'} 38 | }, 39 | 'basics': baCache, 40 | }); 41 | prepareManager(localServerClientConfig); 42 | startLocalServer(); 43 | } 44 | 45 | } 46 | ``` 47 | 48 | 在WebView页面中,绑定LocalServerCacheBinder到Manager中。然后获取转换后的LocalServerUrl,最后由WebView加载展示。 49 | ```dart 50 | class _WebPageState extends State { 51 | 52 | // Local server 管理 53 | late LocalServerCacheBinder _localServerBuilder; 54 | WebViewController? webViewController; 55 | String _innerUrl = ''; 56 | String _title = ''; 57 | 58 | @override 59 | void initState() { 60 | super.initState(); 61 | log('页面开始加载:${DateTime.now()}', name: 'web-time'); 62 | _localServerBuilder = LocalServerCacheBinder()..initBinder(); 63 | LocalServerWebViewManager.instance.registerBuilder(_localServerBuilder); 64 | _innerUrl = _localServerBuilder.convertH5Url2LocalServerUrl(widget.url); 65 | } 66 | 67 | @override 68 | void dispose() { 69 | LocalServerWebViewManager.instance.resignBuilder(_localServerBuilder); 70 | _localServerBuilder.dispose(); 71 | super.dispose(); 72 | } 73 | 74 | @override 75 | Widget build(BuildContext context) { 76 | return Scaffold( 77 | appBar: AppBar( 78 | title: Text( 79 | _title, 80 | ), 81 | ), 82 | body: WebView( 83 | initialUrl: _innerUrl, 84 | debuggingEnabled: true, 85 | onPageStarted: (url) { 86 | print("onPageStarted($url) ----------------------"); 87 | log('Web开始加载:${DateTime.now()}', name: 'web-time'); 88 | }, 89 | onPageFinished: (url) { 90 | print("onPageFinished($url) ----------------------"); 91 | log('Web加载完成:${DateTime.now()}', name: 'web-time'); 92 | }, 93 | onWebViewCreated: (controller) async { 94 | webViewController = controller; 95 | webViewController!.getTitle().then((value) { 96 | setState(() { 97 | _title = value ?? ''; 98 | }); 99 | }); 100 | }, 101 | javascriptMode: JavascriptMode.unrestricted, 102 | ), 103 | ); 104 | } 105 | } 106 | ``` 107 | 108 | 在不用的时候记得关闭LocalServer 109 | 110 | -------------------------------------------------------------------------------- /lib/src/services/local_server_configuration.dart: -------------------------------------------------------------------------------- 1 | import 'dart:convert'; 2 | import 'dart:io'; 3 | 4 | import 'package:local_server_for_webview/tools/local_server_binder.dart'; 5 | import 'package:path_provider/path_provider.dart'; 6 | 7 | /// 本地文件缓存目录管理 8 | class LocalServerConfiguration { 9 | 10 | static String? cacheDirectory; 11 | static Directory? distDirectory; 12 | static String kFileName = 'app_web_cache'; 13 | static String kFileNameDist = 'app_web_cache/dist'; 14 | static String kFileBasic = 'app_web_cache/basic'; 15 | 16 | /// basic 统一文件类的存放目录 17 | static Future getBasicFile(String keyPath) async { 18 | Directory directory; 19 | if (cacheDirectory != null) { 20 | directory = Directory(cacheDirectory!); 21 | } else { 22 | directory = await getTemporaryDirectory(); 23 | cacheDirectory = directory.path; 24 | } 25 | String distPath = directory.path + '/$kFileBasic' + '/$keyPath'; 26 | final tmpFile = File(distPath); 27 | if (tmpFile.existsSync()) { 28 | return tmpFile; 29 | } else { 30 | try { 31 | final tmpDir = await tmpFile.create(recursive: true); 32 | return tmpDir; 33 | } catch(e) { 34 | rethrow; 35 | } 36 | } 37 | } 38 | 39 | /// dist 各项目的存放目录 40 | static Future getDistDirectory() async { 41 | Directory directory; 42 | if (distDirectory != null) { 43 | return distDirectory!; 44 | } 45 | if (cacheDirectory != null) { 46 | directory = Directory(cacheDirectory!); 47 | } else { 48 | directory = await getTemporaryDirectory(); 49 | cacheDirectory = directory.path + '/$kFileName'; 50 | } 51 | String distPath = directory.path + '/$kFileNameDist'; 52 | final tmpDirectory = Directory(distPath); 53 | if (tmpDirectory.existsSync()) { 54 | distDirectory = tmpDirectory; 55 | return tmpDirectory; 56 | } else { 57 | try { 58 | final tmpDir = await tmpDirectory.create(recursive: true); 59 | distDirectory = tmpDir; 60 | return tmpDir; 61 | } catch(e) { 62 | rethrow; 63 | } 64 | } 65 | } 66 | 67 | /// 检查当前项目是否已经存在 68 | static Future checkZipPathDirectoryIsExist(String zippurl) async { 69 | String zipTmpPath = base64Encode(utf8.encode(zippurl)); 70 | final dist = await getDistDirectory(); 71 | String zipPath = dist.path + '/' + zipTmpPath; 72 | final checkDirect = Directory(zipPath); 73 | return checkDirect.existsSync(); 74 | } 75 | 76 | /// 返回对应路径 77 | static String joinZipPathSync(String zipUrl, String fileName) { 78 | Directory tmpDir = getCurrentZipPathSyncDirectory(zipUrl); 79 | if (fileName.isEmpty) { 80 | return tmpDir.path; 81 | } 82 | return tmpDir.path + '/' + fileName; 83 | } 84 | 85 | /// 返回对应目录 86 | static Directory getCurrentZipPathSyncDirectory(String zipUrl, {bool isExist = false}) { 87 | String zipTmpPath = base64Encode(utf8.encode(zipUrl)); 88 | final dist = distDirectory!; 89 | String zipPath = dist.path + '/' + zipTmpPath; 90 | final checkDirect = Directory(zipPath); 91 | return checkDirect; 92 | } 93 | 94 | /// 处理为完整的下载downloadUrl 95 | /// 必须配置 [LocalServerCacheBinderSetting.instance.baseDomain] 96 | static String downloadUrl(String url) { 97 | String downUrl = url; 98 | if (!downUrl.startsWith('http') && !downUrl.startsWith('https')) { 99 | if (!downUrl.startsWith("/")) { 100 | downUrl = "/" + downUrl; 101 | } 102 | downUrl = LocalServerCacheBinderSetting.instance.baseDomain + downUrl; 103 | } 104 | return downUrl; 105 | } 106 | 107 | } -------------------------------------------------------------------------------- /lib/tools/local_server_config_cache.dart: -------------------------------------------------------------------------------- 1 | import 'dart:convert'; 2 | import 'dart:developer'; 3 | 4 | import 'package:flutter/foundation.dart'; 5 | import 'package:local_server_for_webview/src/model/download_service_item.dart'; 6 | import 'package:local_server_for_webview/src/model/download_service_total_asset_item.dart'; 7 | import 'package:local_server_for_webview/src/model/local_server_client_config_item.dart'; 8 | import 'package:shared_preferences/shared_preferences.dart'; 9 | 10 | /// 相应的配置本地存储 11 | class LocalServerConfigCache { 12 | 13 | static const String _optionKey = 'local_options_key'; 14 | static const String _basicKey = 'local_basic_key'; 15 | static const String _assetsKey = 'local_assets_key'; 16 | static SharedPreferences? _sp; 17 | static Future get getSp async { 18 | if (_sp != null) { 19 | return _sp!; 20 | } else { 21 | _sp = await SharedPreferences.getInstance(); 22 | return _sp!; 23 | } 24 | } 25 | 26 | static Future setOptions(List items) async { 27 | List> jsonList = items.map((e) => e.toJson()).toList(); 28 | _saveJson(_optionKey, jsonList); 29 | } 30 | 31 | static Future?> getOptions() async { 32 | List? res = await _getJson(_optionKey); 33 | if (res == null) { 34 | return null; 35 | } 36 | List> decode = res.cast>().toList(); 37 | var optionList = decode.map((e) => LocalServerClientConfigItem.fromJson(e)).toList(); 38 | return optionList; 39 | } 40 | 41 | static Future setBasic(List basic) async { 42 | List> jsonList = basic.map((e) => e.toJson()).toList(); 43 | _saveJson(_basicKey, jsonList); 44 | } 45 | 46 | static Future?> getBasic() async { 47 | List? res = await _getJson(_basicKey); 48 | if (res == null) { 49 | return null; 50 | } 51 | List> decode = res.cast>().toList(); 52 | var basicList = decode.map((e) => DownloadServiceItem.fromJson(e)).toList(); 53 | return basicList; 54 | } 55 | 56 | static Future setAssets(Map map) async { 57 | Map saveJson = map.map((key, value) => MapEntry(key, json.encode(value.toJson()))); 58 | String saveData = json.encode(saveJson); 59 | _saveJson(_assetsKey, saveData); 60 | } 61 | 62 | static Future?> getAssets() async { 63 | String? decodeStr = await _getJson(_assetsKey); 64 | if (decodeStr == null) { 65 | return null; 66 | } 67 | 68 | try { 69 | Map saveJson = json.decode(decodeStr); 70 | var res = saveJson.map((key, value) => MapEntry(key, DownloadServiceTotalAssetItem.fromJson(json.decode(value)))); 71 | return res; 72 | } catch(e) { 73 | _log(e.toString()); 74 | rethrow; 75 | } 76 | } 77 | 78 | static void _saveJson(String key, Object jsonString) async { 79 | var sp = await getSp; 80 | if (jsonString is String) { 81 | sp.setString(key, jsonString); 82 | } else { 83 | var res = json.encode(jsonString); 84 | sp.setString(key, res); 85 | } 86 | } 87 | 88 | /// List, Map 转换不了里面的具体对象 89 | static Future _getJson(String key) async { 90 | var sp = await getSp; 91 | var res = sp.getString(key); 92 | if (res == null) { 93 | return null; 94 | } 95 | if (T == String) { 96 | return res as T; 97 | } 98 | return json.decode(res) as T; 99 | } 100 | 101 | static void _log(Object msg) { 102 | if (!kReleaseMode) { 103 | log(msg.toString(), name: 'Local Service Cache'); 104 | } 105 | } 106 | 107 | } -------------------------------------------------------------------------------- /example/pubspec.yaml: -------------------------------------------------------------------------------- 1 | name: example 2 | description: A new Flutter project. 3 | 4 | # The following line prevents the package from being accidentally published to 5 | # pub.dev using `flutter pub publish`. This is preferred for private packages. 6 | publish_to: 'none' # Remove this line if you wish to publish to pub.dev 7 | 8 | # The following defines the version and build number for your application. 9 | # A version number is three numbers separated by dots, like 1.2.43 10 | # followed by an optional build number separated by a +. 11 | # Both the version and the builder number may be overridden in flutter 12 | # build by specifying --build-name and --build-number, respectively. 13 | # In Android, build-name is used as versionName while build-number used as versionCode. 14 | # Read more about Android versioning at https://developer.android.com/studio/publish/versioning 15 | # In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion. 16 | # Read more about iOS versioning at 17 | # https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html 18 | version: 1.0.0+1 19 | 20 | environment: 21 | sdk: ">=2.16.1 <3.0.0" 22 | 23 | # Dependencies specify other packages that your package needs in order to work. 24 | # To automatically upgrade your package dependencies to the latest versions 25 | # consider running `flutter pub upgrade --major-versions`. Alternatively, 26 | # dependencies can be manually updated by changing the version numbers below to 27 | # the latest version available on pub.dev. To see which dependencies have newer 28 | # versions available, run `flutter pub outdated`. 29 | dependencies: 30 | flutter: 31 | sdk: flutter 32 | local_server_for_webview: 33 | path: ../../local_server_for_webview 34 | # webview 35 | webview_flutter: ^2.1.2 36 | 37 | # The following adds the Cupertino Icons font to your application. 38 | # Use with the CupertinoIcons class for iOS style icons. 39 | cupertino_icons: ^1.0.2 40 | 41 | dev_dependencies: 42 | flutter_test: 43 | sdk: flutter 44 | 45 | # The "flutter_lints" package below contains a set of recommended lints to 46 | # encourage good coding practices. The lint set provided by the package is 47 | # activated in the `analysis_options.yaml` file located at the root of your 48 | # package. See that file for information about deactivating specific lint 49 | # rules and activating additional ones. 50 | flutter_lints: ^1.0.0 51 | 52 | # For information on the generic Dart part of this file, see the 53 | # following page: https://dart.dev/tools/pub/pubspec 54 | 55 | # The following section is specific to Flutter. 56 | flutter: 57 | 58 | # The following line ensures that the Material Icons font is 59 | # included with your application, so that you can use the icons in 60 | # the material Icons class. 61 | uses-material-design: true 62 | 63 | # To add assets to your application, add an assets section, like this: 64 | # assets: 65 | # - images/a_dot_burr.jpeg 66 | # - images/a_dot_ham.jpeg 67 | 68 | # An image asset can refer to one or more resolution-specific "variants", see 69 | # https://flutter.dev/assets-and-images/#resolution-aware. 70 | 71 | # For details regarding adding assets from package dependencies, see 72 | # https://flutter.dev/assets-and-images/#from-packages 73 | 74 | # To add custom fonts to your application, add a fonts section here, 75 | # in this "flutter" section. Each entry in this list should have a 76 | # "family" key with the font family name, and a "fonts" key with a 77 | # list giving the asset and other descriptors for the font. For 78 | # example: 79 | # fonts: 80 | # - family: Schyler 81 | # fonts: 82 | # - asset: fonts/Schyler-Regular.ttf 83 | # - asset: fonts/Schyler-Italic.ttf 84 | # style: italic 85 | # - family: Trajan Pro 86 | # fonts: 87 | # - asset: fonts/TrajanPro.ttf 88 | # - asset: fonts/TrajanPro_Bold.ttf 89 | # weight: 700 90 | # 91 | # For details regarding fonts from package dependencies, 92 | # see https://flutter.dev/custom-fonts/#from-packages 93 | -------------------------------------------------------------------------------- /example/web/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | example 33 | 34 | 35 | 36 | 39 | 103 | 104 | 105 | -------------------------------------------------------------------------------- /lib/tools/local_server_binder.dart: -------------------------------------------------------------------------------- 1 | 2 | import 'dart:io'; 3 | 4 | import 'package:local_server_for_webview/src/model/download_service_total_asset_item.dart'; 5 | import 'package:local_server_for_webview/src/model/local_server_client_config.dart'; 6 | import 'package:local_server_for_webview/src/services/local_server_configuration.dart'; 7 | import 'package:local_server_for_webview/src/services/local_server_service.dart'; 8 | 9 | abstract class LocalServerCacheBuilderProtocol { 10 | dynamic findBuilderResource(String path) {} 11 | } 12 | 13 | /// Local Server Binder的配置 14 | class LocalServerCacheBinderSetting { 15 | factory LocalServerCacheBinderSetting() => _getInstance(); 16 | 17 | static LocalServerCacheBinderSetting get instance => _getInstance(); 18 | static LocalServerCacheBinderSetting? _instance; 19 | 20 | LocalServerCacheBinderSetting._internal(); 21 | 22 | static LocalServerCacheBinderSetting _getInstance() { 23 | _instance ??= LocalServerCacheBinderSetting._internal(); 24 | return _instance!; 25 | } 26 | 27 | LocalServerClientConfig? lsClientConfig; 28 | Map? basicCache; 29 | bool unSupportLocalServer = false; 30 | String baseDomain = ""; 31 | 32 | void setConfig(LocalServerClientConfig config) { 33 | lsClientConfig = config; 34 | } 35 | 36 | void setSupportLocalServer(bool supportLocalServer) { 37 | unSupportLocalServer = !supportLocalServer; 38 | } 39 | 40 | void setBasicCache(Map basicCache) { 41 | this.basicCache = basicCache; 42 | } 43 | 44 | void setBaseHost(String domain) { 45 | baseDomain = domain; 46 | } 47 | 48 | } 49 | 50 | /// Binder 主要是在webpage,把当前项目的资源,携带上统一资源的资源指向 51 | /// 返回LocalServer服务对应path的url 52 | class LocalServerCacheBinder implements LocalServerCacheBuilderProtocol { 53 | 54 | LocalServerClientConfig? get lsClientConfig => LocalServerCacheBinderSetting.instance.lsClientConfig; 55 | 56 | Map? get basicCache => LocalServerCacheBinderSetting.instance.basicCache; 57 | 58 | /// 当前webview是否被禁止使用server 59 | bool get unSupportLocalServer => LocalServerCacheBinderSetting.instance.unSupportLocalServer; 60 | 61 | Map assetsCache = {}; 62 | bool isLocalServer = false; 63 | 64 | String currentH5Path = ""; 65 | 66 | void initBinder() { 67 | LocalServerService.instance.referenceCounter++; 68 | } 69 | 70 | void dispose() { 71 | LocalServerService.instance.referenceCounter--; 72 | } 73 | 74 | @override 75 | findBuilderResource(String path) { 76 | return assetsCache[path]; 77 | } 78 | 79 | /// 转换为Local Server 使用的链接 80 | /// 转换失败则返回原链接[h5Path] 81 | String convertH5Url2LocalServerUrl(String h5Path) { 82 | // 无配置或者未打开的话,返回原链接 83 | if (lsClientConfig == null || !lsClientConfig!.isHavePermission) { 84 | return h5Path; 85 | } 86 | // Local Server 未开启 87 | if (unSupportLocalServer) { 88 | isLocalServer = false; 89 | return h5Path; 90 | } 91 | 92 | // options 无配置 93 | if (lsClientConfig!.options.isEmpty) { 94 | return h5Path; 95 | } 96 | 97 | DownloadServiceTotalAssetItem? tmpAsset; 98 | bool hasEmptyFiles = false; 99 | 100 | // 拿到对应的assets资源,和统一资源basic 101 | void _fetchMemorySources(DownloadServiceTotalAssetItem tmpAsset) { 102 | for (var element in tmpAsset.assets) { 103 | for (var filePath in element.filePath) { 104 | String path = LocalServerConfiguration.joinZipPathSync(element.zipUrl, filePath); 105 | File assetFile = File(path); 106 | 107 | if (!assetFile.existsSync()) { 108 | hasEmptyFiles = true; 109 | return; 110 | } 111 | var contents = assetFile.readAsBytesSync(); 112 | List splits = assetFile.path.split('/'); 113 | String fileName = splits.last; 114 | assetsCache[fileName] = contents; 115 | } 116 | } 117 | if (basicCache != null) { 118 | assetsCache.addAll(basicCache!); 119 | } 120 | } 121 | 122 | Uri h5Uri = Uri.parse(h5Path); 123 | String path = h5Uri.path; 124 | String query = h5Uri.query; 125 | bool canUse = false; 126 | String optionKey = ""; 127 | 128 | // 判断是否资源已经下载完成可使用 129 | for (var option in lsClientConfig!.options) { 130 | if (h5Path.contains(option.key!) && (option.isAssetsDone ?? false)) { 131 | canUse = true; 132 | optionKey = option.key!; 133 | break; 134 | } 135 | } 136 | if (!canUse) { 137 | isLocalServer = false; 138 | return h5Path; 139 | } 140 | tmpAsset = lsClientConfig!.assets[optionKey]; 141 | if (tmpAsset == null) { 142 | isLocalServer = false; 143 | return h5Path; 144 | } 145 | _fetchMemorySources(tmpAsset); 146 | if (hasEmptyFiles) { 147 | return h5Path; 148 | } 149 | isLocalServer = true; 150 | return LocalServerService.instance.getLocalServerWebUrl(h5Path, query.isEmpty ? path : path + '?' + query); 151 | } 152 | 153 | } -------------------------------------------------------------------------------- /lib/tools/local_server_manager.dart: -------------------------------------------------------------------------------- 1 | 2 | import 'dart:developer'; 3 | import 'dart:io'; 4 | 5 | import 'package:flutter/foundation.dart'; 6 | import 'package:local_server_for_webview/src/model/download_service_item.dart'; 7 | import 'package:local_server_for_webview/src/model/local_server_client_config.dart'; 8 | import 'package:local_server_for_webview/src/services/local_server_configuration.dart'; 9 | import 'package:local_server_for_webview/src/services/local_server_service.dart'; 10 | import 'package:local_server_for_webview/tools/local_server_binder.dart'; 11 | import 'package:local_server_for_webview/tools/local_server_config_cache.dart'; 12 | import 'package:local_server_for_webview/tools/local_server_downloader.dart'; 13 | import 'package:local_server_for_webview/tools/local_server_status_handler.dart'; 14 | 15 | class LocalServerClientManager implements LocalServerStatusHandler, 16 | LocalServerDownloadServiceProtocol { 17 | late LocalServerClientConfig localServerClientConfig; 18 | Map basicCache = {}; 19 | Map serviceDegradationMap = {}; 20 | List builders = []; 21 | final Map _fileCache = {}; 22 | int loadStartTime = 0; 23 | 24 | bool unSupportLocalServer = false; 25 | 26 | void init() { 27 | _invokeModule(); 28 | } 29 | 30 | void startLocalServer([String? address, int? port]) => LocalServerService.instance.startServer(address, port); 31 | 32 | void cancelLocalServer() => LocalServerService.instance.cancelServer(); 33 | 34 | void registerBuilder(LocalServerCacheBinder builder) => builders.add(builder); 35 | 36 | void resignBuilder(LocalServerCacheBinder builder) => builders.remove(builder); 37 | 38 | void _invokeModule() async { 39 | LocalServerDownloadService().invoke(this); 40 | LocalServerService.instance.invoke(); 41 | LocalServerService.instance.registerStatusObserve(this); 42 | } 43 | 44 | void prepareManager(LocalServerClientConfig localServerClientConfig) async { 45 | loadStartTime = DateTime.now().millisecondsSinceEpoch; 46 | this.localServerClientConfig = localServerClientConfig; 47 | LocalServerConfiguration.getDistDirectory(); 48 | LocalServerCacheBinderSetting.instance.setConfig(localServerClientConfig); 49 | } 50 | 51 | void setWebViewErrorCode(int errorCode) { 52 | switch (errorCode) { 53 | case -1: 54 | case -7: 55 | case -2: 56 | case -6: 57 | case -1004: 58 | unSupportLocalServer = true; 59 | break; 60 | default: 61 | break; 62 | } 63 | } 64 | 65 | @override 66 | fetchRespondsSources(String path) { 67 | dynamic res; 68 | for (var builder in builders) { 69 | res = builder.findBuilderResource(path); 70 | if (res != null) { 71 | break; 72 | } 73 | } 74 | 75 | if (res == null) { 76 | Map? sourceMsg = _fileCache[path]; 77 | if (sourceMsg == null) { 78 | return null; 79 | } else { 80 | String path = LocalServerConfiguration.joinZipPathSync(sourceMsg['zipUrl'], sourceMsg['filePath']); 81 | File temFile = File(path); 82 | if (temFile.existsSync()) { 83 | return temFile.readAsBytesSync(); 84 | } else { 85 | return null; 86 | } 87 | } 88 | } 89 | return res; 90 | } 91 | 92 | @override 93 | void simpleAssetDownloadsComplete(DownloadServiceItem item) { 94 | for (var file in item.filePath) { 95 | if (file.isEmpty) { 96 | return; 97 | } 98 | List splits = file.split('/'); 99 | String fileName = splits.last; 100 | Map map = {}; 101 | map['zipUrl'] = item.zipUrl; 102 | map['h5Path'] = item.h5Path; 103 | map['filePath'] = file; 104 | _fileCache[fileName] = map; 105 | } 106 | localServerClientConfig.changeAssetsFromZipUrl(item); 107 | } 108 | 109 | @override 110 | simpleAssetDownloadsFailure(DownloadServiceItem item, String errMsg) { 111 | _log('[simpleAssetDownloadsFailure]' + errMsg); 112 | } 113 | 114 | @override 115 | basicsDidFullyDownloaded(bool isSuc, List basicsBucket) { 116 | if (localServerClientConfig.basicIsDown) { 117 | return; 118 | } 119 | Map tmpBasicCache = {}; 120 | for (var loadItem in basicsBucket) { 121 | for (var p in loadItem.filePath) { 122 | String path = LocalServerConfiguration.joinZipPathSync(loadItem.zipUrl, p); 123 | File assetFile = File(path); 124 | if (assetFile.existsSync()) { 125 | var contents = assetFile.readAsBytesSync(); 126 | List splits = assetFile.path.split('/'); 127 | String fileName = splits.last; 128 | tmpBasicCache[fileName] = contents; 129 | } 130 | } 131 | } 132 | basicCache = tmpBasicCache; 133 | LocalServerCacheBinderSetting.instance.setBasicCache(basicCache); 134 | localServerClientConfig.basicIsDown = isSuc; 135 | _log('结束Basic下载,用时: ${(DateTime.now().millisecondsSinceEpoch - loadStartTime) / 1000}'); 136 | } 137 | 138 | @override 139 | assetsDidFullyDownloaded() { 140 | for (var element in localServerClientConfig.options) { 141 | element.isAssetsDone = true; 142 | } 143 | _log('结束Asset 下载, 用时:${(DateTime.now().millisecondsSinceEpoch - loadStartTime) / 1000}'); 144 | LocalServerConfigCache.setAssets(localServerClientConfig.assets); 145 | LocalServerConfigCache.setOptions(localServerClientConfig.options); 146 | } 147 | 148 | @override 149 | createServerSuccess(int port, String localAddress) { 150 | _log('创建localserver 成功 port: $port localAddress:$localAddress'); 151 | } 152 | 153 | @override 154 | createServerFailure(err) { 155 | _log('创建localserver 失败 err: ${err.toString()}'); 156 | } 157 | 158 | @override 159 | serverWillCancel() { 160 | _log('localserver 将要被取消'); 161 | } 162 | 163 | @override 164 | serverDidCancel() { 165 | _log('localserver 已被取消'); 166 | } 167 | 168 | @override 169 | requestServerFailure(String path, Object error) { 170 | _log('localserver 请求失败 uri:$path err:$error'); 171 | } 172 | 173 | void _log(Object msg) { 174 | if (!kReleaseMode) { 175 | log(msg.toString(), name: 'Local Service Config'); 176 | } 177 | } 178 | 179 | } -------------------------------------------------------------------------------- /lib/src/services/local_server_service.dart: -------------------------------------------------------------------------------- 1 | import 'dart:async'; 2 | import 'dart:developer'; 3 | import 'dart:io'; 4 | 5 | import 'package:dio/dio.dart'; 6 | import 'package:local_server_for_webview/local_server_for_webview.dart'; 7 | import 'package:mime/mime.dart'; 8 | import 'package:path/path.dart'; 9 | 10 | /// Http Server 服务 11 | /// @author jm 12 | class LocalServerService extends LocalServerServiceHandler { 13 | 14 | factory LocalServerService() => _getInstance(); 15 | 16 | static LocalServerService get instance => _getInstance(); 17 | static LocalServerService? _instance; 18 | 19 | static LocalServerService _getInstance() { 20 | _instance ??= LocalServerService._internal(); 21 | return _instance!; 22 | } 23 | 24 | LocalServerService._internal(); 25 | 26 | /// 初始化配置 27 | /// 目录的加载 28 | invoke() async { 29 | await LocalServerConfiguration.getDistDirectory(); 30 | } 31 | 32 | /// 获取对应 [oriUrl] 的 Local Server url(如http://127.0.0.1:12345) 33 | /// [localServerKey] 是拼接的path和query,如 test/index.html?v=1 34 | /// 返回的完整url为:http://127.0.0.1:12345/test/index.html?v=1 35 | String getLocalServerWebUrl(String oriUrl, String localServerKey) { 36 | return _getLocalServerWebUrl(oriUrl, localServerKey); 37 | } 38 | 39 | /// 注册状态回调 40 | /// 详见[LocalServerStatusHandler] 41 | void registerStatusObserve(LocalServerStatusHandler handler) { 42 | observe = handler; 43 | } 44 | 45 | /// 关闭状态回调 46 | void cancelStatusObserver() { 47 | observe = null; 48 | } 49 | 50 | /// 开启http server服务 51 | /// 见[HttpServer.bind] 52 | /// [address]若为null,则默认是127.0.0.1 53 | /// [port] 若为null,则默认是0 54 | Future startServer([String? address, int? port]) => _startServer(address, port); 55 | 56 | /// 关闭http server服务, 并且取消状态回调 57 | /// [force] 为true,立即关闭 58 | /// 见[HttpServer.close] 59 | void closeServer({bool force = false}) { 60 | _closeServer(force: force); 61 | } 62 | 63 | /// 关闭http server服务 64 | void cancelServer() => _cancelServer(); 65 | 66 | } 67 | 68 | class LocalServerServiceHandler { 69 | 70 | final String _logKey = 'LocalServer'; 71 | 72 | HttpServer? _server; 73 | 74 | int referenceCounter = 0; 75 | 76 | StreamSubscription? serverSub; 77 | 78 | bool isOpenServer = false; 79 | 80 | String? curAddresses; 81 | 82 | int curPort = 0; 83 | 84 | LocalServerStatusHandler? observe; 85 | 86 | /// oriUrl 其实没用,目前设计是统一一个本地地址。 87 | /// 但也可以考虑设计成不同链接对应不同的本地地址,启动多个服务。用[oriUrl] 来寻找 88 | String _getLocalServerWebUrl(String oriUrl, String localServerKey) { 89 | return 'http://${curAddresses ?? InternetAddress.loopbackIPv4.address}:$curPort$localServerKey'; 90 | } 91 | 92 | Future _startServer([String? address, int? port]) async { 93 | if (isOpenServer) { 94 | return Future.value(_server); 95 | } 96 | try { 97 | isOpenServer = true; 98 | var p = port; 99 | p ??= curPort; 100 | // 开启侦听 http 的请求,port为0则系统会自动选取一个临时端口 101 | _server = await HttpServer.bind(address ?? InternetAddress.loopbackIPv4, p); 102 | curAddresses = _server!.address.address; 103 | curPort = _server!.port; 104 | _server!.sessionTimeout = 60; 105 | // 拦截侦听 106 | serverSub = _server!.listen(_responseWebViewReq, onError: (e) => log(e, name: _logKey)); 107 | if (observe != null) { 108 | observe!.createServerSuccess(curPort, curAddresses!); 109 | } 110 | return _server!; 111 | } catch(e) { 112 | isOpenServer = false; 113 | observe?.createServerFailure(e); 114 | rethrow; 115 | } 116 | } 117 | 118 | /// 还有webpage在使用的时候,不会关闭 119 | void _closeServer({bool force = false}) { 120 | if (referenceCounter > 0) { 121 | return; 122 | } 123 | observe?.serverWillCancel(); 124 | isOpenServer = false; 125 | serverSub?.cancel(); 126 | _server?.close(force: force); 127 | observe?.serverDidCancel(); 128 | } 129 | 130 | void _cancelServer() { 131 | isOpenServer = false; 132 | serverSub?.cancel(); 133 | _server?.close(); 134 | } 135 | 136 | /// 根据拦截的请求(包括html,js,css等),返回对应资源的bytes data即替换 137 | /// 比如index.html,在获取给到webview后,会继续解析得到各js,css资源的请求,只要不是绝对路径也会被拦截 138 | void _responseWebViewReq(HttpRequest request) async { 139 | _getResponseData() async { 140 | try { 141 | String 142 | name; 143 | String? mime; 144 | String path = request.requestedUri.path; 145 | String component = path.split('/').toList().last; 146 | // 拿到文件名, [observe.fetchRespondsSources] 是获取对应缓存资源的数据 147 | var data = observe?.fetchRespondsSources(component); 148 | if (data == null) { 149 | // 有可能有 http://127.0.0.1:1234/test 这种形式的链接,所以尝试拿index.html文件来加载 150 | if (!component.contains('.')) { 151 | data = observe?.fetchRespondsSources('index.html'); 152 | } 153 | if (data != null) { 154 | name = basename('index.html'); 155 | mime = lookupMimeType(name); 156 | } else { 157 | // 找不到本地文件,使用网络下载拿到原始数据 158 | var nowUri = request.requestedUri; 159 | var baseDomain = LocalServerCacheBinderSetting.instance.baseDomain; 160 | var baseUri = Uri.parse(baseDomain); 161 | // 替换为原始url 162 | nowUri = nowUri.replace( 163 | scheme: baseUri.scheme, host: baseUri.host, port: baseUri.port); 164 | // dio请求,responseType 必须是bytes 165 | var res = await Dio().getUri(nowUri, options: Options(responseType: ResponseType.bytes)); 166 | data = res.data; 167 | name = basename(nowUri.path.split('/').toList().last); 168 | mime = lookupMimeType(name); 169 | } 170 | } else { 171 | // 根据文件名拿到对应的MimeType 172 | name = basename(component); 173 | mime = lookupMimeType(name); 174 | } 175 | request.response.headers.add('Content-Type', '$mime; charset=utf-8'); 176 | return data; 177 | } catch(e) { 178 | observe?.requestServerFailure(request.requestedUri.toString(), e); 179 | rethrow; 180 | } 181 | } 182 | 183 | try { 184 | final data = await _getResponseData(); 185 | request.response.add(data); 186 | } catch(e) { 187 | request.response.statusCode = 404; 188 | observe?.requestServerFailure(request.requestedUri.toString(), e); 189 | log('[local server request] Error${e.toString()}', name: _logKey); 190 | } finally { 191 | // 最后要关闭 response 192 | request.response.close(); 193 | } 194 | } 195 | 196 | } -------------------------------------------------------------------------------- /lib/src/model/local_server_client_config.dart: -------------------------------------------------------------------------------- 1 | import 'dart:developer'; 2 | import 'dart:io'; 3 | 4 | import 'package:flutter/foundation.dart'; 5 | import 'package:local_server_for_webview/local_server_for_webview.dart'; 6 | 7 | /// 解析config,并自动触发相应的下载任务 8 | class LocalServerClientConfig { 9 | String key = 'local_server_config'; 10 | 11 | List options = []; 12 | 13 | Map assets = {}; 14 | 15 | Map basics = {}; 16 | 17 | Map> mappingZipAssets = {}; 18 | 19 | bool isHavePermission = true; 20 | 21 | bool basicIsDown = false; 22 | 23 | Map permissionJsonCache = {}; 24 | 25 | /// 解析配置json 26 | /// 默认的配置是 27 | /// { 28 | /// "option": [ 29 | /// { 30 | /// "key": "test", 31 | /// "open": 1, 32 | /// "priority": 0, 33 | /// "version": "20222022" 34 | /// }, 35 | /// { 36 | /// "key": "test2", 37 | /// "open": 0, 38 | /// "priority": 0, 39 | /// "version": "20222222" 40 | /// } 41 | /// ], 42 | /// "assets": { 43 | /// "test": { 44 | /// "compress": "/local-server/test.zip" 45 | /// }, 46 | /// "test2": { 47 | /// "compress": "/local-server/test2.zip" 48 | /// } 49 | /// }, 50 | /// "basics": { 51 | /// "common": { 52 | /// "compress": "/local-server/common.zip", 53 | /// "version": "20220501" 54 | /// } 55 | /// }, 56 | /// "local_server_open": 1 57 | /// } 58 | LocalServerClientConfig.fromJson(Map json) { 59 | // 拿到option,处理优先级和各配置 60 | List? optionJson = json['option']; 61 | if (optionJson != null && optionJson.isNotEmpty) { 62 | for (var value in optionJson) { 63 | final tmpItem = LocalServerClientConfigItem.parse(value); 64 | if (tmpItem != null) { 65 | options.add(tmpItem); 66 | } 67 | } 68 | options.sort((a, b) => (a.priority).compareTo(b.priority)); 69 | } 70 | 71 | Map assetJson = json['assets']; 72 | Map basicMap = json['basics']; 73 | basicMap.forEach((key, value) { 74 | basics[key] = value as Map; 75 | }); 76 | // 处理统一资源 Basic ,对比version,不一样的version则需要更新 77 | LocalServerConfigCache.getBasic().then((value) { 78 | List? oldBasic = List.from(value ?? []); 79 | // 版本不对,则移除,并需要下载 80 | if (value?.isNotEmpty ?? false) { 81 | for (DownloadServiceItem element in value!) { 82 | var res = basics[element.h5Path]; 83 | if (res != null) { 84 | if (res['version'] != element.version) { 85 | oldBasic.removeWhere((e) => element.h5Path == e.h5Path); 86 | } 87 | } 88 | } 89 | } 90 | // 触发预下载 91 | LocalServerDownloadService.instance.preloadBasicsData(json['basics'], basics, oldBasic); 92 | }); 93 | 94 | Map tmpAssets = {}; 95 | for (var e in options) { 96 | if (assetJson[e.key] != null) { 97 | tmpAssets[e.key!] = DownloadServiceTotalAssetItem.fromConfigCenter(assetJson[e.key], e.key!); 98 | } 99 | } 100 | assets = tmpAssets; 101 | assets.forEach((key, value) { 102 | for (var element in value.assets) { 103 | if (mappingZipAssets.containsKey(element.zipUrl)) { 104 | mappingZipAssets[element.zipUrl]?.add(element); 105 | } else { 106 | mappingZipAssets[element.zipUrl] = [element]; 107 | } 108 | } 109 | }); 110 | 111 | // 处理 assets 资源,和版本控制 112 | LocalServerConfigCache.getOptions().then((oldOptions) { 113 | // assets 缓存和版本处理 114 | LocalServerConfigCache.getAssets().then((value) { 115 | var oldAssets = value; 116 | // 版本不对,则移除,并需要下载 117 | if (oldOptions != null) { 118 | for (var e in oldOptions) { 119 | var res = options.where((element) => element.key == e.key); 120 | if (res.isNotEmpty && res.first.version != e.version) { 121 | _log('资源 ${e.key} 需要更新'); 122 | oldAssets?.removeWhere((key, value) => key == e.key); 123 | } 124 | } 125 | } 126 | // 触发预下载 127 | LocalServerDownloadService.instance.preloadAssetsData(_diffAssets(value, assets)); 128 | }); 129 | }); 130 | } 131 | 132 | /// 更改Assets 的状态 133 | void changeAssetsFromZipUrl(DownloadServiceItem item){ 134 | if (mappingZipAssets.containsKey(item.zipUrl)) { 135 | for (var element in mappingZipAssets[item.zipUrl]!) { 136 | element.replaceLoadState(item); 137 | } 138 | } 139 | } 140 | 141 | List _diffAssets( 142 | Map? oldValue, 143 | Map? newValue) { 144 | 145 | if(newValue == null || newValue.isEmpty) { 146 | return []; 147 | } 148 | List resultList = []; 149 | Map oldMap = oldValue ?? {}; 150 | Map newMap = newValue; 151 | 152 | newMap.keys.toList().forEach((keyPath) { 153 | DownloadServiceTotalAssetItem? oldAsset = oldMap[keyPath]; 154 | DownloadServiceTotalAssetItem? newAsset = newMap[keyPath]; 155 | // 如果在旧数据中没有找到新的页面缓存则 当前新数据加入结果数组 156 | if (oldAsset == null) { 157 | resultList.add(newMap[keyPath]); 158 | return; 159 | } 160 | 161 | //以上可以确保new和old数据同时有数据,接下来求两集合相交 找到 内部Zip的差异 162 | final oldZips = oldAsset.assets.map((e) => e.zipUrl).toSet(); 163 | final newZips = newAsset!.assets.map((e) => e.zipUrl).toSet(); 164 | Set intersects = newZips.intersection(oldZips); 165 | 166 | // 遍历旧数据,如果当前zipurl不属于intersects子集,则执行清理文件操作, 167 | // 并标记整体当前oldAsset isAssetsDone 为false 168 | 169 | // 检查当前Asset旧数据是否可以转移到新数据里 170 | for (var oldZipItem in oldAsset.assets) { 171 | if (intersects.contains(oldZipItem.zipUrl)) { 172 | bool checkFileExist = true; 173 | for (var fileName in oldZipItem.filePath) { 174 | var realFilePath = 175 | LocalServerConfiguration.joinZipPathSync(oldZipItem.zipUrl, fileName); 176 | File file = File(realFilePath); 177 | // 检查文件是否可用,如果不可用则不能转移到new Asset 178 | if (!file.existsSync()) { 179 | checkFileExist = false; 180 | } 181 | } 182 | // 如果其中有file本地找不到则,标记当前Asset需要下载 183 | if (!checkFileExist) { 184 | oldZipItem.loadState = LoadStateType.unLoad; 185 | oldZipItem.filePath = []; 186 | oldAsset.isAssetsDone = false; 187 | } 188 | } else { 189 | // 如果不相交也不能转移 190 | oldZipItem.loadState = LoadStateType.unLoad; 191 | oldAsset.isAssetsDone = false; 192 | for (var fileName in oldZipItem.filePath) { 193 | var realFilePath = 194 | LocalServerConfiguration.joinZipPathSync(oldZipItem.zipUrl, fileName); 195 | File file = File(realFilePath); 196 | if (file.existsSync()) { 197 | file.deleteSync(); 198 | } 199 | } 200 | oldZipItem.filePath = []; 201 | } 202 | } 203 | 204 | List tmpNewAssets = []; 205 | int newAssetAllSucCount = 0; 206 | for (var newZipItem in newAsset.assets) { 207 | if (intersects.contains(newZipItem.zipUrl)) { 208 | newAssetAllSucCount++; 209 | for (DownloadServiceItem downloadItem in oldAsset.assets) { 210 | if (downloadItem.zipUrl == newZipItem.zipUrl) { 211 | tmpNewAssets.add(downloadItem); 212 | break; 213 | } 214 | } 215 | } else { 216 | tmpNewAssets.add(newZipItem); 217 | } 218 | } 219 | if(newAssetAllSucCount == newAsset.assets.length) { 220 | newAsset.isAssetsDone = oldAsset.isAssetsDone; 221 | } 222 | 223 | newAsset.assets = tmpNewAssets; 224 | resultList.add(newAsset); 225 | }); 226 | return resultList; 227 | } 228 | 229 | static void _log(Object msg) { 230 | if (!kReleaseMode) { 231 | log(msg.toString(), name: 'Local Service Config'); 232 | } 233 | } 234 | 235 | } -------------------------------------------------------------------------------- /example/pubspec.lock: -------------------------------------------------------------------------------- 1 | # Generated by pub 2 | # See https://dart.dev/tools/pub/glossary#lockfile 3 | packages: 4 | archive: 5 | dependency: transitive 6 | description: 7 | name: archive 8 | url: "https://pub.dartlang.org" 9 | source: hosted 10 | version: "3.3.0" 11 | async: 12 | dependency: transitive 13 | description: 14 | name: async 15 | url: "https://pub.dartlang.org" 16 | source: hosted 17 | version: "2.8.2" 18 | boolean_selector: 19 | dependency: transitive 20 | description: 21 | name: boolean_selector 22 | url: "https://pub.dartlang.org" 23 | source: hosted 24 | version: "2.1.0" 25 | characters: 26 | dependency: transitive 27 | description: 28 | name: characters 29 | url: "https://pub.dartlang.org" 30 | source: hosted 31 | version: "1.2.0" 32 | charcode: 33 | dependency: transitive 34 | description: 35 | name: charcode 36 | url: "https://pub.dartlang.org" 37 | source: hosted 38 | version: "1.3.1" 39 | clock: 40 | dependency: transitive 41 | description: 42 | name: clock 43 | url: "https://pub.dartlang.org" 44 | source: hosted 45 | version: "1.1.0" 46 | collection: 47 | dependency: transitive 48 | description: 49 | name: collection 50 | url: "https://pub.dartlang.org" 51 | source: hosted 52 | version: "1.15.0" 53 | crypto: 54 | dependency: transitive 55 | description: 56 | name: crypto 57 | url: "https://pub.dartlang.org" 58 | source: hosted 59 | version: "3.0.1" 60 | cupertino_icons: 61 | dependency: "direct main" 62 | description: 63 | name: cupertino_icons 64 | url: "https://pub.dartlang.org" 65 | source: hosted 66 | version: "1.0.4" 67 | dio: 68 | dependency: transitive 69 | description: 70 | name: dio 71 | url: "https://pub.dartlang.org" 72 | source: hosted 73 | version: "4.0.6" 74 | fake_async: 75 | dependency: transitive 76 | description: 77 | name: fake_async 78 | url: "https://pub.dartlang.org" 79 | source: hosted 80 | version: "1.2.0" 81 | ffi: 82 | dependency: transitive 83 | description: 84 | name: ffi 85 | url: "https://pub.dartlang.org" 86 | source: hosted 87 | version: "1.1.2" 88 | file: 89 | dependency: transitive 90 | description: 91 | name: file 92 | url: "https://pub.dartlang.org" 93 | source: hosted 94 | version: "6.1.2" 95 | flutter: 96 | dependency: "direct main" 97 | description: flutter 98 | source: sdk 99 | version: "0.0.0" 100 | flutter_lints: 101 | dependency: "direct dev" 102 | description: 103 | name: flutter_lints 104 | url: "https://pub.dartlang.org" 105 | source: hosted 106 | version: "1.0.4" 107 | flutter_test: 108 | dependency: "direct dev" 109 | description: flutter 110 | source: sdk 111 | version: "0.0.0" 112 | flutter_web_plugins: 113 | dependency: transitive 114 | description: flutter 115 | source: sdk 116 | version: "0.0.0" 117 | http: 118 | dependency: transitive 119 | description: 120 | name: http 121 | url: "https://pub.dartlang.org" 122 | source: hosted 123 | version: "0.13.4" 124 | http_parser: 125 | dependency: transitive 126 | description: 127 | name: http_parser 128 | url: "https://pub.dartlang.org" 129 | source: hosted 130 | version: "4.0.0" 131 | js: 132 | dependency: transitive 133 | description: 134 | name: js 135 | url: "https://pub.dartlang.org" 136 | source: hosted 137 | version: "0.6.3" 138 | lints: 139 | dependency: transitive 140 | description: 141 | name: lints 142 | url: "https://pub.dartlang.org" 143 | source: hosted 144 | version: "1.0.1" 145 | local_server_for_webview: 146 | dependency: "direct main" 147 | description: 148 | path: ".." 149 | relative: true 150 | source: path 151 | version: "0.0.1" 152 | matcher: 153 | dependency: transitive 154 | description: 155 | name: matcher 156 | url: "https://pub.dartlang.org" 157 | source: hosted 158 | version: "0.12.11" 159 | material_color_utilities: 160 | dependency: transitive 161 | description: 162 | name: material_color_utilities 163 | url: "https://pub.dartlang.org" 164 | source: hosted 165 | version: "0.1.3" 166 | meta: 167 | dependency: transitive 168 | description: 169 | name: meta 170 | url: "https://pub.dartlang.org" 171 | source: hosted 172 | version: "1.7.0" 173 | mime: 174 | dependency: transitive 175 | description: 176 | name: mime 177 | url: "https://pub.dartlang.org" 178 | source: hosted 179 | version: "1.0.1" 180 | path: 181 | dependency: transitive 182 | description: 183 | name: path 184 | url: "https://pub.dartlang.org" 185 | source: hosted 186 | version: "1.8.0" 187 | path_provider: 188 | dependency: transitive 189 | description: 190 | name: path_provider 191 | url: "https://pub.dartlang.org" 192 | source: hosted 193 | version: "2.0.9" 194 | path_provider_android: 195 | dependency: transitive 196 | description: 197 | name: path_provider_android 198 | url: "https://pub.dartlang.org" 199 | source: hosted 200 | version: "2.0.12" 201 | path_provider_ios: 202 | dependency: transitive 203 | description: 204 | name: path_provider_ios 205 | url: "https://pub.dartlang.org" 206 | source: hosted 207 | version: "2.0.8" 208 | path_provider_linux: 209 | dependency: transitive 210 | description: 211 | name: path_provider_linux 212 | url: "https://pub.dartlang.org" 213 | source: hosted 214 | version: "2.1.5" 215 | path_provider_macos: 216 | dependency: transitive 217 | description: 218 | name: path_provider_macos 219 | url: "https://pub.dartlang.org" 220 | source: hosted 221 | version: "2.0.5" 222 | path_provider_platform_interface: 223 | dependency: transitive 224 | description: 225 | name: path_provider_platform_interface 226 | url: "https://pub.dartlang.org" 227 | source: hosted 228 | version: "2.0.3" 229 | path_provider_windows: 230 | dependency: transitive 231 | description: 232 | name: path_provider_windows 233 | url: "https://pub.dartlang.org" 234 | source: hosted 235 | version: "2.0.5" 236 | platform: 237 | dependency: transitive 238 | description: 239 | name: platform 240 | url: "https://pub.dartlang.org" 241 | source: hosted 242 | version: "3.1.0" 243 | plugin_platform_interface: 244 | dependency: transitive 245 | description: 246 | name: plugin_platform_interface 247 | url: "https://pub.dartlang.org" 248 | source: hosted 249 | version: "2.1.2" 250 | process: 251 | dependency: transitive 252 | description: 253 | name: process 254 | url: "https://pub.dartlang.org" 255 | source: hosted 256 | version: "4.2.4" 257 | shared_preferences: 258 | dependency: transitive 259 | description: 260 | name: shared_preferences 261 | url: "https://pub.dartlang.org" 262 | source: hosted 263 | version: "2.0.13" 264 | shared_preferences_android: 265 | dependency: transitive 266 | description: 267 | name: shared_preferences_android 268 | url: "https://pub.dartlang.org" 269 | source: hosted 270 | version: "2.0.11" 271 | shared_preferences_ios: 272 | dependency: transitive 273 | description: 274 | name: shared_preferences_ios 275 | url: "https://pub.dartlang.org" 276 | source: hosted 277 | version: "2.1.0" 278 | shared_preferences_linux: 279 | dependency: transitive 280 | description: 281 | name: shared_preferences_linux 282 | url: "https://pub.dartlang.org" 283 | source: hosted 284 | version: "2.1.0" 285 | shared_preferences_macos: 286 | dependency: transitive 287 | description: 288 | name: shared_preferences_macos 289 | url: "https://pub.dartlang.org" 290 | source: hosted 291 | version: "2.0.3" 292 | shared_preferences_platform_interface: 293 | dependency: transitive 294 | description: 295 | name: shared_preferences_platform_interface 296 | url: "https://pub.dartlang.org" 297 | source: hosted 298 | version: "2.0.0" 299 | shared_preferences_web: 300 | dependency: transitive 301 | description: 302 | name: shared_preferences_web 303 | url: "https://pub.dartlang.org" 304 | source: hosted 305 | version: "2.0.3" 306 | shared_preferences_windows: 307 | dependency: transitive 308 | description: 309 | name: shared_preferences_windows 310 | url: "https://pub.dartlang.org" 311 | source: hosted 312 | version: "2.1.0" 313 | sky_engine: 314 | dependency: transitive 315 | description: flutter 316 | source: sdk 317 | version: "0.0.99" 318 | source_span: 319 | dependency: transitive 320 | description: 321 | name: source_span 322 | url: "https://pub.dartlang.org" 323 | source: hosted 324 | version: "1.8.1" 325 | stack_trace: 326 | dependency: transitive 327 | description: 328 | name: stack_trace 329 | url: "https://pub.dartlang.org" 330 | source: hosted 331 | version: "1.10.0" 332 | stream_channel: 333 | dependency: transitive 334 | description: 335 | name: stream_channel 336 | url: "https://pub.dartlang.org" 337 | source: hosted 338 | version: "2.1.0" 339 | string_scanner: 340 | dependency: transitive 341 | description: 342 | name: string_scanner 343 | url: "https://pub.dartlang.org" 344 | source: hosted 345 | version: "1.1.0" 346 | term_glyph: 347 | dependency: transitive 348 | description: 349 | name: term_glyph 350 | url: "https://pub.dartlang.org" 351 | source: hosted 352 | version: "1.2.0" 353 | test_api: 354 | dependency: transitive 355 | description: 356 | name: test_api 357 | url: "https://pub.dartlang.org" 358 | source: hosted 359 | version: "0.4.8" 360 | typed_data: 361 | dependency: transitive 362 | description: 363 | name: typed_data 364 | url: "https://pub.dartlang.org" 365 | source: hosted 366 | version: "1.3.0" 367 | uuid: 368 | dependency: transitive 369 | description: 370 | name: uuid 371 | url: "https://pub.dartlang.org" 372 | source: hosted 373 | version: "3.0.6" 374 | vector_math: 375 | dependency: transitive 376 | description: 377 | name: vector_math 378 | url: "https://pub.dartlang.org" 379 | source: hosted 380 | version: "2.1.1" 381 | webview_flutter: 382 | dependency: "direct main" 383 | description: 384 | name: webview_flutter 385 | url: "https://pub.dartlang.org" 386 | source: hosted 387 | version: "2.8.0" 388 | webview_flutter_android: 389 | dependency: transitive 390 | description: 391 | name: webview_flutter_android 392 | url: "https://pub.dartlang.org" 393 | source: hosted 394 | version: "2.8.5" 395 | webview_flutter_platform_interface: 396 | dependency: transitive 397 | description: 398 | name: webview_flutter_platform_interface 399 | url: "https://pub.dartlang.org" 400 | source: hosted 401 | version: "1.8.1" 402 | webview_flutter_wkwebview: 403 | dependency: transitive 404 | description: 405 | name: webview_flutter_wkwebview 406 | url: "https://pub.dartlang.org" 407 | source: hosted 408 | version: "2.7.2" 409 | win32: 410 | dependency: transitive 411 | description: 412 | name: win32 413 | url: "https://pub.dartlang.org" 414 | source: hosted 415 | version: "2.5.1" 416 | xdg_directories: 417 | dependency: transitive 418 | description: 419 | name: xdg_directories 420 | url: "https://pub.dartlang.org" 421 | source: hosted 422 | version: "0.2.0+1" 423 | sdks: 424 | dart: ">=2.16.1 <3.0.0" 425 | flutter: ">=2.8.0" 426 | -------------------------------------------------------------------------------- /lib/tools/local_server_downloader.dart: -------------------------------------------------------------------------------- 1 | 2 | import 'dart:developer'; 3 | import 'dart:io'; 4 | 5 | import 'package:archive/archive.dart'; 6 | import 'package:dio/dio.dart'; 7 | import 'package:flutter/foundation.dart'; 8 | import 'package:local_server_for_webview/local_server_for_webview.dart'; 9 | import 'package:uuid/uuid.dart'; 10 | 11 | abstract class LocalServerDownloadServiceProtocol { 12 | /// 所有basic下载资源完成 13 | basicsDidFullyDownloaded(bool isSuc, List basicsBucket); 14 | 15 | /// 所有Asset下载资源完成 16 | assetsDidFullyDownloaded(); 17 | 18 | /// 单个asset下载完成 19 | simpleAssetDownloadsComplete(DownloadServiceItem item); 20 | 21 | /// 单个asset下载失败 22 | simpleAssetDownloadsFailure(DownloadServiceItem item, String errMsg); 23 | } 24 | 25 | /// Local Server 下载服务 26 | class LocalServerDownloadService { 27 | factory LocalServerDownloadService() => _getInstance(); 28 | 29 | static LocalServerDownloadService get instance => _getInstance(); 30 | static LocalServerDownloadService? _instance; 31 | 32 | LocalServerDownloadService._internal(); 33 | 34 | static LocalServerDownloadService _getInstance() { 35 | _instance ??= LocalServerDownloadService._internal(); 36 | return _instance!; 37 | } 38 | 39 | static const String _logKey = 'local server downloader'; 40 | 41 | /// 最大的同时下载数量 42 | int downloadMaxCount = 10; 43 | 44 | late LocalServerDownloadServiceProtocol _bind; 45 | 46 | List _loadQueue = []; 47 | 48 | Map> _assetsBucket = {}; 49 | 50 | List basicsBucket = []; 51 | int sucCount = 0; 52 | 53 | void invoke(LocalServerDownloadServiceProtocol bind) => _bind = bind; 54 | 55 | /// 预载assets资源 56 | preloadAssetsData(List assets) => _preloadAssetsData(assets); 57 | 58 | /// 预载basics资源, [basicsCache] 是旧的需要去重的缓存 59 | preloadBasicsData(Map basicJson, Map basics, List? basicsCache) => _preloadBasicsData(basicJson, basics, basicsCache); 60 | 61 | int assetsBucketCount = 0; 62 | 63 | /// 下载队列 64 | void _downloadInQueue() { 65 | if (_loadQueue.length > 10 || _assetsBucket.isEmpty) { 66 | return; 67 | } 68 | List dequeueList = _createTmpQueueList(); 69 | _log('已下载个数:$sucCount'); 70 | if (sucCount >= assetsBucketCount) { 71 | _log('当前_bucket资源已全部下载完毕'); 72 | _assetsBucket.forEach((key, value) { 73 | for (var element in value) { 74 | _bind.simpleAssetDownloadsComplete(element); 75 | } 76 | }); 77 | _bind.assetsDidFullyDownloaded(); 78 | _assetsBucket = {}; 79 | _loadQueue = []; 80 | return; 81 | } 82 | if (dequeueList.isEmpty) { 83 | return; 84 | } 85 | _loadQueue.addAll(dequeueList); 86 | 87 | _log('bucket个数: ${_assetsBucket.length} 当前队列未下载个数: ${_loadQueue.length} 已下载个数:$sucCount'); 88 | for (var queueItem in dequeueList) { 89 | // 判断路径之前是否存在 90 | if (queueItem.filePath.isNotEmpty && queueItem.loadState == LoadStateType.success) { 91 | _log('当前资源无需下载使用之前缓存 zipUrl: ${queueItem.zipUrl}'); 92 | _assetsBucket.remove(queueItem.zipUrl); 93 | assetsBucketCount--; 94 | _downloadInQueue(); 95 | return; 96 | } 97 | final zipPath = "${LocalServerConfiguration.cacheDirectory}/${(const Uuid().v4())}.zip"; 98 | queueItem.loadState = LoadStateType.loading; 99 | _log('dio 下载 zipUrl: ${queueItem.zipUrl}'); 100 | Dio().download(queueItem.zipUrl, zipPath).then((resp) { 101 | if (resp.statusCode != 200) { 102 | _log('下载ls 压缩包失败 err:${resp.statusCode} zipUrl:${queueItem.zipUrl}'); 103 | throw Exception('下载ls 压缩包失败 err:${resp.statusCode}'); 104 | } 105 | return unarchive(queueItem, zipPath); 106 | }).then((item) { 107 | var assets = _assetsBucket[item.zipUrl]; 108 | if (assets != null && assets.isNotEmpty) { 109 | for (var bucketItem in assets) { 110 | bucketItem.replaceLoadState(item); 111 | } 112 | _loadQueue.removeWhere((element) => element.zipUrl == item.zipUrl); 113 | } 114 | _downloadInQueue(); 115 | }).catchError((err) { 116 | queueItem.loadState = LoadStateType.failure; 117 | queueItem.downloadCount += 1; 118 | var assets = _assetsBucket[queueItem.zipUrl]; 119 | if (assets != null && assets.isNotEmpty) { 120 | for (var element in assets) { 121 | element.replaceLoadState(queueItem); 122 | } 123 | } 124 | _assetsBucket.remove(queueItem.zipUrl); 125 | assetsBucketCount--; 126 | _downloadInQueue(); 127 | _log('解压失败 err:$err zipUrl:${queueItem.zipUrl}'); 128 | }); 129 | } 130 | } 131 | 132 | /// 解压 133 | DownloadServiceItem unarchive(DownloadServiceItem item, String downPath) { 134 | _log('unarchive 解压 path:${item.h5Path} zip:${item.zipUrl}'); 135 | Directory saveDirct = LocalServerConfiguration.getCurrentZipPathSyncDirectory(item.zipUrl); 136 | final zipFile = File(downPath); 137 | if (!zipFile.existsSync()) { 138 | throw Exception('Local server 下载包文件路径不存在:$downPath'); 139 | } 140 | List bytes = zipFile.readAsBytesSync(); 141 | Archive archive = ZipDecoder().decodeBytes(bytes); 142 | 143 | try { 144 | for (final file in archive) { 145 | final filename = file.name; 146 | if (file.isFile) { 147 | final data = file.content as List; 148 | String filePath = '${saveDirct.path}/$filename'; 149 | File(filePath) 150 | ..createSync(recursive: true) 151 | ..writeAsBytesSync(data); 152 | item.filePath.add(filename); 153 | } else { 154 | Directory('${saveDirct.path}/$filename').create(recursive: true); 155 | } 156 | } 157 | item.loadState = LoadStateType.success; 158 | // 清理之前的缓存 159 | File oldfile = File(downPath); 160 | if (oldfile.existsSync()) { 161 | oldfile.deleteSync(); 162 | } 163 | _log('unarchive 解压成功'); 164 | return item; 165 | } catch(e) { 166 | _log('unarchive 解压失败 item: ${item.toJson().toString()} downPath: $downPath err: $e'); 167 | rethrow; 168 | } 169 | } 170 | 171 | /// 创建下载任务列表 172 | List _createTmpQueueList() { 173 | List dequeueList = []; 174 | sucCount = 0; 175 | void _addQueue(DownloadServiceItem item) { 176 | if (dequeueList.length >= downloadMaxCount || (dequeueList.length + _loadQueue.length) >= downloadMaxCount) { 177 | return; 178 | } 179 | if (_loadQueue.indexWhere((element) => element.zipUrl == item.zipUrl) != -1) { 180 | // 下载列表中已存在则跳过 181 | return; 182 | } 183 | item.loadState = LoadStateType.unLoad; 184 | dequeueList.add(item); 185 | } 186 | 187 | void _traverseBucket() { 188 | _assetsBucket.forEach((key, value) { 189 | for (var tmpItem in value) { 190 | switch(tmpItem.loadState) { 191 | case LoadStateType.unLoad: 192 | case LoadStateType.loading: 193 | _addQueue(tmpItem); 194 | break; 195 | case LoadStateType.success: 196 | sucCount++; 197 | break; 198 | case LoadStateType.failure: 199 | _addQueue(tmpItem); 200 | break; 201 | } 202 | } 203 | }); 204 | } 205 | 206 | _traverseBucket(); 207 | return dequeueList; 208 | } 209 | 210 | /// basics 是另外下载的处理 211 | void _fetchBasicsDataFromNetwork(String key, DownloadServiceItem curItem, List basicsCache) { 212 | if (basicsCache.isNotEmpty) { 213 | _bind.basicsDidFullyDownloaded(false, basicsCache); 214 | } 215 | // 判断basic是否全部下载 216 | void checkBasicDownloadAllDown() async { 217 | int sucLen = basicsBucket 218 | .where((element) => element.loadState == LoadStateType.success) 219 | .toList().length; 220 | if (sucLen >= (LocalServerCacheBinderSetting.instance.lsClientConfig?.basics.length ?? 1)) { 221 | // 保存记录 222 | await LocalServerConfigCache.setBasic(basicsBucket); 223 | // 通知外部basic单元就位 224 | _bind.basicsDidFullyDownloaded(true, basicsBucket); 225 | } 226 | } 227 | 228 | // 判断是否需要递归下载 229 | void checkBasicDownloadNeedRecursion() { 230 | int dirtyCount = basicsBucket 231 | .where((element) => (element.loadState == LoadStateType.unLoad && element.downloadCount < downloadMaxCount)) 232 | .toList().length; 233 | if (dirtyCount <= 0) { 234 | _log("结束Basic 下载,部分资源下载失败"); 235 | return; 236 | } 237 | _fetchBasicsDataFromNetwork(key, curItem, basicsCache); 238 | } 239 | 240 | // merge下载好的路径到_basicsBucket 241 | void replaceItem(DownloadServiceItem item) { 242 | for (var element in basicsBucket) { 243 | if (element.h5Path == item.h5Path) { 244 | element.replaceLoadState(item); 245 | } 246 | } 247 | } 248 | 249 | bool checkBasicCacheIsAvailable() { 250 | var cacheItemList = basicsCache.where((element) => element.h5Path == key).toList(); 251 | if (cacheItemList.isEmpty) { 252 | return false; 253 | } 254 | var cacheItem = cacheItemList.first; 255 | // 之前没有持久化文件,则进入下载 256 | if (cacheItem.filePath.isEmpty) { 257 | return false; 258 | } 259 | 260 | if (cacheItem.zipUrl == curItem.zipUrl) { 261 | bool isExitFilePath = true; 262 | for (var filePath in cacheItem.filePath) { 263 | String tmpPath = LocalServerConfiguration.joinZipPathSync(cacheItem.zipUrl, filePath); 264 | File cacheFile = File(tmpPath); 265 | if (!cacheFile.existsSync()) { 266 | isExitFilePath = false; 267 | } 268 | } 269 | if (!isExitFilePath) { 270 | return false; 271 | } 272 | replaceItem(cacheItem); 273 | checkBasicDownloadAllDown(); 274 | return true; 275 | } else { 276 | for (var deletePath in cacheItem.filePath) { 277 | String filePath = LocalServerConfiguration.joinZipPathSync(cacheItem.zipUrl, deletePath); 278 | File cacheFile = File(filePath); 279 | if (cacheFile.existsSync()) { 280 | cacheFile.deleteSync(recursive: true); 281 | } 282 | } 283 | cacheItem.filePath = []; 284 | return false; 285 | } 286 | } 287 | 288 | // 持久化检查有问题,进入本次下载 289 | if (checkBasicCacheIsAvailable()) { 290 | return; 291 | } 292 | final zipPath = '${LocalServerConfiguration.cacheDirectory}/$key.zip'; 293 | Dio().download(LocalServerConfiguration.downloadUrl(curItem.zipUrl), zipPath).then((resp) { 294 | if (resp.statusCode != 200) { 295 | curItem.downloadCount++; 296 | curItem.loadState = LoadStateType.failure; 297 | throw Exception('下载ls 压缩包失败 err: ${resp.statusCode}'); 298 | } 299 | return unarchive(curItem, zipPath); 300 | }).then((item) { 301 | replaceItem(item); 302 | checkBasicDownloadAllDown(); 303 | }).catchError((err) { 304 | // 失败的移除,不在本次下载(可调整为尝试几次后再移除) 305 | basicsBucket.removeWhere((element) => element.zipUrl == curItem.zipUrl); 306 | _log("basic 资源下载失败 zipUrl: ${LocalServerConfiguration.downloadUrl(curItem.zipUrl)}"); 307 | checkBasicDownloadNeedRecursion(); 308 | }); 309 | } 310 | 311 | Map> _convertToBucketList(List assets) { 312 | Map> _innerMap = {}; 313 | for (var totalAsset in assets) { 314 | for (var value in totalAsset.assets) { 315 | Set? tmpZipBucket = _innerMap[value.zipUrl]; 316 | if (tmpZipBucket == null) { 317 | Set tmp = {}..add(value); 318 | _innerMap[value.zipUrl] = tmp; 319 | } else { 320 | tmpZipBucket.add(value); 321 | } 322 | } 323 | } 324 | return _innerMap; 325 | } 326 | 327 | void _preloadAssetsData(List assets) { 328 | _assetsBucket.addAll(_convertToBucketList(assets)); 329 | int tmpAssetsBucketCount = 0; 330 | _assetsBucket.forEach((key, value) { 331 | for (var element in value) { 332 | tmpAssetsBucketCount++; 333 | _log('assets bucket 已有资源 loadState: ${element.loadState} path: ${element.h5Path} zip: ${element.zipUrl}'); 334 | } 335 | }); 336 | assetsBucketCount = tmpAssetsBucketCount; 337 | _downloadInQueue(); 338 | } 339 | 340 | void _preloadBasicsData(Map basicJson, Map basics, List? basicsCache) async { 341 | void makeBasicItemInBucket(String key) { 342 | if (basicJson[key] != null) { 343 | DownloadServiceItem tmpItem = DownloadServiceItem() 344 | ..h5Path = key 345 | ..zipUrl = LocalServerConfiguration.downloadUrl(basicJson[key]['compress'] ?? '') 346 | ..version = basicJson[key]['version'] 347 | ..filePath = []; 348 | basicsBucket.add(tmpItem); 349 | _fetchBasicsDataFromNetwork(key, tmpItem, basicsCache ?? []); 350 | } 351 | } 352 | 353 | var basic = basics; 354 | for (var element in basic.keys) { 355 | makeBasicItemInBucket(element); 356 | } 357 | } 358 | 359 | void _log(Object msg) { 360 | if (!kReleaseMode) { 361 | log(msg.toString(), name: _logKey); 362 | } 363 | } 364 | 365 | } -------------------------------------------------------------------------------- /example/ios/Runner.xcodeproj/project.pbxproj: -------------------------------------------------------------------------------- 1 | // !$*UTF8*$! 2 | { 3 | archiveVersion = 1; 4 | classes = { 5 | }; 6 | objectVersion = 51; 7 | objects = { 8 | 9 | /* Begin PBXBuildFile section */ 10 | 0394C5D8DC6B0C501FB7456B /* Pods_Runner.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 87C1D2A92294F2C5C28588AF /* Pods_Runner.framework */; }; 11 | 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */ = {isa = PBXBuildFile; fileRef = 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */; }; 12 | 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */ = {isa = PBXBuildFile; fileRef = 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */; }; 13 | 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74858FAE1ED2DC5600515810 /* AppDelegate.swift */; }; 14 | 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FA1CF9000F007C117D /* Main.storyboard */; }; 15 | 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FD1CF9000F007C117D /* Assets.xcassets */; }; 16 | 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */; }; 17 | /* End PBXBuildFile section */ 18 | 19 | /* Begin PBXCopyFilesBuildPhase section */ 20 | 9705A1C41CF9048500538489 /* Embed Frameworks */ = { 21 | isa = PBXCopyFilesBuildPhase; 22 | buildActionMask = 2147483647; 23 | dstPath = ""; 24 | dstSubfolderSpec = 10; 25 | files = ( 26 | ); 27 | name = "Embed Frameworks"; 28 | runOnlyForDeploymentPostprocessing = 0; 29 | }; 30 | /* End PBXCopyFilesBuildPhase section */ 31 | 32 | /* Begin PBXFileReference section */ 33 | 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GeneratedPluginRegistrant.h; sourceTree = ""; }; 34 | 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GeneratedPluginRegistrant.m; sourceTree = ""; }; 35 | 169A91A53D7FE9415108CBDC /* Pods-Runner.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.debug.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"; sourceTree = ""; }; 36 | 2A48DAEDF535A90A89D4A325 /* Pods-Runner.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.profile.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.profile.xcconfig"; sourceTree = ""; }; 37 | 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = AppFrameworkInfo.plist; path = Flutter/AppFrameworkInfo.plist; sourceTree = ""; }; 38 | 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Runner-Bridging-Header.h"; sourceTree = ""; }; 39 | 74858FAE1ED2DC5600515810 /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; 40 | 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = Release.xcconfig; path = Flutter/Release.xcconfig; sourceTree = ""; }; 41 | 84D9D951A85DFF445436FC9D /* Pods-Runner.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.release.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"; sourceTree = ""; }; 42 | 87C1D2A92294F2C5C28588AF /* Pods_Runner.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Runner.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 43 | 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Debug.xcconfig; path = Flutter/Debug.xcconfig; sourceTree = ""; }; 44 | 9740EEB31CF90195004384FC /* Generated.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Generated.xcconfig; path = Flutter/Generated.xcconfig; sourceTree = ""; }; 45 | 97C146EE1CF9000F007C117D /* Runner.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Runner.app; sourceTree = BUILT_PRODUCTS_DIR; }; 46 | 97C146FB1CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; 47 | 97C146FD1CF9000F007C117D /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; 48 | 97C147001CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; 49 | 97C147021CF9000F007C117D /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; 50 | /* End PBXFileReference section */ 51 | 52 | /* Begin PBXFrameworksBuildPhase section */ 53 | 97C146EB1CF9000F007C117D /* Frameworks */ = { 54 | isa = PBXFrameworksBuildPhase; 55 | buildActionMask = 2147483647; 56 | files = ( 57 | 0394C5D8DC6B0C501FB7456B /* Pods_Runner.framework in Frameworks */, 58 | ); 59 | runOnlyForDeploymentPostprocessing = 0; 60 | }; 61 | /* End PBXFrameworksBuildPhase section */ 62 | 63 | /* Begin PBXGroup section */ 64 | 04136CA42DFDDAB50776E3BF /* Pods */ = { 65 | isa = PBXGroup; 66 | children = ( 67 | 169A91A53D7FE9415108CBDC /* Pods-Runner.debug.xcconfig */, 68 | 84D9D951A85DFF445436FC9D /* Pods-Runner.release.xcconfig */, 69 | 2A48DAEDF535A90A89D4A325 /* Pods-Runner.profile.xcconfig */, 70 | ); 71 | path = Pods; 72 | sourceTree = ""; 73 | }; 74 | 9740EEB11CF90186004384FC /* Flutter */ = { 75 | isa = PBXGroup; 76 | children = ( 77 | 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */, 78 | 9740EEB21CF90195004384FC /* Debug.xcconfig */, 79 | 7AFA3C8E1D35360C0083082E /* Release.xcconfig */, 80 | 9740EEB31CF90195004384FC /* Generated.xcconfig */, 81 | ); 82 | name = Flutter; 83 | sourceTree = ""; 84 | }; 85 | 97C146E51CF9000F007C117D = { 86 | isa = PBXGroup; 87 | children = ( 88 | 9740EEB11CF90186004384FC /* Flutter */, 89 | 97C146F01CF9000F007C117D /* Runner */, 90 | 97C146EF1CF9000F007C117D /* Products */, 91 | 04136CA42DFDDAB50776E3BF /* Pods */, 92 | D73C5CB74E24A23660CBA86C /* Frameworks */, 93 | ); 94 | sourceTree = ""; 95 | }; 96 | 97C146EF1CF9000F007C117D /* Products */ = { 97 | isa = PBXGroup; 98 | children = ( 99 | 97C146EE1CF9000F007C117D /* Runner.app */, 100 | ); 101 | name = Products; 102 | sourceTree = ""; 103 | }; 104 | 97C146F01CF9000F007C117D /* Runner */ = { 105 | isa = PBXGroup; 106 | children = ( 107 | 97C146FA1CF9000F007C117D /* Main.storyboard */, 108 | 97C146FD1CF9000F007C117D /* Assets.xcassets */, 109 | 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */, 110 | 97C147021CF9000F007C117D /* Info.plist */, 111 | 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */, 112 | 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */, 113 | 74858FAE1ED2DC5600515810 /* AppDelegate.swift */, 114 | 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */, 115 | ); 116 | path = Runner; 117 | sourceTree = ""; 118 | }; 119 | D73C5CB74E24A23660CBA86C /* Frameworks */ = { 120 | isa = PBXGroup; 121 | children = ( 122 | 87C1D2A92294F2C5C28588AF /* Pods_Runner.framework */, 123 | ); 124 | name = Frameworks; 125 | sourceTree = ""; 126 | }; 127 | /* End PBXGroup section */ 128 | 129 | /* Begin PBXNativeTarget section */ 130 | 97C146ED1CF9000F007C117D /* Runner */ = { 131 | isa = PBXNativeTarget; 132 | buildConfigurationList = 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */; 133 | buildPhases = ( 134 | D3B3EAE0BF14CBEE3E3342F5 /* [CP] Check Pods Manifest.lock */, 135 | 9740EEB61CF901F6004384FC /* Run Script */, 136 | 97C146EA1CF9000F007C117D /* Sources */, 137 | 97C146EB1CF9000F007C117D /* Frameworks */, 138 | 97C146EC1CF9000F007C117D /* Resources */, 139 | 9705A1C41CF9048500538489 /* Embed Frameworks */, 140 | 3B06AD1E1E4923F5004D2608 /* Thin Binary */, 141 | DEBF1FBFC6B17A06298C5BBF /* [CP] Embed Pods Frameworks */, 142 | ); 143 | buildRules = ( 144 | ); 145 | dependencies = ( 146 | ); 147 | name = Runner; 148 | productName = Runner; 149 | productReference = 97C146EE1CF9000F007C117D /* Runner.app */; 150 | productType = "com.apple.product-type.application"; 151 | }; 152 | /* End PBXNativeTarget section */ 153 | 154 | /* Begin PBXProject section */ 155 | 97C146E61CF9000F007C117D /* Project object */ = { 156 | isa = PBXProject; 157 | attributes = { 158 | LastUpgradeCheck = 1300; 159 | ORGANIZATIONNAME = ""; 160 | TargetAttributes = { 161 | 97C146ED1CF9000F007C117D = { 162 | CreatedOnToolsVersion = 7.3.1; 163 | LastSwiftMigration = 1100; 164 | }; 165 | }; 166 | }; 167 | buildConfigurationList = 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */; 168 | compatibilityVersion = "Xcode 9.3"; 169 | developmentRegion = en; 170 | hasScannedForEncodings = 0; 171 | knownRegions = ( 172 | en, 173 | Base, 174 | ); 175 | mainGroup = 97C146E51CF9000F007C117D; 176 | productRefGroup = 97C146EF1CF9000F007C117D /* Products */; 177 | projectDirPath = ""; 178 | projectRoot = ""; 179 | targets = ( 180 | 97C146ED1CF9000F007C117D /* Runner */, 181 | ); 182 | }; 183 | /* End PBXProject section */ 184 | 185 | /* Begin PBXResourcesBuildPhase section */ 186 | 97C146EC1CF9000F007C117D /* Resources */ = { 187 | isa = PBXResourcesBuildPhase; 188 | buildActionMask = 2147483647; 189 | files = ( 190 | 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */, 191 | 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */, 192 | 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */, 193 | 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */, 194 | ); 195 | runOnlyForDeploymentPostprocessing = 0; 196 | }; 197 | /* End PBXResourcesBuildPhase section */ 198 | 199 | /* Begin PBXShellScriptBuildPhase section */ 200 | 3B06AD1E1E4923F5004D2608 /* Thin Binary */ = { 201 | isa = PBXShellScriptBuildPhase; 202 | buildActionMask = 2147483647; 203 | files = ( 204 | ); 205 | inputPaths = ( 206 | ); 207 | name = "Thin Binary"; 208 | outputPaths = ( 209 | ); 210 | runOnlyForDeploymentPostprocessing = 0; 211 | shellPath = /bin/sh; 212 | shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" embed_and_thin"; 213 | }; 214 | 9740EEB61CF901F6004384FC /* Run Script */ = { 215 | isa = PBXShellScriptBuildPhase; 216 | buildActionMask = 2147483647; 217 | files = ( 218 | ); 219 | inputPaths = ( 220 | ); 221 | name = "Run Script"; 222 | outputPaths = ( 223 | ); 224 | runOnlyForDeploymentPostprocessing = 0; 225 | shellPath = /bin/sh; 226 | shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" build"; 227 | }; 228 | D3B3EAE0BF14CBEE3E3342F5 /* [CP] Check Pods Manifest.lock */ = { 229 | isa = PBXShellScriptBuildPhase; 230 | buildActionMask = 2147483647; 231 | files = ( 232 | ); 233 | inputFileListPaths = ( 234 | ); 235 | inputPaths = ( 236 | "${PODS_PODFILE_DIR_PATH}/Podfile.lock", 237 | "${PODS_ROOT}/Manifest.lock", 238 | ); 239 | name = "[CP] Check Pods Manifest.lock"; 240 | outputFileListPaths = ( 241 | ); 242 | outputPaths = ( 243 | "$(DERIVED_FILE_DIR)/Pods-Runner-checkManifestLockResult.txt", 244 | ); 245 | runOnlyForDeploymentPostprocessing = 0; 246 | shellPath = /bin/sh; 247 | shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; 248 | showEnvVarsInLog = 0; 249 | }; 250 | DEBF1FBFC6B17A06298C5BBF /* [CP] Embed Pods Frameworks */ = { 251 | isa = PBXShellScriptBuildPhase; 252 | buildActionMask = 2147483647; 253 | files = ( 254 | ); 255 | inputFileListPaths = ( 256 | "${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks-${CONFIGURATION}-input-files.xcfilelist", 257 | ); 258 | name = "[CP] Embed Pods Frameworks"; 259 | outputFileListPaths = ( 260 | "${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks-${CONFIGURATION}-output-files.xcfilelist", 261 | ); 262 | runOnlyForDeploymentPostprocessing = 0; 263 | shellPath = /bin/sh; 264 | shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks.sh\"\n"; 265 | showEnvVarsInLog = 0; 266 | }; 267 | /* End PBXShellScriptBuildPhase section */ 268 | 269 | /* Begin PBXSourcesBuildPhase section */ 270 | 97C146EA1CF9000F007C117D /* Sources */ = { 271 | isa = PBXSourcesBuildPhase; 272 | buildActionMask = 2147483647; 273 | files = ( 274 | 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */, 275 | 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */, 276 | ); 277 | runOnlyForDeploymentPostprocessing = 0; 278 | }; 279 | /* End PBXSourcesBuildPhase section */ 280 | 281 | /* Begin PBXVariantGroup section */ 282 | 97C146FA1CF9000F007C117D /* Main.storyboard */ = { 283 | isa = PBXVariantGroup; 284 | children = ( 285 | 97C146FB1CF9000F007C117D /* Base */, 286 | ); 287 | name = Main.storyboard; 288 | sourceTree = ""; 289 | }; 290 | 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */ = { 291 | isa = PBXVariantGroup; 292 | children = ( 293 | 97C147001CF9000F007C117D /* Base */, 294 | ); 295 | name = LaunchScreen.storyboard; 296 | sourceTree = ""; 297 | }; 298 | /* End PBXVariantGroup section */ 299 | 300 | /* Begin XCBuildConfiguration section */ 301 | 249021D3217E4FDB00AE95B9 /* Profile */ = { 302 | isa = XCBuildConfiguration; 303 | buildSettings = { 304 | ALWAYS_SEARCH_USER_PATHS = NO; 305 | CLANG_ANALYZER_NONNULL = YES; 306 | CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; 307 | CLANG_CXX_LIBRARY = "libc++"; 308 | CLANG_ENABLE_MODULES = YES; 309 | CLANG_ENABLE_OBJC_ARC = YES; 310 | CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; 311 | CLANG_WARN_BOOL_CONVERSION = YES; 312 | CLANG_WARN_COMMA = YES; 313 | CLANG_WARN_CONSTANT_CONVERSION = YES; 314 | CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; 315 | CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; 316 | CLANG_WARN_EMPTY_BODY = YES; 317 | CLANG_WARN_ENUM_CONVERSION = YES; 318 | CLANG_WARN_INFINITE_RECURSION = YES; 319 | CLANG_WARN_INT_CONVERSION = YES; 320 | CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; 321 | CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; 322 | CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; 323 | CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; 324 | CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; 325 | CLANG_WARN_STRICT_PROTOTYPES = YES; 326 | CLANG_WARN_SUSPICIOUS_MOVE = YES; 327 | CLANG_WARN_UNREACHABLE_CODE = YES; 328 | CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; 329 | "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; 330 | COPY_PHASE_STRIP = NO; 331 | DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; 332 | ENABLE_NS_ASSERTIONS = NO; 333 | ENABLE_STRICT_OBJC_MSGSEND = YES; 334 | GCC_C_LANGUAGE_STANDARD = gnu99; 335 | GCC_NO_COMMON_BLOCKS = YES; 336 | GCC_WARN_64_TO_32_BIT_CONVERSION = YES; 337 | GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; 338 | GCC_WARN_UNDECLARED_SELECTOR = YES; 339 | GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; 340 | GCC_WARN_UNUSED_FUNCTION = YES; 341 | GCC_WARN_UNUSED_VARIABLE = YES; 342 | IPHONEOS_DEPLOYMENT_TARGET = 9.0; 343 | MTL_ENABLE_DEBUG_INFO = NO; 344 | SDKROOT = iphoneos; 345 | SUPPORTED_PLATFORMS = iphoneos; 346 | TARGETED_DEVICE_FAMILY = "1,2"; 347 | VALIDATE_PRODUCT = YES; 348 | }; 349 | name = Profile; 350 | }; 351 | 249021D4217E4FDB00AE95B9 /* Profile */ = { 352 | isa = XCBuildConfiguration; 353 | baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; 354 | buildSettings = { 355 | ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; 356 | CLANG_ENABLE_MODULES = YES; 357 | CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; 358 | DEVELOPMENT_TEAM = 4H8MP8GT89; 359 | ENABLE_BITCODE = NO; 360 | INFOPLIST_FILE = Runner/Info.plist; 361 | LD_RUNPATH_SEARCH_PATHS = ( 362 | "$(inherited)", 363 | "@executable_path/Frameworks", 364 | ); 365 | PRODUCT_BUNDLE_IDENTIFIER = com.example.example; 366 | PRODUCT_NAME = "$(TARGET_NAME)"; 367 | SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; 368 | SWIFT_VERSION = 5.0; 369 | VERSIONING_SYSTEM = "apple-generic"; 370 | }; 371 | name = Profile; 372 | }; 373 | 97C147031CF9000F007C117D /* Debug */ = { 374 | isa = XCBuildConfiguration; 375 | buildSettings = { 376 | ALWAYS_SEARCH_USER_PATHS = NO; 377 | CLANG_ANALYZER_NONNULL = YES; 378 | CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; 379 | CLANG_CXX_LIBRARY = "libc++"; 380 | CLANG_ENABLE_MODULES = YES; 381 | CLANG_ENABLE_OBJC_ARC = YES; 382 | CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; 383 | CLANG_WARN_BOOL_CONVERSION = YES; 384 | CLANG_WARN_COMMA = YES; 385 | CLANG_WARN_CONSTANT_CONVERSION = YES; 386 | CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; 387 | CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; 388 | CLANG_WARN_EMPTY_BODY = YES; 389 | CLANG_WARN_ENUM_CONVERSION = YES; 390 | CLANG_WARN_INFINITE_RECURSION = YES; 391 | CLANG_WARN_INT_CONVERSION = YES; 392 | CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; 393 | CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; 394 | CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; 395 | CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; 396 | CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; 397 | CLANG_WARN_STRICT_PROTOTYPES = YES; 398 | CLANG_WARN_SUSPICIOUS_MOVE = YES; 399 | CLANG_WARN_UNREACHABLE_CODE = YES; 400 | CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; 401 | "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; 402 | COPY_PHASE_STRIP = NO; 403 | DEBUG_INFORMATION_FORMAT = dwarf; 404 | ENABLE_STRICT_OBJC_MSGSEND = YES; 405 | ENABLE_TESTABILITY = YES; 406 | GCC_C_LANGUAGE_STANDARD = gnu99; 407 | GCC_DYNAMIC_NO_PIC = NO; 408 | GCC_NO_COMMON_BLOCKS = YES; 409 | GCC_OPTIMIZATION_LEVEL = 0; 410 | GCC_PREPROCESSOR_DEFINITIONS = ( 411 | "DEBUG=1", 412 | "$(inherited)", 413 | ); 414 | GCC_WARN_64_TO_32_BIT_CONVERSION = YES; 415 | GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; 416 | GCC_WARN_UNDECLARED_SELECTOR = YES; 417 | GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; 418 | GCC_WARN_UNUSED_FUNCTION = YES; 419 | GCC_WARN_UNUSED_VARIABLE = YES; 420 | IPHONEOS_DEPLOYMENT_TARGET = 9.0; 421 | MTL_ENABLE_DEBUG_INFO = YES; 422 | ONLY_ACTIVE_ARCH = YES; 423 | SDKROOT = iphoneos; 424 | TARGETED_DEVICE_FAMILY = "1,2"; 425 | }; 426 | name = Debug; 427 | }; 428 | 97C147041CF9000F007C117D /* Release */ = { 429 | isa = XCBuildConfiguration; 430 | buildSettings = { 431 | ALWAYS_SEARCH_USER_PATHS = NO; 432 | CLANG_ANALYZER_NONNULL = YES; 433 | CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; 434 | CLANG_CXX_LIBRARY = "libc++"; 435 | CLANG_ENABLE_MODULES = YES; 436 | CLANG_ENABLE_OBJC_ARC = YES; 437 | CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; 438 | CLANG_WARN_BOOL_CONVERSION = YES; 439 | CLANG_WARN_COMMA = YES; 440 | CLANG_WARN_CONSTANT_CONVERSION = YES; 441 | CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; 442 | CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; 443 | CLANG_WARN_EMPTY_BODY = YES; 444 | CLANG_WARN_ENUM_CONVERSION = YES; 445 | CLANG_WARN_INFINITE_RECURSION = YES; 446 | CLANG_WARN_INT_CONVERSION = YES; 447 | CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; 448 | CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; 449 | CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; 450 | CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; 451 | CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; 452 | CLANG_WARN_STRICT_PROTOTYPES = YES; 453 | CLANG_WARN_SUSPICIOUS_MOVE = YES; 454 | CLANG_WARN_UNREACHABLE_CODE = YES; 455 | CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; 456 | "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; 457 | COPY_PHASE_STRIP = NO; 458 | DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; 459 | ENABLE_NS_ASSERTIONS = NO; 460 | ENABLE_STRICT_OBJC_MSGSEND = YES; 461 | GCC_C_LANGUAGE_STANDARD = gnu99; 462 | GCC_NO_COMMON_BLOCKS = YES; 463 | GCC_WARN_64_TO_32_BIT_CONVERSION = YES; 464 | GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; 465 | GCC_WARN_UNDECLARED_SELECTOR = YES; 466 | GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; 467 | GCC_WARN_UNUSED_FUNCTION = YES; 468 | GCC_WARN_UNUSED_VARIABLE = YES; 469 | IPHONEOS_DEPLOYMENT_TARGET = 9.0; 470 | MTL_ENABLE_DEBUG_INFO = NO; 471 | SDKROOT = iphoneos; 472 | SUPPORTED_PLATFORMS = iphoneos; 473 | SWIFT_COMPILATION_MODE = wholemodule; 474 | SWIFT_OPTIMIZATION_LEVEL = "-O"; 475 | TARGETED_DEVICE_FAMILY = "1,2"; 476 | VALIDATE_PRODUCT = YES; 477 | }; 478 | name = Release; 479 | }; 480 | 97C147061CF9000F007C117D /* Debug */ = { 481 | isa = XCBuildConfiguration; 482 | baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */; 483 | buildSettings = { 484 | ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; 485 | CLANG_ENABLE_MODULES = YES; 486 | CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; 487 | DEVELOPMENT_TEAM = 4H8MP8GT89; 488 | ENABLE_BITCODE = NO; 489 | INFOPLIST_FILE = Runner/Info.plist; 490 | LD_RUNPATH_SEARCH_PATHS = ( 491 | "$(inherited)", 492 | "@executable_path/Frameworks", 493 | ); 494 | PRODUCT_BUNDLE_IDENTIFIER = com.example.example; 495 | PRODUCT_NAME = "$(TARGET_NAME)"; 496 | SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; 497 | SWIFT_OPTIMIZATION_LEVEL = "-Onone"; 498 | SWIFT_VERSION = 5.0; 499 | VERSIONING_SYSTEM = "apple-generic"; 500 | }; 501 | name = Debug; 502 | }; 503 | 97C147071CF9000F007C117D /* Release */ = { 504 | isa = XCBuildConfiguration; 505 | baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; 506 | buildSettings = { 507 | ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; 508 | CLANG_ENABLE_MODULES = YES; 509 | CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; 510 | DEVELOPMENT_TEAM = 4H8MP8GT89; 511 | ENABLE_BITCODE = NO; 512 | INFOPLIST_FILE = Runner/Info.plist; 513 | LD_RUNPATH_SEARCH_PATHS = ( 514 | "$(inherited)", 515 | "@executable_path/Frameworks", 516 | ); 517 | PRODUCT_BUNDLE_IDENTIFIER = com.example.example; 518 | PRODUCT_NAME = "$(TARGET_NAME)"; 519 | SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; 520 | SWIFT_VERSION = 5.0; 521 | VERSIONING_SYSTEM = "apple-generic"; 522 | }; 523 | name = Release; 524 | }; 525 | /* End XCBuildConfiguration section */ 526 | 527 | /* Begin XCConfigurationList section */ 528 | 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */ = { 529 | isa = XCConfigurationList; 530 | buildConfigurations = ( 531 | 97C147031CF9000F007C117D /* Debug */, 532 | 97C147041CF9000F007C117D /* Release */, 533 | 249021D3217E4FDB00AE95B9 /* Profile */, 534 | ); 535 | defaultConfigurationIsVisible = 0; 536 | defaultConfigurationName = Release; 537 | }; 538 | 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */ = { 539 | isa = XCConfigurationList; 540 | buildConfigurations = ( 541 | 97C147061CF9000F007C117D /* Debug */, 542 | 97C147071CF9000F007C117D /* Release */, 543 | 249021D4217E4FDB00AE95B9 /* Profile */, 544 | ); 545 | defaultConfigurationIsVisible = 0; 546 | defaultConfigurationName = Release; 547 | }; 548 | /* End XCConfigurationList section */ 549 | }; 550 | rootObject = 97C146E61CF9000F007C117D /* Project object */; 551 | } 552 | --------------------------------------------------------------------------------