├── .editorconfig ├── .fvmrc ├── .github └── workflows │ └── pr-checks.yaml ├── .gitignore ├── .idea ├── copyright │ ├── Apache_2_0.xml │ └── profiles_settings.xml └── runConfigurations │ └── example_lib_main_dart.xml ├── .metadata ├── .pubignore ├── CHANGELOG.md ├── LICENSE ├── README.md ├── analysis_options.yaml ├── android ├── .gitignore ├── .idea │ ├── .gitignore │ ├── .name │ ├── compiler.xml │ ├── encodings.xml │ ├── gradle.xml │ ├── jarRepositories.xml │ ├── misc.xml │ └── vcs.xml ├── build.gradle ├── gradle.properties ├── gradle │ └── wrapper │ │ └── gradle-wrapper.properties ├── settings.gradle └── src │ └── main │ ├── AndroidManifest.xml │ └── kotlin │ └── com │ └── nimroddayan │ └── flutternsd │ └── FlutterNsdPlugin.kt ├── apple └── Classes │ └── SwiftFlutterNsdPlugin.swift ├── example ├── .fvmrc ├── .gitignore ├── .metadata ├── .pubignore ├── README.md ├── analysis_options.yaml ├── android │ ├── .gitignore │ ├── app │ │ ├── build.gradle.kts │ │ └── src │ │ │ ├── debug │ │ │ └── AndroidManifest.xml │ │ │ ├── main │ │ │ ├── AndroidManifest.xml │ │ │ ├── kotlin │ │ │ │ └── com │ │ │ │ │ └── nimroddayan │ │ │ │ │ └── flutternsd │ │ │ │ │ └── example │ │ │ │ │ ├── ExampleApp.kt │ │ │ │ │ └── MainActivity.kt │ │ │ └── res │ │ │ │ ├── drawable │ │ │ │ └── launch_background.xml │ │ │ │ ├── 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 │ │ │ │ └── values │ │ │ │ └── styles.xml │ │ │ └── profile │ │ │ └── AndroidManifest.xml │ ├── build.gradle.kts │ ├── gradle.properties │ ├── gradle │ │ └── wrapper │ │ │ └── gradle-wrapper.properties │ └── settings.gradle.kts ├── ios │ ├── .gitignore │ ├── Flutter │ │ ├── AppFrameworkInfo.plist │ │ ├── Debug.xcconfig │ │ └── Release.xcconfig │ ├── Podfile │ ├── Podfile.lock │ ├── Runner.xcodeproj │ │ ├── project.pbxproj │ │ ├── project.xcworkspace │ │ │ ├── contents.xcworkspacedata │ │ │ └── xcshareddata │ │ │ │ ├── IDEWorkspaceChecks.plist │ │ │ │ └── WorkspaceSettings.xcsettings │ │ └── xcshareddata │ │ │ └── xcschemes │ │ │ └── Runner.xcscheme │ ├── Runner.xcworkspace │ │ ├── contents.xcworkspacedata │ │ └── xcshareddata │ │ │ ├── IDEWorkspaceChecks.plist │ │ │ └── WorkspaceSettings.xcsettings │ └── Runner │ │ ├── AppDelegate.swift │ │ ├── Assets.xcassets │ │ ├── AppIcon.appiconset │ │ │ ├── Contents.json │ │ │ ├── Icon-App-1024x1024@1x.png │ │ │ ├── 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-83.5x83.5@2x.png │ │ └── LaunchImage.imageset │ │ │ ├── Contents.json │ │ │ ├── LaunchImage.png │ │ │ ├── LaunchImage@2x.png │ │ │ ├── LaunchImage@3x.png │ │ │ └── README.md │ │ ├── Base.lproj │ │ ├── LaunchScreen.storyboard │ │ └── Main.storyboard │ │ ├── Info.plist │ │ └── Runner-Bridging-Header.h ├── lib │ └── main.dart ├── macos │ ├── .gitignore │ ├── Flutter │ │ ├── Flutter-Debug.xcconfig │ │ ├── Flutter-Release.xcconfig │ │ └── GeneratedPluginRegistrant.swift │ ├── Podfile │ ├── Podfile.lock │ ├── Runner.xcodeproj │ │ ├── project.pbxproj │ │ ├── project.xcworkspace │ │ │ └── xcshareddata │ │ │ │ └── IDEWorkspaceChecks.plist │ │ └── xcshareddata │ │ │ └── xcschemes │ │ │ └── Runner.xcscheme │ ├── Runner.xcworkspace │ │ ├── contents.xcworkspacedata │ │ └── xcshareddata │ │ │ └── IDEWorkspaceChecks.plist │ └── Runner │ │ ├── AppDelegate.swift │ │ ├── Assets.xcassets │ │ └── AppIcon.appiconset │ │ │ ├── Contents.json │ │ │ ├── app_icon_1024.png │ │ │ ├── app_icon_128.png │ │ │ ├── app_icon_16.png │ │ │ ├── app_icon_256.png │ │ │ ├── app_icon_32.png │ │ │ ├── app_icon_512.png │ │ │ └── app_icon_64.png │ │ ├── Base.lproj │ │ └── MainMenu.xib │ │ ├── Configs │ │ ├── AppInfo.xcconfig │ │ ├── Debug.xcconfig │ │ ├── Release.xcconfig │ │ └── Warnings.xcconfig │ │ ├── DebugProfile.entitlements │ │ ├── Info.plist │ │ ├── MainFlutterWindow.swift │ │ └── Release.entitlements ├── pubspec.lock ├── pubspec.yaml └── windows │ ├── .gitignore │ ├── CMakeLists.txt │ ├── flutter │ ├── CMakeLists.txt │ ├── generated_plugin_registrant.cc │ ├── generated_plugin_registrant.h │ └── generated_plugins.cmake │ └── runner │ ├── CMakeLists.txt │ ├── Runner.rc │ ├── flutter_window.cpp │ ├── flutter_window.h │ ├── main.cpp │ ├── resource.h │ ├── resources │ └── app_icon.ico │ ├── run_loop.cpp │ ├── run_loop.h │ ├── runner.exe.manifest │ ├── utils.cpp │ ├── utils.h │ ├── win32_window.cpp │ └── win32_window.h ├── ios ├── .gitignore ├── Assets │ └── .gitkeep ├── Classes │ ├── FlutterNsdPlugin.h │ ├── FlutterNsdPlugin.m │ └── SwiftFlutterNsdPlugin.swift └── flutter_nsd.podspec ├── lib └── flutter_nsd.dart ├── macos ├── Classes │ └── SwiftFlutterNsdPlugin.swift └── flutter_nsd.podspec ├── pubspec.yaml ├── test └── flutter_nsd_test.dart └── windows ├── .gitignore ├── CMakeLists.txt ├── flutter_nsd_plugin.cpp ├── include └── flutter_nsd │ └── flutter_nsd_plugin.h ├── mdns.h ├── mdns_impl.c └── mdns_impl.h /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | charset = utf-8 5 | end_of_line = lf 6 | indent_size = 2 7 | indent_style = space 8 | insert_final_newline = true 9 | trim_trailing_whitespace = true 10 | 11 | [*.dart] 12 | indent_brace_style = K&R 13 | -------------------------------------------------------------------------------- /.fvmrc: -------------------------------------------------------------------------------- 1 | { 2 | "flutter": "3.29.3", 3 | "flavors": {} 4 | } -------------------------------------------------------------------------------- /.github/workflows/pr-checks.yaml: -------------------------------------------------------------------------------- 1 | name: PR checks 2 | 3 | on: 4 | workflow_dispatch: 5 | pull_request: 6 | branches: [master] 7 | 8 | jobs: 9 | android-build: 10 | name: Android example build 11 | runs-on: ubuntu-latest 12 | steps: 13 | - uses: actions/checkout@v4 14 | - uses: actions/setup-java@v4 15 | with: 16 | distribution: 'zulu' 17 | java-version: '17' 18 | - uses: kuhnroyal/flutter-fvm-config-action/setup@v3 19 | - run: flutter pub get 20 | working-directory: example 21 | - run: flutter build apk 22 | working-directory: example 23 | - uses: actions/upload-artifact@v4 24 | with: 25 | name: android-build 26 | path: | 27 | example/build/app/outputs/flutter-apk/app-release.apk 28 | flutter-lint: 29 | name: Flutter lint 30 | runs-on: ubuntu-latest 31 | steps: 32 | - uses: actions/checkout@v4 33 | - uses: kuhnroyal/flutter-fvm-config-action/setup@v3 34 | - run: | 35 | flutter pub get 36 | flutter analyze 37 | 38 | ios-build: 39 | name: iOS build 40 | runs-on: macos-latest 41 | steps: 42 | - uses: actions/checkout@v4 43 | - uses: kuhnroyal/flutter-fvm-config-action/setup@v3 44 | - run: flutter pub get 45 | working-directory: example 46 | - run: flutter build ios --release --no-codesign 47 | working-directory: example 48 | - uses: actions/upload-artifact@v4 49 | with: 50 | name: ios-build 51 | path: | 52 | example/build/ios/iphoneos/Runner.app 53 | 54 | macos-build: 55 | name: MacOS Build 56 | runs-on: macos-latest 57 | steps: 58 | - uses: actions/checkout@v4 59 | - uses: kuhnroyal/flutter-fvm-config-action/setup@v3 60 | - run: flutter config --enable-macos-desktop 61 | working-directory: example 62 | - run: flutter build macos 63 | working-directory: example 64 | - uses: actions/upload-artifact@v4 65 | with: 66 | name: windows-build 67 | path: | 68 | example/build/macos/Build/Products/Release/flutter_nsd_example.app 69 | 70 | windows-build: 71 | name: Windows build 72 | runs-on: windows-latest 73 | steps: 74 | - uses: actions/checkout@v4 75 | - uses: kuhnroyal/flutter-fvm-config-action/setup@v3 76 | - run: | 77 | cd example/ 78 | flutter config --enable-windows-desktop 79 | flutter build windows 80 | - uses: actions/upload-artifact@v4 81 | with: 82 | name: windows-build 83 | path: | 84 | example/build/windows/runner/Release/ 85 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Miscellaneous 2 | *.class 3 | *.log 4 | *.pyc 5 | *.swp 6 | .DS_Store 7 | .atom/ 8 | .buildlog/ 9 | .history 10 | .svn/ 11 | migrate_working_dir/ 12 | 13 | # IntelliJ related 14 | *.iml 15 | *.ipr 16 | *.iws 17 | !.idea/copyright/Apache_2_0.xml 18 | !.idea/copyright/profiles_settings.xml 19 | !.idea/runConfigurations/example_lib_main_dart.xml 20 | .idea/**/* 21 | 22 | # The .vscode folder contains launch configuration and tasks you configure in 23 | # VS Code which you may wish to be included in version control, so this line 24 | # is commented out by default. 25 | #.vscode/ 26 | 27 | # Flutter/Dart/Pub related 28 | **/doc/api/ 29 | **/ios/Flutter/.last_build_id 30 | .dart_tool/ 31 | .flutter-plugins 32 | .flutter-plugins-dependencies 33 | .packages 34 | .pub-cache/ 35 | .pub/ 36 | /build/ 37 | pubspec.lock 38 | 39 | # Symbolication related 40 | app.*.symbols 41 | 42 | # Obfuscation related 43 | app.*.map.json 44 | 45 | # Android Studio will place build artifacts here 46 | /android/app/debug 47 | /android/app/profile 48 | /android/app/release 49 | 50 | # FVM Version Cache 51 | .fvm/ 52 | -------------------------------------------------------------------------------- /.idea/copyright/Apache_2_0.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 6 | -------------------------------------------------------------------------------- /.idea/copyright/profiles_settings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | -------------------------------------------------------------------------------- /.idea/runConfigurations/example_lib_main_dart.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 6 | -------------------------------------------------------------------------------- /.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: bbfbf1770cca2da7c82e887e4e4af910034800b6 8 | channel: unknown 9 | 10 | project_type: plugin 11 | -------------------------------------------------------------------------------- /.pubignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | .dart_tool/ 3 | .fvm/ 4 | .packages 5 | .pub/ 6 | pubspec.lock 7 | build/ 8 | .idea/ 9 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | ## 1.6.0 2 | Updated to Flutter 3.29.3 3 | 4 | ## 1.5.0 5 | Fixed #22: NsdServiceInfo now includes a list of addresses for the service (ipv4 or ipv6). This is 6 | currently not supported on iOS or macOS 7 | 8 | 9 | 10 | ## 1.4.0 11 | Added support for Kotlin 1.5.20 12 | 13 | ## 1.3.3 14 | 15 | Fixed #33: Windows: TXT records are returned as string instead of UInt8List, causing failure (Thanks @jnstahl) 16 | Fixed #36: Windows: txt records are sent as [key: key] instead of [key: value] (Thanks @jnstahl) 17 | 18 | ## 1.3.2 19 | 20 | This release is identical in functionality to the previous one. It only fixes pub.dev analysis 21 | errors. 22 | 23 | * Fixed: pub.dev analsis error 24 | 25 | ## 1.3.1 26 | 27 | This release is identical in functionality to the previous one. It only fixes pub.dev analysis 28 | errors. 29 | 30 | * Fixed #27: Address pub.dev static analysis 31 | * Fixed various lint errors 32 | 33 | ## 1.3.0 34 | 35 | * Fixed #10: Make pubspec description valid 36 | * Added #11 MacOS desktop support 37 | * Added #16 Support for Windows (Thanks @jnstahl) 38 | 39 | ## 1.2.0 40 | 41 | * #6 Android: Fixed failure to resolve service sequentially (Thanks @julianscheel). 42 | 43 | ## 1.1.0 44 | 45 | * Fixed #3: discovery can't start after hot-restart (thanks @julianscheel). `NsdError` now has 46 | a property that provides more info about the error via the new enum `NsdErrorCode`. Check the 47 | example for more info how to use it. 48 | 49 | ## 1.0.0 50 | 51 | * Changed version scheme to adhere to pub version guidelines (dropping the 'alpha') 52 | * Updated README.md with detailed instructions on support for iOS 14 53 | * Removed Flutter version bounds so that the plugin can be used with Flutter 2+ 54 | 55 | ## 1.0.0-alpha03 56 | 57 | * Increased Dart SDK to 2.12.0-0 58 | * Added Null Safety support 59 | * Added TXT record to NsdServiceInfo (thanks @pheki) 60 | 61 | ## 1.0.0-alpha02 62 | 63 | * Fixed 'stream has already been listened to' 64 | 65 | ## 1.0.0-alpha01 66 | 67 | * Support service discovery on iOS and Android 68 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2017 Nimrod Dayan 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Flutter Network Service Discovery plugin 2 | 3 | A Flutter plugin for Network Service Discovery (mDNS) on Android, iOS, MacOS and Windows. The plugin uses the platform's own API when possible. 4 | 5 | The plugin currently only supports discovery, but not registry of services. 6 | 7 | ## Install 8 | 9 | Add the dependency to pubspec.yaml: 10 | 11 | ``` 12 | dependencies: 13 | flutter_nsd: ^1.6.0 14 | ``` 15 | 16 | ## Getting Started 17 | 18 | Initialize `FlutterNsd` singleton and listen to the stream: 19 | 20 | ```dart 21 | void init() async { 22 | final flutterNsd = FlutterNsd(); 23 | 24 | flutterNsd.stream.listen((nsdServiceInfo) { 25 | print('Discovered service name: ${nsdServiceInfo.name}'); 26 | print('Discovered service hostname/IP: ${nsdServiceInfo.hostname}'); 27 | print('Discovered service port: ${nsdServiceInfo.port}'); 28 | }, onError: (e) { 29 | if (e is NsdError) { 30 | // Check e.errorCode for the specific error 31 | } 32 | }); 33 | } 34 | ``` 35 | 36 | Start discovery when needed. At this point, if any services are discovered, your stream listener 37 | will get notified. In case of an error, `NsdError` is emitted to the stream (Currently it's 38 | just a generic error, but in the future, it will be more specific). 39 | 40 | > Notice that on Android the service name must end with a dot otherwise the service will not be found. 41 | 42 | ```dart 43 | void startDiscoveryButton() async { 44 | await flutterNsd.discoverServices('_http._tcp.'); 45 | } 46 | ``` 47 | 48 | Stop discovery when done. If you don't call this method, discovery will continue until the app 49 | process is killed. 50 | 51 | ```dart 52 | void stopDiscoveryButton() async { 53 | await flutterNsd.stopDiscovery(); 54 | } 55 | 56 | ``` 57 | 58 | See the example project for a more detailed Flutter app example. 59 | 60 | ## Note about Android 61 | 62 | Minimum Android API version supported is 21. 63 | 64 | Android emulator doesn't support Network Service Discovery so you'll have to use a real device. 65 | 66 | ## Note about iOS 67 | 68 | This plugin uses `NetServiceBrowser` and can therefore support iOS version 9+. 69 | 70 | On iOS 14+, you need to modify `Info.plist` file and add two keys: 71 | 72 | * `Bonjour Services` - this is an array, the first item should be the service you're trying to 73 | discover. For example, `_http._tcp.`. 74 | * `Privacy - Local Network Usage Description` - this key is for granting the app local network access. 75 | The value is the text which will be shown to the user in a permission dialog once you call 76 | `flutterNsd.discoverServices()`. 77 | 78 | Example: 79 | 80 | ```xml 81 | NSLocalNetworkUsageDescription 82 | Reasoning for the user why you need this permission goes here 83 | NSBonjourServices 84 | 85 | _http._tcp. 86 | 87 | ``` 88 | 89 | For more info about network discovery on iOS 14, I suggest you watch 90 | this [video](https://developer.apple.com/videos/play/wwdc2020/10110/). 91 | 92 | *Note that you don't need to worry about modifying `Info.plist` if you are just testing with a simulator.* 93 | 94 | The iOS and macOS implementations currently do not return *hostAddresses* 95 | 96 | ## Note about Windows 97 | 98 | Windows does not have native support for MDNS, therefore it is implemented using the https://github.com/mjansson/mdns library 99 | which implements MDNS using sockets. The library will return separate results for ipv4 and ipv6. 100 | 101 | The current implementation will send MDNS multicast every 10 seconds until stopped. 102 | 103 | Due to the native socket calls, any app using this plugin on windows will trigger a dialog from Windows to allow network access on the first launch. 104 | 105 | For Windows development you will need Visual Studio 2019 or higher with the C++ workload installed, see https://docs.flutter.dev/desktop#additional-windows-requirements 106 | 107 | ## Testing 108 | 109 | On MacOS it's easy to test network service discovery via the following command which will create a mock service: 110 | 111 | ``` 112 | dns-sd -R TestService _http._tcp . 3000 113 | ``` 114 | 115 | Then scan for this service using the example app on any of the supported platforms. 116 | 117 | ## License 118 | 119 | Copyright 2023 Nimrod Dayan nimroddayan.com 120 | 121 | Licensed under the Apache License, Version 2.0 (the "License"); 122 | you may not use this file except in compliance with the License. 123 | You may obtain a copy of the License at 124 | 125 | http://www.apache.org/licenses/LICENSE-2.0 126 | 127 | Unless required by applicable law or agreed to in writing, software 128 | distributed under the License is distributed on an "AS IS" BASIS, 129 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 130 | See the License for the specific language governing permissions and 131 | limitations under the License. 132 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /android/.idea/.gitignore: -------------------------------------------------------------------------------- 1 | # Default ignored files 2 | /shelf/ 3 | /workspace.xml 4 | caches/ 5 | modules.xml 6 | -------------------------------------------------------------------------------- /android/.idea/.name: -------------------------------------------------------------------------------- 1 | flutter_nsd -------------------------------------------------------------------------------- /android/.idea/compiler.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /android/.idea/encodings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /android/.idea/gradle.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 20 | 21 | -------------------------------------------------------------------------------- /android/.idea/jarRepositories.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 9 | 10 | 14 | 15 | 19 | 20 | 24 | 25 | -------------------------------------------------------------------------------- /android/.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 39 | 40 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 81 | -------------------------------------------------------------------------------- /android/.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /android/build.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2021 Nimrod Dayan nimroddayan.com 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | */ 17 | 18 | plugins { 19 | id "com.android.library" 20 | id "kotlin-android" 21 | } 22 | 23 | group 'com.nimroddayan.flutternsd' 24 | version '1.0-SNAPSHOT' 25 | 26 | rootProject.allprojects { 27 | repositories { 28 | google() 29 | mavenCentral() 30 | } 31 | } 32 | 33 | android { 34 | namespace = "com.nimroddayan.flutternsd" 35 | compileSdkVersion 35 36 | 37 | compileOptions { 38 | sourceCompatibility = JavaVersion.VERSION_11 39 | targetCompatibility = JavaVersion.VERSION_11 40 | } 41 | 42 | kotlinOptions { 43 | jvmTarget = JavaVersion.VERSION_11 44 | } 45 | 46 | sourceSets { 47 | main.java.srcDirs += "src/main/kotlin" 48 | test.java.srcDirs += "src/test/kotlin" 49 | } 50 | 51 | defaultConfig { 52 | minSdk = 21 53 | } 54 | } 55 | 56 | dependencies { 57 | implementation 'com.jakewharton.timber:timber:5.0.1' 58 | } 59 | -------------------------------------------------------------------------------- /android/gradle.properties: -------------------------------------------------------------------------------- 1 | # 2 | # Copyright 2021 Nimrod Dayan nimroddayan.com 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | # 16 | # 17 | 18 | org.gradle.jvmargs=-Xmx1536M 19 | android.enableR8=true 20 | android.useAndroidX=true 21 | android.enableJetifier=true 22 | -------------------------------------------------------------------------------- /android/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | # 2 | # Copyright 2021 Nimrod Dayan nimroddayan.com 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | # 16 | # 17 | 18 | distributionBase=GRADLE_USER_HOME 19 | distributionPath=wrapper/dists 20 | zipStoreBase=GRADLE_USER_HOME 21 | zipStorePath=wrapper/dists 22 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.3-bin.zip 23 | -------------------------------------------------------------------------------- /android/settings.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2021 Nimrod Dayan nimroddayan.com 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | */ 17 | 18 | rootProject.name = 'flutter_nsd' 19 | -------------------------------------------------------------------------------- /android/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /android/src/main/kotlin/com/nimroddayan/flutternsd/FlutterNsdPlugin.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2021 Nimrod Dayan nimroddayan.com 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | */ 17 | 18 | package com.nimroddayan.flutternsd 19 | 20 | import android.net.nsd.NsdManager 21 | import android.net.nsd.NsdServiceInfo 22 | import android.os.Build 23 | import android.os.Build.VERSION_CODES 24 | import android.os.Handler 25 | import android.os.Looper 26 | import androidx.annotation.NonNull 27 | import androidx.core.content.ContextCompat.getSystemService 28 | import io.flutter.embedding.engine.plugins.FlutterPlugin 29 | import io.flutter.plugin.common.MethodCall 30 | import io.flutter.plugin.common.MethodChannel 31 | import io.flutter.plugin.common.MethodChannel.MethodCallHandler 32 | import io.flutter.plugin.common.MethodChannel.Result 33 | import timber.log.Timber 34 | import java.util.LinkedList 35 | import java.util.Queue 36 | 37 | /** FlutterNsdPlugin */ 38 | class FlutterNsdPlugin : FlutterPlugin, MethodCallHandler { 39 | /// The MethodChannel that will the communication between Flutter and native Android 40 | /// 41 | /// This local reference serves to register the plugin with the Flutter Engine and unregister it 42 | /// when the Flutter Engine is detached from the Activity 43 | private lateinit var channel: MethodChannel 44 | 45 | private var nsdManager: NsdManager? = null 46 | 47 | private lateinit var serviceType: String 48 | private lateinit var mainHandler: Handler 49 | 50 | /// The serviceResolveQueue is used to sequence the service resolve calls 51 | /// 52 | /// Android's NsdManager does not allow multiple resolve procedures in 53 | /// parallel, thus they must be sequenced to avoid running into errors if 54 | /// devices are discovered quickly after another. 55 | private var serviceResolveQueue: Queue = LinkedList() 56 | 57 | override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) { 58 | nsdManager = getSystemService(flutterPluginBinding.applicationContext, NsdManager::class.java) 59 | channel = MethodChannel(flutterPluginBinding.binaryMessenger, "com.nimroddayan/flutter_nsd") 60 | mainHandler = Handler(Looper.getMainLooper()) 61 | channel.setMethodCallHandler(this) 62 | Timber.d("Plugin initialized successfully") 63 | } 64 | 65 | override fun onMethodCall(@NonNull call: MethodCall, @NonNull result: Result) { 66 | if (nsdManager == null) { 67 | result.error("1000", "NsdManager not initialized", null) 68 | } 69 | 70 | Timber.d("Method called: ${call.method}") 71 | when (call.method) { 72 | "startDiscovery" -> { 73 | val serviceType = try { 74 | call.argument("serviceType") 75 | } catch (ex: Exception) { 76 | result.error("1002", "service type must be a string", null) 77 | return 78 | } 79 | 80 | if (serviceType == null) { 81 | result.error("1001", "service type cannot be null", null) 82 | return 83 | } 84 | 85 | startDiscovery(serviceType) 86 | result.success(null) 87 | } 88 | "stopDiscovery" -> { 89 | stopDiscovery() 90 | result.success(null) 91 | } 92 | else -> { 93 | result.notImplemented() 94 | } 95 | } 96 | } 97 | 98 | override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) { 99 | channel.setMethodCallHandler(null) 100 | } 101 | 102 | private fun startDiscovery(serviceType: String) { 103 | Timber.d("Staring NSD for service type: $serviceType") 104 | this.serviceType = serviceType 105 | try { 106 | nsdManager?.discoverServices(serviceType, NsdManager.PROTOCOL_DNS_SD, discoveryListener) 107 | } catch (ex: IllegalArgumentException) { 108 | // Happens when the listener is already registered - indicating that there's already 109 | // an ongoing discovery 110 | Timber.w(ex, "Cannot start, NSD is already running") 111 | mainHandler.post { 112 | channel.invokeMethod("onStartDiscoveryFailed", null) 113 | } 114 | } 115 | } 116 | 117 | private fun stopDiscovery() { 118 | Timber.d("Stopping NSD") 119 | try { 120 | nsdManager?.stopServiceDiscovery(discoveryListener) 121 | } catch (ex: IllegalArgumentException) { 122 | // Happens when the listener is not registered - indicating that there was no ongoing 123 | // discovery. 124 | Timber.w(ex, "Cannot stop NSD when it's not started") 125 | mainHandler.post { 126 | channel.invokeMethod("onStopDiscoveryFailed", null) 127 | } 128 | } 129 | } 130 | 131 | private fun resolveService(service: NsdServiceInfo?) { 132 | try { 133 | nsdManager?.resolveService(service, resolveListener) 134 | } catch (e: Exception) { 135 | Timber.w(e, "Cannot resolve service, service resolve in progress") 136 | } 137 | } 138 | 139 | private val discoveryListener = object : NsdManager.DiscoveryListener { 140 | 141 | // Called as soon as service discovery begins. 142 | override fun onDiscoveryStarted(regType: String) { 143 | Timber.d("NSD started") 144 | } 145 | 146 | override fun onServiceFound(service: NsdServiceInfo) { 147 | Timber.d("Service found serviceName: ${service.serviceName} serviceType: ${service.serviceType}") 148 | if (serviceType == service.serviceType) { 149 | Timber.d("Resolving service $service") 150 | serviceResolveQueue.add(service) 151 | 152 | // Resolve service if no other service is currently being 153 | // resolved. Otherwise do nothing here, the service will be 154 | // resolved once other services from the queue were resolved. 155 | if (serviceResolveQueue.count() == 1) { 156 | resolveService(serviceResolveQueue.peek()) 157 | } 158 | } 159 | } 160 | 161 | override fun onServiceLost(service: NsdServiceInfo) { 162 | Timber.v("Service lost $service") 163 | val result = service.toMap() 164 | mainHandler.post { 165 | channel.invokeMethod("onServiceLost", result) 166 | } 167 | } 168 | 169 | override fun onDiscoveryStopped(serviceType: String) { 170 | Timber.d("NSD stopped") 171 | mainHandler.post { 172 | channel.invokeMethod("onDiscoveryStopped", null) 173 | } 174 | } 175 | 176 | override fun onStartDiscoveryFailed(serviceType: String, errorCode: Int) { 177 | Timber.w("Failed to start NSD. Error code $errorCode") 178 | nsdManager?.stopServiceDiscovery(this) 179 | mainHandler.post { 180 | channel.invokeMethod("onStartDiscoveryFailed", errorCode) 181 | } 182 | } 183 | 184 | override fun onStopDiscoveryFailed(serviceType: String, errorCode: Int) { 185 | Timber.w("Failed to stop NSD. Error code $errorCode") 186 | nsdManager?.stopServiceDiscovery(this) 187 | mainHandler.post { 188 | channel.invokeMethod("onStopDiscoveryFailed", errorCode) 189 | } 190 | } 191 | } 192 | 193 | private val resolveListener = object : NsdManager.ResolveListener { 194 | override fun onResolveFailed(serviceInfo: NsdServiceInfo?, errorCode: Int) { 195 | Timber.w("Failed to resolve service $serviceInfo error code: $errorCode") 196 | mainHandler.post { 197 | channel.invokeMethod("onResolveFailed", errorCode) 198 | } 199 | 200 | processQueue() 201 | } 202 | 203 | override fun onServiceResolved(serviceInfo: NsdServiceInfo?) { 204 | val result = serviceInfo.toMap() 205 | mainHandler.post { 206 | channel.invokeMethod("onServiceResolved", result) 207 | } 208 | 209 | processQueue() 210 | } 211 | 212 | private fun processQueue() { 213 | serviceResolveQueue.remove() 214 | // Resolve next service from queue 215 | if (!serviceResolveQueue.isEmpty()) { 216 | resolveService(serviceResolveQueue.peek()) 217 | } 218 | } 219 | } 220 | } 221 | 222 | private fun NsdServiceInfo?.toMap(): Map { 223 | val hostname = this?.host?.canonicalHostName 224 | val port = this?.port 225 | val name = this?.serviceName 226 | val txt = this?.attributes 227 | val hostAddresses = if(Build.VERSION.SDK_INT > VERSION_CODES.UPSIDE_DOWN_CAKE) { 228 | this?.hostAddresses?.map { it.hostAddress } 229 | } else { 230 | listOf(this?.host?.hostAddress) 231 | } 232 | 233 | 234 | Timber.v("Resolved service: $name-$hostname:$port $txt") 235 | return mapOf( 236 | "hostname" to hostname, 237 | "hostAddresses" to hostAddresses, 238 | "port" to port, 239 | "name" to name, 240 | "txt" to txt 241 | ) 242 | } 243 | -------------------------------------------------------------------------------- /apple/Classes/SwiftFlutterNsdPlugin.swift: -------------------------------------------------------------------------------- 1 | #if canImport(FlutterMacOS) 2 | import FlutterMacOS 3 | import Cocoa 4 | #else 5 | import Flutter 6 | import UIKit 7 | #endif 8 | 9 | public class SwiftFlutterNsdPlugin: NSObject, FlutterPlugin, NetServiceBrowserDelegate, NetServiceDelegate { 10 | private var netServiceBrowser: NetServiceBrowser! 11 | private var services = [NetService]() 12 | private var channel: FlutterMethodChannel 13 | 14 | init(channel: FlutterMethodChannel) { 15 | self.channel = channel 16 | self.services.removeAll() 17 | netServiceBrowser = NetServiceBrowser() 18 | super.init() 19 | } 20 | 21 | public static func register(with registrar: FlutterPluginRegistrar) { 22 | #if canImport(FlutterMacOS) 23 | let flutterNsdChannel = FlutterMethodChannel(name: "com.nimroddayan/flutter_nsd", binaryMessenger: registrar.messenger) 24 | #else 25 | let flutterNsdChannel = FlutterMethodChannel(name: "com.nimroddayan/flutter_nsd", binaryMessenger: registrar.messenger()) 26 | #endif 27 | let instance = SwiftFlutterNsdPlugin(channel: flutterNsdChannel) 28 | registrar.addMethodCallDelegate(instance, channel: flutterNsdChannel) 29 | } 30 | 31 | public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) { 32 | switch call.method { 33 | case "startDiscovery": 34 | let args = call.arguments as? [String: Any] 35 | guard let serviceType = args?["serviceType"] as? String else { 36 | result(FlutterError(code: "1001", message: "Service type cannot be null", details: nil)) 37 | return 38 | } 39 | 40 | self.startDiscovery(serviceType) 41 | result(nil) 42 | case "stopDiscovery": 43 | self.stopDiscovery() 44 | result(nil) 45 | default: 46 | result(FlutterMethodNotImplemented) 47 | } 48 | } 49 | 50 | private func startDiscovery(_ serviceType: String) { 51 | netServiceBrowser.delegate = self 52 | netServiceBrowser.searchForServices(ofType: serviceType, inDomain: "") 53 | } 54 | 55 | private func stopDiscovery() { 56 | netServiceBrowser.stop() 57 | } 58 | 59 | private func updateInterface() { 60 | for service in services { 61 | if service.port == -1 { 62 | service.delegate = self 63 | service.resolve(withTimeout: 10) 64 | } 65 | } 66 | } 67 | 68 | public func netServiceBrowser(_ browser: NetServiceBrowser, didNotSearch errorDict: [String : NSNumber]) { 69 | channel.invokeMethod("onStartDiscoveryFailed", arguments: nil); 70 | } 71 | 72 | public func netServiceBrowserDidStopSearch(_ browser: NetServiceBrowser) { 73 | channel.invokeMethod("onDiscoveryStopped", arguments: nil); 74 | netServiceBrowser.delegate = nil 75 | } 76 | 77 | public func netServiceBrowser(_ browser: NetServiceBrowser, didFind service: NetService, moreComing: Bool) { 78 | services.append(service) 79 | if !moreComing { 80 | self.updateInterface() 81 | } 82 | } 83 | 84 | public func netServiceDidResolveAddress(_ sender: NetService) { 85 | var port: Int? = sender.port 86 | if port == -1 { 87 | port = nil 88 | } 89 | var txt: [String: FlutterStandardTypedData]? = nil; 90 | if let txtRecordData = sender.txtRecordData() { 91 | txt = NetService.dictionary(fromTXTRecord: txtRecordData).mapValues( { (value) -> FlutterStandardTypedData in 92 | FlutterStandardTypedData(bytes: value) 93 | }) 94 | } 95 | 96 | let arguments: [String: Any?] = ["hostname": sender.hostName, "port": port, "name": sender.name, "txt": txt]; 97 | 98 | channel.invokeMethod("onServiceResolved", arguments: arguments) 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /example/.fvmrc: -------------------------------------------------------------------------------- 1 | { 2 | "flutter": "3.29.3", 3 | "flavors": {} 4 | } -------------------------------------------------------------------------------- /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 | # Exceptions to above rules. 44 | !/packages/flutter_tools/test/data/dart_dependencies_test/**/.packages 45 | 46 | # FVM Version Cache 47 | .fvm/ 48 | !pubspec.lock 49 | -------------------------------------------------------------------------------- /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: bbfbf1770cca2da7c82e887e4e4af910034800b6 8 | channel: unknown 9 | 10 | project_type: app 11 | -------------------------------------------------------------------------------- /example/.pubignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | .dart_tool/ 3 | .fvm/ 4 | .packages 5 | .pub/ 6 | pubspec.lock 7 | build/ 8 | -------------------------------------------------------------------------------- /example/README.md: -------------------------------------------------------------------------------- 1 | # Flutter NSD plugin example 2 | 3 | Demonstrates how to use the flutter_nsd plugin. 4 | 5 | ## Getting Started 6 | 7 | in `main.dart`, change the service type from `_example._tcp.` to the real service you're trying 8 | to discover. Then simply launch the app on either iOS or Android. Note that for iOS, the example 9 | is currently configured to only work with a simulator. Please see the library README.md for more 10 | info on that. 11 | -------------------------------------------------------------------------------- /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/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 | .idea/caches/ 13 | .cxx/ 14 | .fvm/ 15 | -------------------------------------------------------------------------------- /example/android/app/build.gradle.kts: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2025 Nimrod Dayan nimroddayan.com 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | */ 17 | 18 | plugins { 19 | id("com.android.application") 20 | id("kotlin-android") 21 | // The Flutter Gradle Plugin must be applied after the Android and Kotlin Gradle plugins. 22 | id("dev.flutter.flutter-gradle-plugin") 23 | } 24 | 25 | android { 26 | namespace = "com.nimroddayan.flutternsd.example" 27 | compileSdk = flutter.compileSdkVersion 28 | ndkVersion = flutter.ndkVersion 29 | 30 | ndkVersion = "27.0.12077973" 31 | 32 | compileOptions { 33 | sourceCompatibility = JavaVersion.VERSION_11 34 | targetCompatibility = JavaVersion.VERSION_11 35 | } 36 | 37 | kotlinOptions { 38 | jvmTarget = JavaVersion.VERSION_11.toString() 39 | } 40 | 41 | defaultConfig { 42 | applicationId = "com.nimroddayan.flutternsd.example" 43 | minSdk = flutter.minSdkVersion 44 | targetSdk = flutter.targetSdkVersion 45 | versionCode = flutter.versionCode 46 | versionName = flutter.versionName 47 | } 48 | 49 | buildTypes { 50 | release { 51 | signingConfig = signingConfigs.getByName("debug") 52 | } 53 | } 54 | } 55 | 56 | flutter { 57 | source = "../.." 58 | } 59 | 60 | dependencies { 61 | implementation("com.jakewharton.timber:timber:5.0.1") 62 | } 63 | -------------------------------------------------------------------------------- /example/android/app/src/debug/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 17 | 18 | 20 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /example/android/app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 17 | 18 | 19 | 24 | 28 | 36 | 40 | 44 | 49 | 53 | 54 | 55 | 56 | 57 | 58 | 60 | 63 | 64 | 65 | -------------------------------------------------------------------------------- /example/android/app/src/main/kotlin/com/nimroddayan/flutternsd/example/ExampleApp.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2021 Nimrod Dayan nimroddayan.com 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | */ 17 | 18 | package com.nimroddayan.flutternsd.example 19 | 20 | import io.flutter.app.FlutterApplication 21 | import timber.log.Timber 22 | 23 | class ExampleApp : FlutterApplication() { 24 | override fun onCreate() { 25 | super.onCreate() 26 | Timber.plant(Timber.DebugTree()) 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /example/android/app/src/main/kotlin/com/nimroddayan/flutternsd/example/MainActivity.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2021 Nimrod Dayan nimroddayan.com 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | */ 17 | 18 | package com.nimroddayan.flutternsd.example 19 | 20 | import io.flutter.embedding.android.FlutterActivity 21 | 22 | class MainActivity: FlutterActivity() 23 | -------------------------------------------------------------------------------- /example/android/app/src/main/res/drawable/launch_background.xml: -------------------------------------------------------------------------------- 1 | 2 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 29 | 30 | -------------------------------------------------------------------------------- /example/android/app/src/main/res/mipmap-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Nimrodda/flutter_nsd/5565033b1d76405ca9aaaf79c676a654ddfb6348/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/Nimrodda/flutter_nsd/5565033b1d76405ca9aaaf79c676a654ddfb6348/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/Nimrodda/flutter_nsd/5565033b1d76405ca9aaaf79c676a654ddfb6348/example/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Nimrodda/flutter_nsd/5565033b1d76405ca9aaaf79c676a654ddfb6348/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/Nimrodda/flutter_nsd/5565033b1d76405ca9aaaf79c676a654ddfb6348/example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /example/android/app/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 18 | 19 | 20 | 21 | 26 | 32 | 35 | 36 | -------------------------------------------------------------------------------- /example/android/app/src/profile/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 17 | 18 | 19 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /example/android/build.gradle.kts: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2025 Nimrod Dayan nimroddayan.com 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | */ 17 | 18 | allprojects { 19 | repositories { 20 | google() 21 | mavenCentral() 22 | } 23 | } 24 | 25 | val newBuildDir: Directory = rootProject.layout.buildDirectory.dir("../../build").get() 26 | rootProject.layout.buildDirectory.value(newBuildDir) 27 | 28 | subprojects { 29 | val newSubprojectBuildDir: Directory = newBuildDir.dir(project.name) 30 | project.layout.buildDirectory.value(newSubprojectBuildDir) 31 | } 32 | subprojects { 33 | project.evaluationDependsOn(":app") 34 | } 35 | 36 | tasks.register("clean") { 37 | delete(rootProject.layout.buildDirectory) 38 | } 39 | -------------------------------------------------------------------------------- /example/android/gradle.properties: -------------------------------------------------------------------------------- 1 | # 2 | # Copyright 2021 Nimrod Dayan nimroddayan.com 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | # 16 | # 17 | 18 | org.gradle.jvmargs=-Xmx1536M 19 | android.enableR8=true 20 | android.useAndroidX=true 21 | android.enableJetifier=true 22 | -------------------------------------------------------------------------------- /example/android/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | # 2 | # Copyright 2021 Nimrod Dayan nimroddayan.com 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | # 16 | # 17 | 18 | #Fri Jun 23 08:50:38 CEST 2017 19 | distributionBase=GRADLE_USER_HOME 20 | distributionPath=wrapper/dists 21 | zipStoreBase=GRADLE_USER_HOME 22 | zipStorePath=wrapper/dists 23 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.9-bin.zip 24 | -------------------------------------------------------------------------------- /example/android/settings.gradle.kts: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2025 Nimrod Dayan nimroddayan.com 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | */ 17 | 18 | pluginManagement { 19 | val flutterSdkPath = run { 20 | val properties = java.util.Properties() 21 | file("local.properties").inputStream().use { properties.load(it) } 22 | val flutterSdkPath = properties.getProperty("flutter.sdk") 23 | require(flutterSdkPath != null) { "flutter.sdk not set in local.properties" } 24 | flutterSdkPath 25 | } 26 | 27 | includeBuild("$flutterSdkPath/packages/flutter_tools/gradle") 28 | 29 | repositories { 30 | google() 31 | mavenCentral() 32 | gradlePluginPortal() 33 | } 34 | } 35 | 36 | plugins { 37 | id("dev.flutter.flutter-plugin-loader") version "1.0.0" 38 | id("com.android.application") version "8.7.0" apply false 39 | id("org.jetbrains.kotlin.android") version "1.8.22" apply false 40 | } 41 | 42 | include(":app") 43 | -------------------------------------------------------------------------------- /example/ios/.gitignore: -------------------------------------------------------------------------------- 1 | *.mode1v3 2 | *.mode2v3 3 | *.moved-aside 4 | *.pbxuser 5 | *.perspectivev3 6 | **/*sync/ 7 | .sconsign.dblite 8 | .tags* 9 | **/.vagrant/ 10 | **/DerivedData/ 11 | Icon? 12 | **/Pods/ 13 | **/.symlinks/ 14 | profile 15 | xcuserdata 16 | **/.generated/ 17 | Flutter/App.framework 18 | Flutter/Flutter.framework 19 | Flutter/Flutter.podspec 20 | Flutter/Generated.xcconfig 21 | Flutter/app.flx 22 | Flutter/app.zip 23 | Flutter/flutter_assets/ 24 | Flutter/flutter_export_environment.sh 25 | ServiceDefinitions.json 26 | Runner/GeneratedPluginRegistrant.* 27 | 28 | # Exceptions to above rules. 29 | !default.mode1v3 30 | !default.mode2v3 31 | !default.pbxuser 32 | !default.perspectivev3 33 | -------------------------------------------------------------------------------- /example/ios/Flutter/AppFrameworkInfo.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | $(DEVELOPMENT_LANGUAGE) 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 | 8.0 25 | 26 | 27 | -------------------------------------------------------------------------------- /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/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/ios/Podfile.lock: -------------------------------------------------------------------------------- 1 | PODS: 2 | - Flutter (1.0.0) 3 | - flutter_nsd (0.0.1): 4 | - Flutter 5 | 6 | DEPENDENCIES: 7 | - Flutter (from `Flutter`) 8 | - flutter_nsd (from `.symlinks/plugins/flutter_nsd/ios`) 9 | 10 | EXTERNAL SOURCES: 11 | Flutter: 12 | :path: Flutter 13 | flutter_nsd: 14 | :path: ".symlinks/plugins/flutter_nsd/ios" 15 | 16 | SPEC CHECKSUMS: 17 | Flutter: 434fef37c0980e73bb6479ef766c45957d4b510c 18 | flutter_nsd: e945908005778ba9e7466b7d4dc9ea1c758022d4 19 | 20 | PODFILE CHECKSUM: aafe91acc616949ddb318b77800a7f51bffa2a4c 21 | 22 | COCOAPODS: 1.10.1 23 | -------------------------------------------------------------------------------- /example/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /example/ios/Runner.xcodeproj/project.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/xcshareddata/xcschemes/Runner.xcscheme: -------------------------------------------------------------------------------- 1 | 2 | 5 | 8 | 9 | 15 | 21 | 22 | 23 | 24 | 25 | 30 | 31 | 32 | 33 | 39 | 40 | 41 | 42 | 43 | 44 | 54 | 56 | 62 | 63 | 64 | 65 | 66 | 67 | 73 | 75 | 81 | 82 | 83 | 84 | 86 | 87 | 90 | 91 | 92 | -------------------------------------------------------------------------------- /example/ios/Runner.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /example/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | IDEDidComputeMac32BitWarning 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /example/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | PreviewsEnabled 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /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/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/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Nimrodda/flutter_nsd/5565033b1d76405ca9aaaf79c676a654ddfb6348/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png -------------------------------------------------------------------------------- /example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Nimrodda/flutter_nsd/5565033b1d76405ca9aaaf79c676a654ddfb6348/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/Nimrodda/flutter_nsd/5565033b1d76405ca9aaaf79c676a654ddfb6348/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/Nimrodda/flutter_nsd/5565033b1d76405ca9aaaf79c676a654ddfb6348/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/Nimrodda/flutter_nsd/5565033b1d76405ca9aaaf79c676a654ddfb6348/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/Nimrodda/flutter_nsd/5565033b1d76405ca9aaaf79c676a654ddfb6348/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/Nimrodda/flutter_nsd/5565033b1d76405ca9aaaf79c676a654ddfb6348/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/Nimrodda/flutter_nsd/5565033b1d76405ca9aaaf79c676a654ddfb6348/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/Nimrodda/flutter_nsd/5565033b1d76405ca9aaaf79c676a654ddfb6348/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/Nimrodda/flutter_nsd/5565033b1d76405ca9aaaf79c676a654ddfb6348/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/Nimrodda/flutter_nsd/5565033b1d76405ca9aaaf79c676a654ddfb6348/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/Nimrodda/flutter_nsd/5565033b1d76405ca9aaaf79c676a654ddfb6348/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/Nimrodda/flutter_nsd/5565033b1d76405ca9aaaf79c676a654ddfb6348/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/Nimrodda/flutter_nsd/5565033b1d76405ca9aaaf79c676a654ddfb6348/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png -------------------------------------------------------------------------------- /example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Nimrodda/flutter_nsd/5565033b1d76405ca9aaaf79c676a654ddfb6348/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Nimrodda/flutter_nsd/5565033b1d76405ca9aaaf79c676a654ddfb6348/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png -------------------------------------------------------------------------------- /example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Nimrodda/flutter_nsd/5565033b1d76405ca9aaaf79c676a654ddfb6348/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png -------------------------------------------------------------------------------- /example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Nimrodda/flutter_nsd/5565033b1d76405ca9aaaf79c676a654ddfb6348/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png -------------------------------------------------------------------------------- /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. -------------------------------------------------------------------------------- /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/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 | -------------------------------------------------------------------------------- /example/ios/Runner/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | $(DEVELOPMENT_LANGUAGE) 7 | CFBundleExecutable 8 | $(EXECUTABLE_NAME) 9 | CFBundleIdentifier 10 | $(PRODUCT_BUNDLE_IDENTIFIER) 11 | CFBundleInfoDictionaryVersion 12 | 6.0 13 | CFBundleName 14 | flutter_nsd_example 15 | CFBundlePackageType 16 | APPL 17 | CFBundleShortVersionString 18 | $(FLUTTER_BUILD_NAME) 19 | CFBundleSignature 20 | ???? 21 | CFBundleVersion 22 | $(FLUTTER_BUILD_NUMBER) 23 | LSRequiresIPhoneOS 24 | 25 | NSLocalNetworkUsageDescription 26 | Approve to scan local network 27 | UILaunchStoryboardName 28 | LaunchScreen 29 | UIMainStoryboardFile 30 | Main 31 | UISupportedInterfaceOrientations 32 | 33 | UIInterfaceOrientationPortrait 34 | UIInterfaceOrientationLandscapeLeft 35 | UIInterfaceOrientationLandscapeRight 36 | 37 | UISupportedInterfaceOrientations~ipad 38 | 39 | UIInterfaceOrientationPortrait 40 | UIInterfaceOrientationPortraitUpsideDown 41 | UIInterfaceOrientationLandscapeLeft 42 | UIInterfaceOrientationLandscapeRight 43 | 44 | UIViewControllerBasedStatusBarAppearance 45 | 46 | NSBonjourServices 47 | 48 | _example._tcp. 49 | 50 | 51 | 52 | -------------------------------------------------------------------------------- /example/ios/Runner/Runner-Bridging-Header.h: -------------------------------------------------------------------------------- 1 | #import "GeneratedPluginRegistrant.h" 2 | -------------------------------------------------------------------------------- /example/lib/main.dart: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2021 Nimrod Dayan nimroddayan.com 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | */ 17 | 18 | import 'package:flutter/material.dart'; 19 | import 'dart:async'; 20 | 21 | import 'package:flutter_nsd/flutter_nsd.dart'; 22 | 23 | void main() { 24 | runApp(const MyApp()); 25 | } 26 | 27 | class MyApp extends StatefulWidget { 28 | const MyApp({Key? key}) : super(key: key); 29 | 30 | @override 31 | State createState() => _MyAppState(); 32 | } 33 | 34 | class _MyAppState extends State { 35 | final flutterNsd = FlutterNsd(); 36 | final services = []; 37 | bool initialStart = true; 38 | bool _scanning = false; 39 | 40 | _MyAppState(); 41 | 42 | @override 43 | void initState() { 44 | super.initState(); 45 | 46 | // Try one restart if initial start fails, which happens on hot-restart of 47 | // the flutter app. 48 | flutterNsd.stream.listen( 49 | (NsdServiceInfo service) { 50 | setState(() { 51 | services.add(service); 52 | }); 53 | }, 54 | onError: (e) async { 55 | if (e is NsdError) { 56 | if (e.errorCode == NsdErrorCode.startDiscoveryFailed && 57 | initialStart) { 58 | await stopDiscovery(); 59 | } else if (e.errorCode == NsdErrorCode.discoveryStopped && 60 | initialStart) { 61 | initialStart = false; 62 | await startDiscovery(); 63 | } 64 | } 65 | }, 66 | ); 67 | } 68 | 69 | Future startDiscovery() async { 70 | if (_scanning) return; 71 | 72 | setState(() { 73 | services.clear(); 74 | _scanning = true; 75 | }); 76 | await flutterNsd.discoverServices('_http._tcp.'); 77 | } 78 | 79 | Future stopDiscovery() async { 80 | if (!_scanning) return; 81 | 82 | setState(() { 83 | services.clear(); 84 | _scanning = false; 85 | }); 86 | flutterNsd.stopDiscovery(); 87 | } 88 | 89 | @override 90 | Widget build(BuildContext context) { 91 | return MaterialApp( 92 | home: Scaffold( 93 | appBar: AppBar( 94 | title: const Text('NSD Example'), 95 | ), 96 | body: Column( 97 | children: [ 98 | Row( 99 | mainAxisAlignment: MainAxisAlignment.spaceEvenly, 100 | children: [ 101 | ElevatedButton( 102 | child: const Text('Start'), 103 | onPressed: () async => startDiscovery(), 104 | ), 105 | ElevatedButton( 106 | child: const Text('Stop'), 107 | onPressed: () async => stopDiscovery(), 108 | ), 109 | ], 110 | ), 111 | Expanded( 112 | child: _buildMainWidget(context), 113 | ), 114 | ], 115 | ), 116 | ), 117 | ); 118 | } 119 | 120 | Widget _buildMainWidget(BuildContext context) { 121 | if (services.isEmpty && _scanning) { 122 | return const Center( 123 | child: CircularProgressIndicator(), 124 | ); 125 | } else if (services.isEmpty && !_scanning) { 126 | return const SizedBox.shrink(); 127 | } else { 128 | return ListView.builder( 129 | itemBuilder: (context, index) => ListTile( 130 | title: Text(services[index].name ?? 'Invalid service name'), 131 | ), 132 | itemCount: services.length, 133 | ); 134 | } 135 | } 136 | } 137 | -------------------------------------------------------------------------------- /example/macos/.gitignore: -------------------------------------------------------------------------------- 1 | # Flutter-related 2 | **/Flutter/ephemeral/ 3 | **/Pods/ 4 | 5 | # Xcode-related 6 | **/xcuserdata/ 7 | -------------------------------------------------------------------------------- /example/macos/Flutter/Flutter-Debug.xcconfig: -------------------------------------------------------------------------------- 1 | #include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig" 2 | #include "ephemeral/Flutter-Generated.xcconfig" 3 | -------------------------------------------------------------------------------- /example/macos/Flutter/Flutter-Release.xcconfig: -------------------------------------------------------------------------------- 1 | #include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig" 2 | #include "ephemeral/Flutter-Generated.xcconfig" 3 | -------------------------------------------------------------------------------- /example/macos/Flutter/GeneratedPluginRegistrant.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Generated file. Do not edit. 3 | // 4 | 5 | import FlutterMacOS 6 | import Foundation 7 | 8 | import flutter_nsd 9 | 10 | func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) { 11 | SwiftFlutterNsdPlugin.register(with: registry.registrar(forPlugin: "SwiftFlutterNsdPlugin")) 12 | } 13 | -------------------------------------------------------------------------------- /example/macos/Podfile: -------------------------------------------------------------------------------- 1 | platform :osx, '10.14' 2 | 3 | # CocoaPods analytics sends network stats synchronously affecting flutter build latency. 4 | ENV['COCOAPODS_DISABLE_STATS'] = 'true' 5 | 6 | project 'Runner', { 7 | 'Debug' => :debug, 8 | 'Profile' => :release, 9 | 'Release' => :release, 10 | } 11 | 12 | def flutter_root 13 | generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'ephemeral', 'Flutter-Generated.xcconfig'), __FILE__) 14 | unless File.exist?(generated_xcode_build_settings_path) 15 | raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure \"flutter pub get\" is executed first" 16 | end 17 | 18 | File.foreach(generated_xcode_build_settings_path) do |line| 19 | matches = line.match(/FLUTTER_ROOT\=(.*)/) 20 | return matches[1].strip if matches 21 | end 22 | raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Flutter-Generated.xcconfig, then run \"flutter pub get\"" 23 | end 24 | 25 | require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root) 26 | 27 | flutter_macos_podfile_setup 28 | 29 | target 'Runner' do 30 | use_frameworks! 31 | use_modular_headers! 32 | 33 | flutter_install_all_macos_pods File.dirname(File.realpath(__FILE__)) 34 | end 35 | 36 | post_install do |installer| 37 | installer.pods_project.targets.each do |target| 38 | flutter_additional_macos_build_settings(target) 39 | end 40 | end 41 | -------------------------------------------------------------------------------- /example/macos/Podfile.lock: -------------------------------------------------------------------------------- 1 | PODS: 2 | - flutter_nsd (0.0.1): 3 | - FlutterMacOS 4 | - FlutterMacOS (1.0.0) 5 | 6 | DEPENDENCIES: 7 | - flutter_nsd (from `Flutter/ephemeral/.symlinks/plugins/flutter_nsd/macos`) 8 | - FlutterMacOS (from `Flutter/ephemeral`) 9 | 10 | EXTERNAL SOURCES: 11 | flutter_nsd: 12 | :path: Flutter/ephemeral/.symlinks/plugins/flutter_nsd/macos 13 | FlutterMacOS: 14 | :path: Flutter/ephemeral 15 | 16 | SPEC CHECKSUMS: 17 | flutter_nsd: 74ca85e30ed7290353c947d044a092abe7c79273 18 | FlutterMacOS: 8f6f14fa908a6fb3fba0cd85dbd81ec4b251fb24 19 | 20 | PODFILE CHECKSUM: 353c8bcc5d5b0994e508d035b5431cfe18c1dea7 21 | 22 | COCOAPODS: 1.16.2 23 | -------------------------------------------------------------------------------- /example/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | IDEDidComputeMac32BitWarning 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /example/macos/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 | 53 | 55 | 61 | 62 | 63 | 64 | 65 | 66 | 72 | 74 | 80 | 81 | 82 | 83 | 85 | 86 | 89 | 90 | 91 | -------------------------------------------------------------------------------- /example/macos/Runner.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /example/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | IDEDidComputeMac32BitWarning 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /example/macos/Runner/AppDelegate.swift: -------------------------------------------------------------------------------- 1 | import Cocoa 2 | import FlutterMacOS 3 | 4 | @main 5 | class AppDelegate: FlutterAppDelegate { 6 | override func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { 7 | return true 8 | } 9 | 10 | override func applicationSupportsSecureRestorableState(_ app: NSApplication) -> Bool { 11 | return true 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /example/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "images" : [ 3 | { 4 | "size" : "16x16", 5 | "idiom" : "mac", 6 | "filename" : "app_icon_16.png", 7 | "scale" : "1x" 8 | }, 9 | { 10 | "size" : "16x16", 11 | "idiom" : "mac", 12 | "filename" : "app_icon_32.png", 13 | "scale" : "2x" 14 | }, 15 | { 16 | "size" : "32x32", 17 | "idiom" : "mac", 18 | "filename" : "app_icon_32.png", 19 | "scale" : "1x" 20 | }, 21 | { 22 | "size" : "32x32", 23 | "idiom" : "mac", 24 | "filename" : "app_icon_64.png", 25 | "scale" : "2x" 26 | }, 27 | { 28 | "size" : "128x128", 29 | "idiom" : "mac", 30 | "filename" : "app_icon_128.png", 31 | "scale" : "1x" 32 | }, 33 | { 34 | "size" : "128x128", 35 | "idiom" : "mac", 36 | "filename" : "app_icon_256.png", 37 | "scale" : "2x" 38 | }, 39 | { 40 | "size" : "256x256", 41 | "idiom" : "mac", 42 | "filename" : "app_icon_256.png", 43 | "scale" : "1x" 44 | }, 45 | { 46 | "size" : "256x256", 47 | "idiom" : "mac", 48 | "filename" : "app_icon_512.png", 49 | "scale" : "2x" 50 | }, 51 | { 52 | "size" : "512x512", 53 | "idiom" : "mac", 54 | "filename" : "app_icon_512.png", 55 | "scale" : "1x" 56 | }, 57 | { 58 | "size" : "512x512", 59 | "idiom" : "mac", 60 | "filename" : "app_icon_1024.png", 61 | "scale" : "2x" 62 | } 63 | ], 64 | "info" : { 65 | "version" : 1, 66 | "author" : "xcode" 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Nimrodda/flutter_nsd/5565033b1d76405ca9aaaf79c676a654ddfb6348/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png -------------------------------------------------------------------------------- /example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Nimrodda/flutter_nsd/5565033b1d76405ca9aaaf79c676a654ddfb6348/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png -------------------------------------------------------------------------------- /example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Nimrodda/flutter_nsd/5565033b1d76405ca9aaaf79c676a654ddfb6348/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png -------------------------------------------------------------------------------- /example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Nimrodda/flutter_nsd/5565033b1d76405ca9aaaf79c676a654ddfb6348/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png -------------------------------------------------------------------------------- /example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Nimrodda/flutter_nsd/5565033b1d76405ca9aaaf79c676a654ddfb6348/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png -------------------------------------------------------------------------------- /example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Nimrodda/flutter_nsd/5565033b1d76405ca9aaaf79c676a654ddfb6348/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png -------------------------------------------------------------------------------- /example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Nimrodda/flutter_nsd/5565033b1d76405ca9aaaf79c676a654ddfb6348/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png -------------------------------------------------------------------------------- /example/macos/Runner/Configs/AppInfo.xcconfig: -------------------------------------------------------------------------------- 1 | // Application-level settings for the Runner target. 2 | // 3 | // This may be replaced with something auto-generated from metadata (e.g., pubspec.yaml) in the 4 | // future. If not, the values below would default to using the project name when this becomes a 5 | // 'flutter create' template. 6 | 7 | // The application's name. By default this is also the title of the Flutter window. 8 | PRODUCT_NAME = flutter_nsd_example 9 | 10 | // The application's bundle identifier 11 | PRODUCT_BUNDLE_IDENTIFIER = com.example.flutterNsdExample 12 | 13 | // The copyright displayed in application information 14 | PRODUCT_COPYRIGHT = Copyright © 2021 com.example. All rights reserved. 15 | -------------------------------------------------------------------------------- /example/macos/Runner/Configs/Debug.xcconfig: -------------------------------------------------------------------------------- 1 | #include "../../Flutter/Flutter-Debug.xcconfig" 2 | #include "Warnings.xcconfig" 3 | -------------------------------------------------------------------------------- /example/macos/Runner/Configs/Release.xcconfig: -------------------------------------------------------------------------------- 1 | #include "../../Flutter/Flutter-Release.xcconfig" 2 | #include "Warnings.xcconfig" 3 | -------------------------------------------------------------------------------- /example/macos/Runner/Configs/Warnings.xcconfig: -------------------------------------------------------------------------------- 1 | WARNING_CFLAGS = -Wall -Wconditional-uninitialized -Wnullable-to-nonnull-conversion -Wmissing-method-return-type -Woverlength-strings 2 | GCC_WARN_UNDECLARED_SELECTOR = YES 3 | CLANG_UNDEFINED_BEHAVIOR_SANITIZER_NULLABILITY = YES 4 | CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE 5 | CLANG_WARN__DUPLICATE_METHOD_MATCH = YES 6 | CLANG_WARN_PRAGMA_PACK = YES 7 | CLANG_WARN_STRICT_PROTOTYPES = YES 8 | CLANG_WARN_COMMA = YES 9 | GCC_WARN_STRICT_SELECTOR_MATCH = YES 10 | CLANG_WARN_OBJC_REPEATED_USE_OF_WEAK = YES 11 | CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES 12 | GCC_WARN_SHADOW = YES 13 | CLANG_WARN_UNREACHABLE_CODE = YES 14 | -------------------------------------------------------------------------------- /example/macos/Runner/DebugProfile.entitlements: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | com.apple.security.app-sandbox 6 | 7 | com.apple.security.cs.allow-jit 8 | 9 | com.apple.security.network.server 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /example/macos/Runner/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | $(DEVELOPMENT_LANGUAGE) 7 | CFBundleExecutable 8 | $(EXECUTABLE_NAME) 9 | CFBundleIconFile 10 | 11 | CFBundleIdentifier 12 | $(PRODUCT_BUNDLE_IDENTIFIER) 13 | CFBundleInfoDictionaryVersion 14 | 6.0 15 | CFBundleName 16 | $(PRODUCT_NAME) 17 | CFBundlePackageType 18 | APPL 19 | CFBundleShortVersionString 20 | $(FLUTTER_BUILD_NAME) 21 | CFBundleVersion 22 | $(FLUTTER_BUILD_NUMBER) 23 | LSMinimumSystemVersion 24 | $(MACOSX_DEPLOYMENT_TARGET) 25 | NSHumanReadableCopyright 26 | $(PRODUCT_COPYRIGHT) 27 | NSMainNibFile 28 | MainMenu 29 | NSPrincipalClass 30 | NSApplication 31 | 32 | 33 | -------------------------------------------------------------------------------- /example/macos/Runner/MainFlutterWindow.swift: -------------------------------------------------------------------------------- 1 | import Cocoa 2 | import FlutterMacOS 3 | 4 | class MainFlutterWindow: NSWindow { 5 | override func awakeFromNib() { 6 | let flutterViewController = FlutterViewController.init() 7 | let windowFrame = self.frame 8 | self.contentViewController = flutterViewController 9 | self.setFrame(windowFrame, display: true) 10 | 11 | RegisterGeneratedPlugins(registry: flutterViewController) 12 | 13 | super.awakeFromNib() 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /example/macos/Runner/Release.entitlements: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | com.apple.security.app-sandbox 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /example/pubspec.lock: -------------------------------------------------------------------------------- 1 | # Generated by pub 2 | # See https://dart.dev/tools/pub/glossary#lockfile 3 | packages: 4 | async: 5 | dependency: transitive 6 | description: 7 | name: async 8 | sha256: d2872f9c19731c2e5f10444b14686eb7cc85c76274bd6c16e1816bff9a3bab63 9 | url: "https://pub.dev" 10 | source: hosted 11 | version: "2.12.0" 12 | boolean_selector: 13 | dependency: transitive 14 | description: 15 | name: boolean_selector 16 | sha256: "8aab1771e1243a5063b8b0ff68042d67334e3feab9e95b9490f9a6ebf73b42ea" 17 | url: "https://pub.dev" 18 | source: hosted 19 | version: "2.1.2" 20 | characters: 21 | dependency: transitive 22 | description: 23 | name: characters 24 | sha256: f71061c654a3380576a52b451dd5532377954cf9dbd272a78fc8479606670803 25 | url: "https://pub.dev" 26 | source: hosted 27 | version: "1.4.0" 28 | clock: 29 | dependency: transitive 30 | description: 31 | name: clock 32 | sha256: fddb70d9b5277016c77a80201021d40a2247104d9f4aa7bab7157b7e3f05b84b 33 | url: "https://pub.dev" 34 | source: hosted 35 | version: "1.1.2" 36 | collection: 37 | dependency: transitive 38 | description: 39 | name: collection 40 | sha256: "2f5709ae4d3d59dd8f7cd309b4e023046b57d8a6c82130785d2b0e5868084e76" 41 | url: "https://pub.dev" 42 | source: hosted 43 | version: "1.19.1" 44 | cupertino_icons: 45 | dependency: "direct main" 46 | description: 47 | name: cupertino_icons 48 | sha256: d57953e10f9f8327ce64a508a355f0b1ec902193f66288e8cb5070e7c47eeb2d 49 | url: "https://pub.dev" 50 | source: hosted 51 | version: "1.0.6" 52 | fake_async: 53 | dependency: transitive 54 | description: 55 | name: fake_async 56 | sha256: "6a95e56b2449df2273fd8c45a662d6947ce1ebb7aafe80e550a3f68297f3cacc" 57 | url: "https://pub.dev" 58 | source: hosted 59 | version: "1.3.2" 60 | flutter: 61 | dependency: "direct main" 62 | description: flutter 63 | source: sdk 64 | version: "0.0.0" 65 | flutter_lints: 66 | dependency: "direct dev" 67 | description: 68 | name: flutter_lints 69 | sha256: b543301ad291598523947dc534aaddc5aaad597b709d2426d3a0e0d44c5cb493 70 | url: "https://pub.dev" 71 | source: hosted 72 | version: "1.0.4" 73 | flutter_nsd: 74 | dependency: "direct main" 75 | description: 76 | path: ".." 77 | relative: true 78 | source: path 79 | version: "1.5.0" 80 | flutter_test: 81 | dependency: "direct dev" 82 | description: flutter 83 | source: sdk 84 | version: "0.0.0" 85 | leak_tracker: 86 | dependency: transitive 87 | description: 88 | name: leak_tracker 89 | sha256: c35baad643ba394b40aac41080300150a4f08fd0fd6a10378f8f7c6bc161acec 90 | url: "https://pub.dev" 91 | source: hosted 92 | version: "10.0.8" 93 | leak_tracker_flutter_testing: 94 | dependency: transitive 95 | description: 96 | name: leak_tracker_flutter_testing 97 | sha256: f8b613e7e6a13ec79cfdc0e97638fddb3ab848452eff057653abd3edba760573 98 | url: "https://pub.dev" 99 | source: hosted 100 | version: "3.0.9" 101 | leak_tracker_testing: 102 | dependency: transitive 103 | description: 104 | name: leak_tracker_testing 105 | sha256: "6ba465d5d76e67ddf503e1161d1f4a6bc42306f9d66ca1e8f079a47290fb06d3" 106 | url: "https://pub.dev" 107 | source: hosted 108 | version: "3.0.1" 109 | lints: 110 | dependency: transitive 111 | description: 112 | name: lints 113 | sha256: a2c3d198cb5ea2e179926622d433331d8b58374ab8f29cdda6e863bd62fd369c 114 | url: "https://pub.dev" 115 | source: hosted 116 | version: "1.0.1" 117 | matcher: 118 | dependency: transitive 119 | description: 120 | name: matcher 121 | sha256: dc58c723c3c24bf8d3e2d3ad3f2f9d7bd9cf43ec6feaa64181775e60190153f2 122 | url: "https://pub.dev" 123 | source: hosted 124 | version: "0.12.17" 125 | material_color_utilities: 126 | dependency: transitive 127 | description: 128 | name: material_color_utilities 129 | sha256: f7142bb1154231d7ea5f96bc7bde4bda2a0945d2806bb11670e30b850d56bdec 130 | url: "https://pub.dev" 131 | source: hosted 132 | version: "0.11.1" 133 | meta: 134 | dependency: transitive 135 | description: 136 | name: meta 137 | sha256: e3641ec5d63ebf0d9b41bd43201a66e3fc79a65db5f61fc181f04cd27aab950c 138 | url: "https://pub.dev" 139 | source: hosted 140 | version: "1.16.0" 141 | path: 142 | dependency: transitive 143 | description: 144 | name: path 145 | sha256: "75cca69d1490965be98c73ceaea117e8a04dd21217b37b292c9ddbec0d955bc5" 146 | url: "https://pub.dev" 147 | source: hosted 148 | version: "1.9.1" 149 | sky_engine: 150 | dependency: transitive 151 | description: flutter 152 | source: sdk 153 | version: "0.0.0" 154 | source_span: 155 | dependency: transitive 156 | description: 157 | name: source_span 158 | sha256: "254ee5351d6cb365c859e20ee823c3bb479bf4a293c22d17a9f1bf144ce86f7c" 159 | url: "https://pub.dev" 160 | source: hosted 161 | version: "1.10.1" 162 | stack_trace: 163 | dependency: transitive 164 | description: 165 | name: stack_trace 166 | sha256: "8b27215b45d22309b5cddda1aa2b19bdfec9df0e765f2de506401c071d38d1b1" 167 | url: "https://pub.dev" 168 | source: hosted 169 | version: "1.12.1" 170 | stream_channel: 171 | dependency: transitive 172 | description: 173 | name: stream_channel 174 | sha256: "969e04c80b8bcdf826f8f16579c7b14d780458bd97f56d107d3950fdbeef059d" 175 | url: "https://pub.dev" 176 | source: hosted 177 | version: "2.1.4" 178 | string_scanner: 179 | dependency: transitive 180 | description: 181 | name: string_scanner 182 | sha256: "921cd31725b72fe181906c6a94d987c78e3b98c2e205b397ea399d4054872b43" 183 | url: "https://pub.dev" 184 | source: hosted 185 | version: "1.4.1" 186 | term_glyph: 187 | dependency: transitive 188 | description: 189 | name: term_glyph 190 | sha256: "7f554798625ea768a7518313e58f83891c7f5024f88e46e7182a4558850a4b8e" 191 | url: "https://pub.dev" 192 | source: hosted 193 | version: "1.2.2" 194 | test_api: 195 | dependency: transitive 196 | description: 197 | name: test_api 198 | sha256: fb31f383e2ee25fbbfe06b40fe21e1e458d14080e3c67e7ba0acfde4df4e0bbd 199 | url: "https://pub.dev" 200 | source: hosted 201 | version: "0.7.4" 202 | vector_math: 203 | dependency: transitive 204 | description: 205 | name: vector_math 206 | sha256: "80b3257d1492ce4d091729e3a67a60407d227c27241d6927be0130c98e741803" 207 | url: "https://pub.dev" 208 | source: hosted 209 | version: "2.1.4" 210 | vm_service: 211 | dependency: transitive 212 | description: 213 | name: vm_service 214 | sha256: "0968250880a6c5fe7edc067ed0a13d4bae1577fe2771dcf3010d52c4a9d3ca14" 215 | url: "https://pub.dev" 216 | source: hosted 217 | version: "14.3.1" 218 | sdks: 219 | dart: ">=3.7.0-0 <4.0.0" 220 | flutter: ">=3.18.0-18.0.pre.54" 221 | -------------------------------------------------------------------------------- /example/pubspec.yaml: -------------------------------------------------------------------------------- 1 | name: flutter_nsd_example 2 | description: Demonstrates how to use the flutter_nsd plugin. 3 | 4 | publish_to: 'none' 5 | 6 | environment: 7 | sdk: ">=2.12.0-0 <4.0.0" 8 | 9 | dependencies: 10 | flutter: 11 | sdk: flutter 12 | 13 | flutter_nsd: 14 | path: ../ 15 | 16 | cupertino_icons: ^1.0.6 17 | 18 | dev_dependencies: 19 | flutter_lints: ^1.0.4 20 | flutter_test: 21 | sdk: flutter 22 | 23 | flutter: 24 | uses-material-design: true 25 | -------------------------------------------------------------------------------- /example/windows/.gitignore: -------------------------------------------------------------------------------- 1 | flutter/ephemeral/ 2 | 3 | # Visual Studio user-specific files. 4 | *.suo 5 | *.user 6 | *.userosscache 7 | *.sln.docstates 8 | 9 | # Visual Studio build-related files. 10 | x64/ 11 | x86/ 12 | 13 | # Visual Studio cache files 14 | # files ending in .cache can be ignored 15 | *.[Cc]ache 16 | # but keep track of directories ending in .cache 17 | !*.[Cc]ache/ 18 | -------------------------------------------------------------------------------- /example/windows/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.15) 2 | project(flutter_nsd_example LANGUAGES CXX) 3 | 4 | set(BINARY_NAME "flutter_nsd_example") 5 | 6 | cmake_policy(SET CMP0063 NEW) 7 | 8 | set(CMAKE_INSTALL_RPATH "$ORIGIN/lib") 9 | 10 | # Configure build options. 11 | get_property(IS_MULTICONFIG GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG) 12 | if(IS_MULTICONFIG) 13 | set(CMAKE_CONFIGURATION_TYPES "Debug;Profile;Release" 14 | CACHE STRING "" FORCE) 15 | else() 16 | if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) 17 | set(CMAKE_BUILD_TYPE "Debug" CACHE 18 | STRING "Flutter build mode" FORCE) 19 | set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS 20 | "Debug" "Profile" "Release") 21 | endif() 22 | endif() 23 | 24 | set(CMAKE_EXE_LINKER_FLAGS_PROFILE "${CMAKE_EXE_LINKER_FLAGS_RELEASE}") 25 | set(CMAKE_SHARED_LINKER_FLAGS_PROFILE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE}") 26 | set(CMAKE_C_FLAGS_PROFILE "${CMAKE_C_FLAGS_RELEASE}") 27 | set(CMAKE_CXX_FLAGS_PROFILE "${CMAKE_CXX_FLAGS_RELEASE}") 28 | 29 | # Use Unicode for all projects. 30 | add_definitions(-DUNICODE -D_UNICODE) 31 | 32 | # Compilation settings that should be applied to most targets. 33 | function(APPLY_STANDARD_SETTINGS TARGET) 34 | target_compile_features(${TARGET} PUBLIC cxx_std_17) 35 | target_compile_options(${TARGET} PRIVATE /W4 /WX /wd"4100") 36 | target_compile_options(${TARGET} PRIVATE /EHsc) 37 | target_compile_definitions(${TARGET} PRIVATE "_HAS_EXCEPTIONS=0") 38 | target_compile_definitions(${TARGET} PRIVATE "$<$:_DEBUG>") 39 | endfunction() 40 | 41 | set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") 42 | 43 | # Flutter library and tool build rules. 44 | add_subdirectory(${FLUTTER_MANAGED_DIR}) 45 | 46 | # Application build 47 | add_subdirectory("runner") 48 | 49 | # Generated plugin build rules, which manage building the plugins and adding 50 | # them to the application. 51 | include(flutter/generated_plugins.cmake) 52 | 53 | 54 | # === Installation === 55 | # Support files are copied into place next to the executable, so that it can 56 | # run in place. This is done instead of making a separate bundle (as on Linux) 57 | # so that building and running from within Visual Studio will work. 58 | set(BUILD_BUNDLE_DIR "$") 59 | # Make the "install" step default, as it's required to run. 60 | set(CMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD 1) 61 | if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) 62 | set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) 63 | endif() 64 | 65 | set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") 66 | set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}") 67 | 68 | install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" 69 | COMPONENT Runtime) 70 | 71 | install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" 72 | COMPONENT Runtime) 73 | 74 | install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" 75 | COMPONENT Runtime) 76 | 77 | if(PLUGIN_BUNDLED_LIBRARIES) 78 | install(FILES "${PLUGIN_BUNDLED_LIBRARIES}" 79 | DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" 80 | COMPONENT Runtime) 81 | endif() 82 | 83 | # Fully re-copy the assets directory on each build to avoid having stale files 84 | # from a previous install. 85 | set(FLUTTER_ASSET_DIR_NAME "flutter_assets") 86 | install(CODE " 87 | file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") 88 | " COMPONENT Runtime) 89 | install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" 90 | DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) 91 | 92 | # Install the AOT library on non-Debug builds only. 93 | install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" 94 | CONFIGURATIONS Profile;Release 95 | COMPONENT Runtime) 96 | -------------------------------------------------------------------------------- /example/windows/flutter/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.15) 2 | 3 | set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") 4 | 5 | # Configuration provided via flutter tool. 6 | include(${EPHEMERAL_DIR}/generated_config.cmake) 7 | 8 | # TODO: Move the rest of this into files in ephemeral. See 9 | # https://github.com/flutter/flutter/issues/57146. 10 | set(WRAPPER_ROOT "${EPHEMERAL_DIR}/cpp_client_wrapper") 11 | 12 | # === Flutter Library === 13 | set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/flutter_windows.dll") 14 | 15 | # Published to parent scope for install step. 16 | set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) 17 | set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) 18 | set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) 19 | set(AOT_LIBRARY "${PROJECT_DIR}/build/windows/app.so" PARENT_SCOPE) 20 | 21 | list(APPEND FLUTTER_LIBRARY_HEADERS 22 | "flutter_export.h" 23 | "flutter_windows.h" 24 | "flutter_messenger.h" 25 | "flutter_plugin_registrar.h" 26 | "flutter_texture_registrar.h" 27 | ) 28 | list(TRANSFORM FLUTTER_LIBRARY_HEADERS PREPEND "${EPHEMERAL_DIR}/") 29 | add_library(flutter INTERFACE) 30 | target_include_directories(flutter INTERFACE 31 | "${EPHEMERAL_DIR}" 32 | ) 33 | target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}.lib") 34 | add_dependencies(flutter flutter_assemble) 35 | 36 | # === Wrapper === 37 | list(APPEND CPP_WRAPPER_SOURCES_CORE 38 | "core_implementations.cc" 39 | "standard_codec.cc" 40 | ) 41 | list(TRANSFORM CPP_WRAPPER_SOURCES_CORE PREPEND "${WRAPPER_ROOT}/") 42 | list(APPEND CPP_WRAPPER_SOURCES_PLUGIN 43 | "plugin_registrar.cc" 44 | ) 45 | list(TRANSFORM CPP_WRAPPER_SOURCES_PLUGIN PREPEND "${WRAPPER_ROOT}/") 46 | list(APPEND CPP_WRAPPER_SOURCES_APP 47 | "flutter_engine.cc" 48 | "flutter_view_controller.cc" 49 | ) 50 | list(TRANSFORM CPP_WRAPPER_SOURCES_APP PREPEND "${WRAPPER_ROOT}/") 51 | 52 | # Wrapper sources needed for a plugin. 53 | add_library(flutter_wrapper_plugin STATIC 54 | ${CPP_WRAPPER_SOURCES_CORE} 55 | ${CPP_WRAPPER_SOURCES_PLUGIN} 56 | ) 57 | apply_standard_settings(flutter_wrapper_plugin) 58 | set_target_properties(flutter_wrapper_plugin PROPERTIES 59 | POSITION_INDEPENDENT_CODE ON) 60 | set_target_properties(flutter_wrapper_plugin PROPERTIES 61 | CXX_VISIBILITY_PRESET hidden) 62 | target_link_libraries(flutter_wrapper_plugin PUBLIC flutter) 63 | target_include_directories(flutter_wrapper_plugin PUBLIC 64 | "${WRAPPER_ROOT}/include" 65 | ) 66 | add_dependencies(flutter_wrapper_plugin flutter_assemble) 67 | 68 | # Wrapper sources needed for the runner. 69 | add_library(flutter_wrapper_app STATIC 70 | ${CPP_WRAPPER_SOURCES_CORE} 71 | ${CPP_WRAPPER_SOURCES_APP} 72 | ) 73 | apply_standard_settings(flutter_wrapper_app) 74 | target_link_libraries(flutter_wrapper_app PUBLIC flutter) 75 | target_include_directories(flutter_wrapper_app PUBLIC 76 | "${WRAPPER_ROOT}/include" 77 | ) 78 | add_dependencies(flutter_wrapper_app flutter_assemble) 79 | 80 | # === Flutter tool backend === 81 | # _phony_ is a non-existent file to force this command to run every time, 82 | # since currently there's no way to get a full input/output list from the 83 | # flutter tool. 84 | set(PHONY_OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/_phony_") 85 | set_source_files_properties("${PHONY_OUTPUT}" PROPERTIES SYMBOLIC TRUE) 86 | add_custom_command( 87 | OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} 88 | ${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_PLUGIN} 89 | ${CPP_WRAPPER_SOURCES_APP} 90 | ${PHONY_OUTPUT} 91 | COMMAND ${CMAKE_COMMAND} -E env 92 | ${FLUTTER_TOOL_ENVIRONMENT} 93 | "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.bat" 94 | windows-x64 $ 95 | VERBATIM 96 | ) 97 | add_custom_target(flutter_assemble DEPENDS 98 | "${FLUTTER_LIBRARY}" 99 | ${FLUTTER_LIBRARY_HEADERS} 100 | ${CPP_WRAPPER_SOURCES_CORE} 101 | ${CPP_WRAPPER_SOURCES_PLUGIN} 102 | ${CPP_WRAPPER_SOURCES_APP} 103 | ) 104 | -------------------------------------------------------------------------------- /example/windows/flutter/generated_plugin_registrant.cc: -------------------------------------------------------------------------------- 1 | // 2 | // Generated file. Do not edit. 3 | // 4 | 5 | // clang-format off 6 | 7 | #include "generated_plugin_registrant.h" 8 | 9 | #include 10 | 11 | void RegisterPlugins(flutter::PluginRegistry* registry) { 12 | FlutterNsdPluginRegisterWithRegistrar( 13 | registry->GetRegistrarForPlugin("FlutterNsdPlugin")); 14 | } 15 | -------------------------------------------------------------------------------- /example/windows/flutter/generated_plugin_registrant.h: -------------------------------------------------------------------------------- 1 | // 2 | // Generated file. Do not edit. 3 | // 4 | 5 | // clang-format off 6 | 7 | #ifndef GENERATED_PLUGIN_REGISTRANT_ 8 | #define GENERATED_PLUGIN_REGISTRANT_ 9 | 10 | #include 11 | 12 | // Registers Flutter plugins. 13 | void RegisterPlugins(flutter::PluginRegistry* registry); 14 | 15 | #endif // GENERATED_PLUGIN_REGISTRANT_ 16 | -------------------------------------------------------------------------------- /example/windows/flutter/generated_plugins.cmake: -------------------------------------------------------------------------------- 1 | # 2 | # Generated file, do not edit. 3 | # 4 | 5 | list(APPEND FLUTTER_PLUGIN_LIST 6 | flutter_nsd 7 | ) 8 | 9 | list(APPEND FLUTTER_FFI_PLUGIN_LIST 10 | ) 11 | 12 | set(PLUGIN_BUNDLED_LIBRARIES) 13 | 14 | foreach(plugin ${FLUTTER_PLUGIN_LIST}) 15 | add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/windows plugins/${plugin}) 16 | target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) 17 | list(APPEND PLUGIN_BUNDLED_LIBRARIES $) 18 | list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) 19 | endforeach(plugin) 20 | 21 | foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) 22 | add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/windows plugins/${ffi_plugin}) 23 | list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) 24 | endforeach(ffi_plugin) 25 | -------------------------------------------------------------------------------- /example/windows/runner/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.15) 2 | project(runner LANGUAGES CXX) 3 | 4 | add_executable(${BINARY_NAME} WIN32 5 | "flutter_window.cpp" 6 | "main.cpp" 7 | "run_loop.cpp" 8 | "utils.cpp" 9 | "win32_window.cpp" 10 | "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" 11 | "Runner.rc" 12 | "runner.exe.manifest" 13 | ) 14 | apply_standard_settings(${BINARY_NAME}) 15 | target_compile_definitions(${BINARY_NAME} PRIVATE "NOMINMAX") 16 | target_link_libraries(${BINARY_NAME} PRIVATE flutter flutter_wrapper_app) 17 | target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") 18 | add_dependencies(${BINARY_NAME} flutter_assemble) 19 | -------------------------------------------------------------------------------- /example/windows/runner/Runner.rc: -------------------------------------------------------------------------------- 1 | // Microsoft Visual C++ generated resource script. 2 | // 3 | #pragma code_page(65001) 4 | #include "resource.h" 5 | 6 | #define APSTUDIO_READONLY_SYMBOLS 7 | ///////////////////////////////////////////////////////////////////////////// 8 | // 9 | // Generated from the TEXTINCLUDE 2 resource. 10 | // 11 | #include "winres.h" 12 | 13 | ///////////////////////////////////////////////////////////////////////////// 14 | #undef APSTUDIO_READONLY_SYMBOLS 15 | 16 | ///////////////////////////////////////////////////////////////////////////// 17 | // English (United States) resources 18 | 19 | #if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) 20 | LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US 21 | 22 | #ifdef APSTUDIO_INVOKED 23 | ///////////////////////////////////////////////////////////////////////////// 24 | // 25 | // TEXTINCLUDE 26 | // 27 | 28 | 1 TEXTINCLUDE 29 | BEGIN 30 | "resource.h\0" 31 | END 32 | 33 | 2 TEXTINCLUDE 34 | BEGIN 35 | "#include ""winres.h""\r\n" 36 | "\0" 37 | END 38 | 39 | 3 TEXTINCLUDE 40 | BEGIN 41 | "\r\n" 42 | "\0" 43 | END 44 | 45 | #endif // APSTUDIO_INVOKED 46 | 47 | 48 | ///////////////////////////////////////////////////////////////////////////// 49 | // 50 | // Icon 51 | // 52 | 53 | // Icon with lowest ID value placed first to ensure application icon 54 | // remains consistent on all systems. 55 | IDI_APP_ICON ICON "resources\\app_icon.ico" 56 | 57 | 58 | ///////////////////////////////////////////////////////////////////////////// 59 | // 60 | // Version 61 | // 62 | 63 | #ifdef FLUTTER_BUILD_NUMBER 64 | #define VERSION_AS_NUMBER FLUTTER_BUILD_NUMBER 65 | #else 66 | #define VERSION_AS_NUMBER 1,0,0 67 | #endif 68 | 69 | #ifdef FLUTTER_BUILD_NAME 70 | #define VERSION_AS_STRING #FLUTTER_BUILD_NAME 71 | #else 72 | #define VERSION_AS_STRING "1.0.0" 73 | #endif 74 | 75 | VS_VERSION_INFO VERSIONINFO 76 | FILEVERSION VERSION_AS_NUMBER 77 | PRODUCTVERSION VERSION_AS_NUMBER 78 | FILEFLAGSMASK VS_FFI_FILEFLAGSMASK 79 | #ifdef _DEBUG 80 | FILEFLAGS VS_FF_DEBUG 81 | #else 82 | FILEFLAGS 0x0L 83 | #endif 84 | FILEOS VOS__WINDOWS32 85 | FILETYPE VFT_APP 86 | FILESUBTYPE 0x0L 87 | BEGIN 88 | BLOCK "StringFileInfo" 89 | BEGIN 90 | BLOCK "040904e4" 91 | BEGIN 92 | VALUE "CompanyName", "com.nimroddayan.flutternsd" "\0" 93 | VALUE "FileDescription", "A new Flutter project." "\0" 94 | VALUE "FileVersion", VERSION_AS_STRING "\0" 95 | VALUE "InternalName", "example" "\0" 96 | VALUE "LegalCopyright", "Copyright (C) 2022 com.nimroddayan.flutternsd. All rights reserved." "\0" 97 | VALUE "OriginalFilename", "example.exe" "\0" 98 | VALUE "ProductName", "example" "\0" 99 | VALUE "ProductVersion", VERSION_AS_STRING "\0" 100 | END 101 | END 102 | BLOCK "VarFileInfo" 103 | BEGIN 104 | VALUE "Translation", 0x409, 1252 105 | END 106 | END 107 | 108 | #endif // English (United States) resources 109 | ///////////////////////////////////////////////////////////////////////////// 110 | 111 | 112 | 113 | #ifndef APSTUDIO_INVOKED 114 | ///////////////////////////////////////////////////////////////////////////// 115 | // 116 | // Generated from the TEXTINCLUDE 3 resource. 117 | // 118 | 119 | 120 | ///////////////////////////////////////////////////////////////////////////// 121 | #endif // not APSTUDIO_INVOKED 122 | -------------------------------------------------------------------------------- /example/windows/runner/flutter_window.cpp: -------------------------------------------------------------------------------- 1 | #include "flutter_window.h" 2 | 3 | #include 4 | 5 | #include "flutter/generated_plugin_registrant.h" 6 | 7 | FlutterWindow::FlutterWindow(RunLoop* run_loop, 8 | const flutter::DartProject& project) 9 | : run_loop_(run_loop), project_(project) {} 10 | 11 | FlutterWindow::~FlutterWindow() {} 12 | 13 | bool FlutterWindow::OnCreate() { 14 | if (!Win32Window::OnCreate()) { 15 | return false; 16 | } 17 | 18 | RECT frame = GetClientArea(); 19 | 20 | // The size here must match the window dimensions to avoid unnecessary surface 21 | // creation / destruction in the startup path. 22 | flutter_controller_ = std::make_unique( 23 | frame.right - frame.left, frame.bottom - frame.top, project_); 24 | // Ensure that basic setup of the controller was successful. 25 | if (!flutter_controller_->engine() || !flutter_controller_->view()) { 26 | return false; 27 | } 28 | RegisterPlugins(flutter_controller_->engine()); 29 | run_loop_->RegisterFlutterInstance(flutter_controller_->engine()); 30 | SetChildContent(flutter_controller_->view()->GetNativeWindow()); 31 | return true; 32 | } 33 | 34 | void FlutterWindow::OnDestroy() { 35 | if (flutter_controller_) { 36 | run_loop_->UnregisterFlutterInstance(flutter_controller_->engine()); 37 | flutter_controller_ = nullptr; 38 | } 39 | 40 | Win32Window::OnDestroy(); 41 | } 42 | 43 | LRESULT 44 | FlutterWindow::MessageHandler(HWND hwnd, UINT const message, 45 | WPARAM const wparam, 46 | LPARAM const lparam) noexcept { 47 | // Give Flutter, including plugins, an opportunity to handle window messages. 48 | if (flutter_controller_) { 49 | std::optional result = 50 | flutter_controller_->HandleTopLevelWindowProc(hwnd, message, wparam, 51 | lparam); 52 | if (result) { 53 | return *result; 54 | } 55 | } 56 | 57 | switch (message) { 58 | case WM_FONTCHANGE: 59 | flutter_controller_->engine()->ReloadSystemFonts(); 60 | break; 61 | } 62 | 63 | return Win32Window::MessageHandler(hwnd, message, wparam, lparam); 64 | } 65 | -------------------------------------------------------------------------------- /example/windows/runner/flutter_window.h: -------------------------------------------------------------------------------- 1 | #ifndef RUNNER_FLUTTER_WINDOW_H_ 2 | #define RUNNER_FLUTTER_WINDOW_H_ 3 | 4 | #include 5 | #include 6 | 7 | #include 8 | 9 | #include "run_loop.h" 10 | #include "win32_window.h" 11 | 12 | // A window that does nothing but host a Flutter view. 13 | class FlutterWindow : public Win32Window { 14 | public: 15 | // Creates a new FlutterWindow driven by the |run_loop|, hosting a 16 | // Flutter view running |project|. 17 | explicit FlutterWindow(RunLoop* run_loop, 18 | const flutter::DartProject& project); 19 | virtual ~FlutterWindow(); 20 | 21 | protected: 22 | // Win32Window: 23 | bool OnCreate() override; 24 | void OnDestroy() override; 25 | LRESULT MessageHandler(HWND window, UINT const message, WPARAM const wparam, 26 | LPARAM const lparam) noexcept override; 27 | 28 | private: 29 | // The run loop driving events for this window. 30 | RunLoop* run_loop_; 31 | 32 | // The project to run. 33 | flutter::DartProject project_; 34 | 35 | // The Flutter instance hosted by this window. 36 | std::unique_ptr flutter_controller_; 37 | }; 38 | 39 | #endif // RUNNER_FLUTTER_WINDOW_H_ 40 | -------------------------------------------------------------------------------- /example/windows/runner/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #include "flutter_window.h" 6 | #include "run_loop.h" 7 | #include "utils.h" 8 | 9 | int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev, 10 | _In_ wchar_t *command_line, _In_ int show_command) { 11 | // Attach to console when present (e.g., 'flutter run') or create a 12 | // new console when running with a debugger. 13 | if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) { 14 | CreateAndAttachConsole(); 15 | } 16 | 17 | // Initialize COM, so that it is available for use in the library and/or 18 | // plugins. 19 | ::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED); 20 | 21 | RunLoop run_loop; 22 | 23 | flutter::DartProject project(L"data"); 24 | 25 | std::vector command_line_arguments = 26 | GetCommandLineArguments(); 27 | 28 | project.set_dart_entrypoint_arguments(std::move(command_line_arguments)); 29 | 30 | FlutterWindow window(&run_loop, project); 31 | Win32Window::Point origin(10, 10); 32 | Win32Window::Size size(1280, 720); 33 | if (!window.CreateAndShow(L"example", origin, size)) { 34 | return EXIT_FAILURE; 35 | } 36 | window.SetQuitOnClose(true); 37 | 38 | run_loop.Run(); 39 | 40 | ::CoUninitialize(); 41 | return EXIT_SUCCESS; 42 | } 43 | -------------------------------------------------------------------------------- /example/windows/runner/resource.h: -------------------------------------------------------------------------------- 1 | //{{NO_DEPENDENCIES}} 2 | // Microsoft Visual C++ generated include file. 3 | // Used by Runner.rc 4 | // 5 | #define IDI_APP_ICON 101 6 | 7 | // Next default values for new objects 8 | // 9 | #ifdef APSTUDIO_INVOKED 10 | #ifndef APSTUDIO_READONLY_SYMBOLS 11 | #define _APS_NEXT_RESOURCE_VALUE 102 12 | #define _APS_NEXT_COMMAND_VALUE 40001 13 | #define _APS_NEXT_CONTROL_VALUE 1001 14 | #define _APS_NEXT_SYMED_VALUE 101 15 | #endif 16 | #endif 17 | -------------------------------------------------------------------------------- /example/windows/runner/resources/app_icon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Nimrodda/flutter_nsd/5565033b1d76405ca9aaaf79c676a654ddfb6348/example/windows/runner/resources/app_icon.ico -------------------------------------------------------------------------------- /example/windows/runner/run_loop.cpp: -------------------------------------------------------------------------------- 1 | #include "run_loop.h" 2 | 3 | #include 4 | 5 | #include 6 | 7 | RunLoop::RunLoop() {} 8 | 9 | RunLoop::~RunLoop() {} 10 | 11 | void RunLoop::Run() { 12 | bool keep_running = true; 13 | TimePoint next_flutter_event_time = TimePoint::clock::now(); 14 | while (keep_running) { 15 | std::chrono::nanoseconds wait_duration = 16 | std::max(std::chrono::nanoseconds(0), 17 | next_flutter_event_time - TimePoint::clock::now()); 18 | ::MsgWaitForMultipleObjects( 19 | 0, nullptr, FALSE, static_cast(wait_duration.count() / 1000), 20 | QS_ALLINPUT); 21 | bool processed_events = false; 22 | MSG message; 23 | // All pending Windows messages must be processed; MsgWaitForMultipleObjects 24 | // won't return again for items left in the queue after PeekMessage. 25 | while (::PeekMessage(&message, nullptr, 0, 0, PM_REMOVE)) { 26 | processed_events = true; 27 | if (message.message == WM_QUIT) { 28 | keep_running = false; 29 | break; 30 | } 31 | ::TranslateMessage(&message); 32 | ::DispatchMessage(&message); 33 | // Allow Flutter to process messages each time a Windows message is 34 | // processed, to prevent starvation. 35 | next_flutter_event_time = 36 | std::min(next_flutter_event_time, ProcessFlutterMessages()); 37 | } 38 | // If the PeekMessage loop didn't run, process Flutter messages. 39 | if (!processed_events) { 40 | next_flutter_event_time = 41 | std::min(next_flutter_event_time, ProcessFlutterMessages()); 42 | } 43 | } 44 | } 45 | 46 | void RunLoop::RegisterFlutterInstance( 47 | flutter::FlutterEngine* flutter_instance) { 48 | flutter_instances_.insert(flutter_instance); 49 | } 50 | 51 | void RunLoop::UnregisterFlutterInstance( 52 | flutter::FlutterEngine* flutter_instance) { 53 | flutter_instances_.erase(flutter_instance); 54 | } 55 | 56 | RunLoop::TimePoint RunLoop::ProcessFlutterMessages() { 57 | TimePoint next_event_time = TimePoint::max(); 58 | for (auto instance : flutter_instances_) { 59 | std::chrono::nanoseconds wait_duration = instance->ProcessMessages(); 60 | if (wait_duration != std::chrono::nanoseconds::max()) { 61 | next_event_time = 62 | std::min(next_event_time, TimePoint::clock::now() + wait_duration); 63 | } 64 | } 65 | return next_event_time; 66 | } 67 | -------------------------------------------------------------------------------- /example/windows/runner/run_loop.h: -------------------------------------------------------------------------------- 1 | #ifndef RUNNER_RUN_LOOP_H_ 2 | #define RUNNER_RUN_LOOP_H_ 3 | 4 | #include 5 | 6 | #include 7 | #include 8 | 9 | // A runloop that will service events for Flutter instances as well 10 | // as native messages. 11 | class RunLoop { 12 | public: 13 | RunLoop(); 14 | ~RunLoop(); 15 | 16 | // Prevent copying 17 | RunLoop(RunLoop const&) = delete; 18 | RunLoop& operator=(RunLoop const&) = delete; 19 | 20 | // Runs the run loop until the application quits. 21 | void Run(); 22 | 23 | // Registers the given Flutter instance for event servicing. 24 | void RegisterFlutterInstance( 25 | flutter::FlutterEngine* flutter_instance); 26 | 27 | // Unregisters the given Flutter instance from event servicing. 28 | void UnregisterFlutterInstance( 29 | flutter::FlutterEngine* flutter_instance); 30 | 31 | private: 32 | using TimePoint = std::chrono::steady_clock::time_point; 33 | 34 | // Processes all currently pending messages for registered Flutter instances. 35 | TimePoint ProcessFlutterMessages(); 36 | 37 | std::set flutter_instances_; 38 | }; 39 | 40 | #endif // RUNNER_RUN_LOOP_H_ 41 | -------------------------------------------------------------------------------- /example/windows/runner/runner.exe.manifest: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | PerMonitorV2 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /example/windows/runner/utils.cpp: -------------------------------------------------------------------------------- 1 | #include "utils.h" 2 | 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | #include 9 | 10 | void CreateAndAttachConsole() { 11 | if (::AllocConsole()) { 12 | FILE *unused; 13 | if (freopen_s(&unused, "CONOUT$", "w", stdout)) { 14 | _dup2(_fileno(stdout), 1); 15 | } 16 | if (freopen_s(&unused, "CONOUT$", "w", stderr)) { 17 | _dup2(_fileno(stdout), 2); 18 | } 19 | std::ios::sync_with_stdio(); 20 | FlutterDesktopResyncOutputStreams(); 21 | } 22 | } 23 | 24 | std::vector GetCommandLineArguments() { 25 | // Convert the UTF-16 command line arguments to UTF-8 for the Engine to use. 26 | int argc; 27 | wchar_t** argv = ::CommandLineToArgvW(::GetCommandLineW(), &argc); 28 | if (argv == nullptr) { 29 | return std::vector(); 30 | } 31 | 32 | std::vector command_line_arguments; 33 | 34 | // Skip the first argument as it's the binary name. 35 | for (int i = 1; i < argc; i++) { 36 | command_line_arguments.push_back(Utf8FromUtf16(argv[i])); 37 | } 38 | 39 | ::LocalFree(argv); 40 | 41 | return command_line_arguments; 42 | } 43 | 44 | std::string Utf8FromUtf16(const wchar_t* utf16_string) { 45 | if (utf16_string == nullptr) { 46 | return std::string(); 47 | } 48 | int target_length = ::WideCharToMultiByte( 49 | CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, 50 | -1, nullptr, 0, nullptr, nullptr); 51 | if (target_length == 0) { 52 | return std::string(); 53 | } 54 | std::string utf8_string; 55 | utf8_string.resize(target_length); 56 | int converted_length = ::WideCharToMultiByte( 57 | CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, 58 | -1, utf8_string.data(), 59 | target_length, nullptr, nullptr); 60 | if (converted_length == 0) { 61 | return std::string(); 62 | } 63 | return utf8_string; 64 | } 65 | -------------------------------------------------------------------------------- /example/windows/runner/utils.h: -------------------------------------------------------------------------------- 1 | #ifndef RUNNER_UTILS_H_ 2 | #define RUNNER_UTILS_H_ 3 | 4 | #include 5 | #include 6 | 7 | // Creates a console for the process, and redirects stdout and stderr to 8 | // it for both the runner and the Flutter library. 9 | void CreateAndAttachConsole(); 10 | 11 | // Takes a null-terminated wchar_t* encoded in UTF-16 and returns a std::string 12 | // encoded in UTF-8. Returns an empty std::string on failure. 13 | std::string Utf8FromUtf16(const wchar_t* utf16_string); 14 | 15 | // Gets the command line arguments passed in as a std::vector, 16 | // encoded in UTF-8. Returns an empty std::vector on failure. 17 | std::vector GetCommandLineArguments(); 18 | 19 | #endif // RUNNER_UTILS_H_ 20 | -------------------------------------------------------------------------------- /example/windows/runner/win32_window.cpp: -------------------------------------------------------------------------------- 1 | #include "win32_window.h" 2 | 3 | #include 4 | 5 | #include "resource.h" 6 | 7 | namespace { 8 | 9 | constexpr const wchar_t kWindowClassName[] = L"FLUTTER_RUNNER_WIN32_WINDOW"; 10 | 11 | // The number of Win32Window objects that currently exist. 12 | static int g_active_window_count = 0; 13 | 14 | using EnableNonClientDpiScaling = BOOL __stdcall(HWND hwnd); 15 | 16 | // Scale helper to convert logical scaler values to physical using passed in 17 | // scale factor 18 | int Scale(int source, double scale_factor) { 19 | return static_cast(source * scale_factor); 20 | } 21 | 22 | // Dynamically loads the |EnableNonClientDpiScaling| from the User32 module. 23 | // This API is only needed for PerMonitor V1 awareness mode. 24 | void EnableFullDpiSupportIfAvailable(HWND hwnd) { 25 | HMODULE user32_module = LoadLibraryA("User32.dll"); 26 | if (!user32_module) { 27 | return; 28 | } 29 | auto enable_non_client_dpi_scaling = 30 | reinterpret_cast( 31 | GetProcAddress(user32_module, "EnableNonClientDpiScaling")); 32 | if (enable_non_client_dpi_scaling != nullptr) { 33 | enable_non_client_dpi_scaling(hwnd); 34 | FreeLibrary(user32_module); 35 | } 36 | } 37 | 38 | } // namespace 39 | 40 | // Manages the Win32Window's window class registration. 41 | class WindowClassRegistrar { 42 | public: 43 | ~WindowClassRegistrar() = default; 44 | 45 | // Returns the singleton registar instance. 46 | static WindowClassRegistrar* GetInstance() { 47 | if (!instance_) { 48 | instance_ = new WindowClassRegistrar(); 49 | } 50 | return instance_; 51 | } 52 | 53 | // Returns the name of the window class, registering the class if it hasn't 54 | // previously been registered. 55 | const wchar_t* GetWindowClass(); 56 | 57 | // Unregisters the window class. Should only be called if there are no 58 | // instances of the window. 59 | void UnregisterWindowClass(); 60 | 61 | private: 62 | WindowClassRegistrar() = default; 63 | 64 | static WindowClassRegistrar* instance_; 65 | 66 | bool class_registered_ = false; 67 | }; 68 | 69 | WindowClassRegistrar* WindowClassRegistrar::instance_ = nullptr; 70 | 71 | const wchar_t* WindowClassRegistrar::GetWindowClass() { 72 | if (!class_registered_) { 73 | WNDCLASS window_class{}; 74 | window_class.hCursor = LoadCursor(nullptr, IDC_ARROW); 75 | window_class.lpszClassName = kWindowClassName; 76 | window_class.style = CS_HREDRAW | CS_VREDRAW; 77 | window_class.cbClsExtra = 0; 78 | window_class.cbWndExtra = 0; 79 | window_class.hInstance = GetModuleHandle(nullptr); 80 | window_class.hIcon = 81 | LoadIcon(window_class.hInstance, MAKEINTRESOURCE(IDI_APP_ICON)); 82 | window_class.hbrBackground = 0; 83 | window_class.lpszMenuName = nullptr; 84 | window_class.lpfnWndProc = Win32Window::WndProc; 85 | RegisterClass(&window_class); 86 | class_registered_ = true; 87 | } 88 | return kWindowClassName; 89 | } 90 | 91 | void WindowClassRegistrar::UnregisterWindowClass() { 92 | UnregisterClass(kWindowClassName, nullptr); 93 | class_registered_ = false; 94 | } 95 | 96 | Win32Window::Win32Window() { 97 | ++g_active_window_count; 98 | } 99 | 100 | Win32Window::~Win32Window() { 101 | --g_active_window_count; 102 | Destroy(); 103 | } 104 | 105 | bool Win32Window::CreateAndShow(const std::wstring& title, 106 | const Point& origin, 107 | const Size& size) { 108 | Destroy(); 109 | 110 | const wchar_t* window_class = 111 | WindowClassRegistrar::GetInstance()->GetWindowClass(); 112 | 113 | const POINT target_point = {static_cast(origin.x), 114 | static_cast(origin.y)}; 115 | HMONITOR monitor = MonitorFromPoint(target_point, MONITOR_DEFAULTTONEAREST); 116 | UINT dpi = FlutterDesktopGetDpiForMonitor(monitor); 117 | double scale_factor = dpi / 96.0; 118 | 119 | HWND window = CreateWindow( 120 | window_class, title.c_str(), WS_OVERLAPPEDWINDOW | WS_VISIBLE, 121 | Scale(origin.x, scale_factor), Scale(origin.y, scale_factor), 122 | Scale(size.width, scale_factor), Scale(size.height, scale_factor), 123 | nullptr, nullptr, GetModuleHandle(nullptr), this); 124 | 125 | if (!window) { 126 | return false; 127 | } 128 | 129 | return OnCreate(); 130 | } 131 | 132 | // static 133 | LRESULT CALLBACK Win32Window::WndProc(HWND const window, 134 | UINT const message, 135 | WPARAM const wparam, 136 | LPARAM const lparam) noexcept { 137 | if (message == WM_NCCREATE) { 138 | auto window_struct = reinterpret_cast(lparam); 139 | SetWindowLongPtr(window, GWLP_USERDATA, 140 | reinterpret_cast(window_struct->lpCreateParams)); 141 | 142 | auto that = static_cast(window_struct->lpCreateParams); 143 | EnableFullDpiSupportIfAvailable(window); 144 | that->window_handle_ = window; 145 | } else if (Win32Window* that = GetThisFromHandle(window)) { 146 | return that->MessageHandler(window, message, wparam, lparam); 147 | } 148 | 149 | return DefWindowProc(window, message, wparam, lparam); 150 | } 151 | 152 | LRESULT 153 | Win32Window::MessageHandler(HWND hwnd, 154 | UINT const message, 155 | WPARAM const wparam, 156 | LPARAM const lparam) noexcept { 157 | switch (message) { 158 | case WM_DESTROY: 159 | window_handle_ = nullptr; 160 | Destroy(); 161 | if (quit_on_close_) { 162 | PostQuitMessage(0); 163 | } 164 | return 0; 165 | 166 | case WM_DPICHANGED: { 167 | auto newRectSize = reinterpret_cast(lparam); 168 | LONG newWidth = newRectSize->right - newRectSize->left; 169 | LONG newHeight = newRectSize->bottom - newRectSize->top; 170 | 171 | SetWindowPos(hwnd, nullptr, newRectSize->left, newRectSize->top, newWidth, 172 | newHeight, SWP_NOZORDER | SWP_NOACTIVATE); 173 | 174 | return 0; 175 | } 176 | case WM_SIZE: { 177 | RECT rect = GetClientArea(); 178 | if (child_content_ != nullptr) { 179 | // Size and position the child window. 180 | MoveWindow(child_content_, rect.left, rect.top, rect.right - rect.left, 181 | rect.bottom - rect.top, TRUE); 182 | } 183 | return 0; 184 | } 185 | 186 | case WM_ACTIVATE: 187 | if (child_content_ != nullptr) { 188 | SetFocus(child_content_); 189 | } 190 | return 0; 191 | } 192 | 193 | return DefWindowProc(window_handle_, message, wparam, lparam); 194 | } 195 | 196 | void Win32Window::Destroy() { 197 | OnDestroy(); 198 | 199 | if (window_handle_) { 200 | DestroyWindow(window_handle_); 201 | window_handle_ = nullptr; 202 | } 203 | if (g_active_window_count == 0) { 204 | WindowClassRegistrar::GetInstance()->UnregisterWindowClass(); 205 | } 206 | } 207 | 208 | Win32Window* Win32Window::GetThisFromHandle(HWND const window) noexcept { 209 | return reinterpret_cast( 210 | GetWindowLongPtr(window, GWLP_USERDATA)); 211 | } 212 | 213 | void Win32Window::SetChildContent(HWND content) { 214 | child_content_ = content; 215 | SetParent(content, window_handle_); 216 | RECT frame = GetClientArea(); 217 | 218 | MoveWindow(content, frame.left, frame.top, frame.right - frame.left, 219 | frame.bottom - frame.top, true); 220 | 221 | SetFocus(child_content_); 222 | } 223 | 224 | RECT Win32Window::GetClientArea() { 225 | RECT frame; 226 | GetClientRect(window_handle_, &frame); 227 | return frame; 228 | } 229 | 230 | HWND Win32Window::GetHandle() { 231 | return window_handle_; 232 | } 233 | 234 | void Win32Window::SetQuitOnClose(bool quit_on_close) { 235 | quit_on_close_ = quit_on_close; 236 | } 237 | 238 | bool Win32Window::OnCreate() { 239 | // No-op; provided for subclasses. 240 | return true; 241 | } 242 | 243 | void Win32Window::OnDestroy() { 244 | // No-op; provided for subclasses. 245 | } 246 | -------------------------------------------------------------------------------- /example/windows/runner/win32_window.h: -------------------------------------------------------------------------------- 1 | #ifndef RUNNER_WIN32_WINDOW_H_ 2 | #define RUNNER_WIN32_WINDOW_H_ 3 | 4 | #include 5 | 6 | #include 7 | #include 8 | #include 9 | 10 | // A class abstraction for a high DPI-aware Win32 Window. Intended to be 11 | // inherited from by classes that wish to specialize with custom 12 | // rendering and input handling 13 | class Win32Window { 14 | public: 15 | struct Point { 16 | unsigned int x; 17 | unsigned int y; 18 | Point(unsigned int x, unsigned int y) : x(x), y(y) {} 19 | }; 20 | 21 | struct Size { 22 | unsigned int width; 23 | unsigned int height; 24 | Size(unsigned int width, unsigned int height) 25 | : width(width), height(height) {} 26 | }; 27 | 28 | Win32Window(); 29 | virtual ~Win32Window(); 30 | 31 | // Creates and shows a win32 window with |title| and position and size using 32 | // |origin| and |size|. New windows are created on the default monitor. Window 33 | // sizes are specified to the OS in physical pixels, hence to ensure a 34 | // consistent size to will treat the width height passed in to this function 35 | // as logical pixels and scale to appropriate for the default monitor. Returns 36 | // true if the window was created successfully. 37 | bool CreateAndShow(const std::wstring& title, 38 | const Point& origin, 39 | const Size& size); 40 | 41 | // Release OS resources associated with window. 42 | void Destroy(); 43 | 44 | // Inserts |content| into the window tree. 45 | void SetChildContent(HWND content); 46 | 47 | // Returns the backing Window handle to enable clients to set icon and other 48 | // window properties. Returns nullptr if the window has been destroyed. 49 | HWND GetHandle(); 50 | 51 | // If true, closing this window will quit the application. 52 | void SetQuitOnClose(bool quit_on_close); 53 | 54 | // Return a RECT representing the bounds of the current client area. 55 | RECT GetClientArea(); 56 | 57 | protected: 58 | // Processes and route salient window messages for mouse handling, 59 | // size change and DPI. Delegates handling of these to member overloads that 60 | // inheriting classes can handle. 61 | virtual LRESULT MessageHandler(HWND window, 62 | UINT const message, 63 | WPARAM const wparam, 64 | LPARAM const lparam) noexcept; 65 | 66 | // Called when CreateAndShow is called, allowing subclass window-related 67 | // setup. Subclasses should return false if setup fails. 68 | virtual bool OnCreate(); 69 | 70 | // Called when Destroy is called. 71 | virtual void OnDestroy(); 72 | 73 | private: 74 | friend class WindowClassRegistrar; 75 | 76 | // OS callback called by message pump. Handles the WM_NCCREATE message which 77 | // is passed when the non-client area is being created and enables automatic 78 | // non-client DPI scaling so that the non-client area automatically 79 | // responsponds to changes in DPI. All other messages are handled by 80 | // MessageHandler. 81 | static LRESULT CALLBACK WndProc(HWND const window, 82 | UINT const message, 83 | WPARAM const wparam, 84 | LPARAM const lparam) noexcept; 85 | 86 | // Retrieves a class instance pointer for |window| 87 | static Win32Window* GetThisFromHandle(HWND const window) noexcept; 88 | 89 | bool quit_on_close_ = false; 90 | 91 | // window handle for top level window. 92 | HWND window_handle_ = nullptr; 93 | 94 | // window handle for hosted content. 95 | HWND child_content_ = nullptr; 96 | }; 97 | 98 | #endif // RUNNER_WIN32_WINDOW_H_ 99 | -------------------------------------------------------------------------------- /ios/.gitignore: -------------------------------------------------------------------------------- 1 | .idea/ 2 | .vagrant/ 3 | .sconsign.dblite 4 | .svn/ 5 | 6 | .DS_Store 7 | *.swp 8 | profile 9 | 10 | DerivedData/ 11 | build/ 12 | GeneratedPluginRegistrant.h 13 | GeneratedPluginRegistrant.m 14 | 15 | .generated/ 16 | 17 | *.pbxuser 18 | *.mode1v3 19 | *.mode2v3 20 | *.perspectivev3 21 | 22 | !default.pbxuser 23 | !default.mode1v3 24 | !default.mode2v3 25 | !default.perspectivev3 26 | 27 | xcuserdata 28 | 29 | *.moved-aside 30 | 31 | *.pyc 32 | *sync/ 33 | Icon? 34 | .tags* 35 | 36 | /Flutter/Generated.xcconfig 37 | /Flutter/flutter_export_environment.sh -------------------------------------------------------------------------------- /ios/Assets/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Nimrodda/flutter_nsd/5565033b1d76405ca9aaaf79c676a654ddfb6348/ios/Assets/.gitkeep -------------------------------------------------------------------------------- /ios/Classes/FlutterNsdPlugin.h: -------------------------------------------------------------------------------- 1 | #import 2 | 3 | @interface FlutterNsdPlugin : NSObject 4 | @end 5 | -------------------------------------------------------------------------------- /ios/Classes/FlutterNsdPlugin.m: -------------------------------------------------------------------------------- 1 | #import "FlutterNsdPlugin.h" 2 | #if __has_include() 3 | #import 4 | #else 5 | // Support project import fallback if the generated compatibility header 6 | // is not copied when this plugin is created as a library. 7 | // https://forums.swift.org/t/swift-static-libraries-dont-copy-generated-objective-c-header/19816 8 | #import "flutter_nsd-Swift.h" 9 | #endif 10 | 11 | @implementation FlutterNsdPlugin 12 | + (void)registerWithRegistrar:(NSObject*)registrar { 13 | [SwiftFlutterNsdPlugin registerWithRegistrar:registrar]; 14 | } 15 | @end 16 | -------------------------------------------------------------------------------- /ios/Classes/SwiftFlutterNsdPlugin.swift: -------------------------------------------------------------------------------- 1 | #if canImport(FlutterMacOS) 2 | import FlutterMacOS 3 | import Cocoa 4 | #else 5 | import Flutter 6 | import UIKit 7 | #endif 8 | 9 | public class SwiftFlutterNsdPlugin: NSObject, FlutterPlugin, NetServiceBrowserDelegate, NetServiceDelegate { 10 | private var netServiceBrowser: NetServiceBrowser! 11 | private var services = [NetService]() 12 | private var channel: FlutterMethodChannel 13 | 14 | init(channel: FlutterMethodChannel) { 15 | self.channel = channel 16 | self.services.removeAll() 17 | netServiceBrowser = NetServiceBrowser() 18 | super.init() 19 | } 20 | 21 | public static func register(with registrar: FlutterPluginRegistrar) { 22 | #if canImport(FlutterMacOS) 23 | let flutterNsdChannel = FlutterMethodChannel(name: "com.nimroddayan/flutter_nsd", binaryMessenger: registrar.messenger) 24 | #else 25 | let flutterNsdChannel = FlutterMethodChannel(name: "com.nimroddayan/flutter_nsd", binaryMessenger: registrar.messenger()) 26 | #endif 27 | let instance = SwiftFlutterNsdPlugin(channel: flutterNsdChannel) 28 | registrar.addMethodCallDelegate(instance, channel: flutterNsdChannel) 29 | } 30 | 31 | public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) { 32 | switch call.method { 33 | case "startDiscovery": 34 | let args = call.arguments as? [String: Any] 35 | guard let serviceType = args?["serviceType"] as? String else { 36 | result(FlutterError(code: "1001", message: "Service type cannot be null", details: nil)) 37 | return 38 | } 39 | 40 | self.startDiscovery(serviceType) 41 | result(nil) 42 | case "stopDiscovery": 43 | self.stopDiscovery() 44 | result(nil) 45 | default: 46 | result(FlutterMethodNotImplemented) 47 | } 48 | } 49 | 50 | private func startDiscovery(_ serviceType: String) { 51 | netServiceBrowser.delegate = self 52 | netServiceBrowser.searchForServices(ofType: serviceType, inDomain: "") 53 | } 54 | 55 | private func stopDiscovery() { 56 | netServiceBrowser.stop() 57 | } 58 | 59 | private func updateInterface() { 60 | for service in services { 61 | if service.port == -1 { 62 | service.delegate = self 63 | service.resolve(withTimeout: 10) 64 | } 65 | } 66 | } 67 | 68 | public func netServiceBrowser(_ browser: NetServiceBrowser, didNotSearch errorDict: [String : NSNumber]) { 69 | channel.invokeMethod("onStartDiscoveryFailed", arguments: nil); 70 | } 71 | 72 | public func netServiceBrowserDidStopSearch(_ browser: NetServiceBrowser) { 73 | channel.invokeMethod("onDiscoveryStopped", arguments: nil); 74 | netServiceBrowser.delegate = nil 75 | } 76 | 77 | public func netServiceBrowser(_ browser: NetServiceBrowser, didFind service: NetService, moreComing: Bool) { 78 | services.append(service) 79 | if !moreComing { 80 | self.updateInterface() 81 | } 82 | } 83 | 84 | public func netServiceDidResolveAddress(_ sender: NetService) { 85 | var port: Int? = sender.port 86 | if port == -1 { 87 | port = nil 88 | } 89 | var txt: [String: FlutterStandardTypedData]? = nil; 90 | if let txtRecordData = sender.txtRecordData() { 91 | txt = NetService.dictionary(fromTXTRecord: txtRecordData).mapValues( { (value) -> FlutterStandardTypedData in 92 | FlutterStandardTypedData(bytes: value) 93 | }) 94 | } 95 | 96 | let arguments: [String: Any?] = ["hostname": sender.hostName, "port": port, "name": sender.name, "txt": txt]; 97 | 98 | channel.invokeMethod("onServiceResolved", arguments: arguments) 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /ios/flutter_nsd.podspec: -------------------------------------------------------------------------------- 1 | # 2 | # To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html. 3 | # Run `pod lib lint flutter_nsd.podspec' to validate before publishing. 4 | # 5 | Pod::Spec.new do |s| 6 | s.name = 'flutter_nsd' 7 | s.version = '0.0.1' 8 | s.summary = 'A new flutter plugin project.' 9 | s.description = <<-DESC 10 | A new flutter plugin project. 11 | DESC 12 | s.homepage = 'http://example.com' 13 | s.license = { :file => '../LICENSE' } 14 | s.author = { 'Your Company' => 'email@example.com' } 15 | s.source = { :path => '.' } 16 | s.source_files = 'Classes/**/*' 17 | s.dependency 'Flutter' 18 | s.platform = :ios, '8.0' 19 | 20 | # Flutter.framework does not contain a i386 slice. Only x86_64 simulators are supported. 21 | s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES', 'VALID_ARCHS[sdk=iphonesimulator*]' => 'x86_64' } 22 | s.swift_version = '5.0' 23 | end 24 | -------------------------------------------------------------------------------- /lib/flutter_nsd.dart: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2021 Nimrod Dayan nimroddayan.com 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | */ 17 | 18 | import 'dart:async'; 19 | 20 | import 'package:flutter/services.dart'; 21 | 22 | /// Singleton API for managing Network Service Discovery 23 | /// 24 | /// Get the singleton by calling FlutterNsd() and listen to its [stream] for [NsdServiceInfo] emissions. 25 | /// Then invoke [discoverServices] to start service discovery. 26 | /// Stop discovery by calling [stopDiscovery] when you're done. 27 | /// 28 | class FlutterNsd { 29 | static const MethodChannel _channel = 30 | MethodChannel('com.nimroddayan/flutter_nsd'); 31 | static final FlutterNsd _instance = FlutterNsd._internal(); 32 | 33 | final _streamController = StreamController(); 34 | late Stream _stream; 35 | 36 | /// Factory for getting [FlutterNsd] singleton object 37 | factory FlutterNsd() { 38 | return _instance; 39 | } 40 | 41 | FlutterNsd._internal() { 42 | _stream = _streamController.stream.asBroadcastStream(); 43 | } 44 | 45 | /// Stream that emits a [NsdServiceInfo] for each service discovered or a [NsdError] in case of an error. 46 | Stream get stream => _stream; 47 | 48 | /// Start network service discovery for [serviceType] for an infinite amount 49 | /// of time (or until the app process is killed). Make sure to call [stopDiscovery] when you're done. 50 | Future discoverServices(String serviceType) async { 51 | await _channel.invokeMethod('startDiscovery', {'serviceType': serviceType}); 52 | 53 | _channel.setMethodCallHandler((MethodCall call) async { 54 | switch (call.method) { 55 | case 'onStartDiscoveryFailed': 56 | _streamController.addError(NsdError( 57 | errorCode: NsdErrorCode.startDiscoveryFailed, 58 | )); 59 | break; 60 | case 'onStopDiscoveryFailed': 61 | _streamController.addError(NsdError( 62 | errorCode: NsdErrorCode.stopDiscoveryFailed, 63 | )); 64 | break; 65 | case 'onResolveFailed': 66 | _streamController.addError(NsdError( 67 | errorCode: NsdErrorCode.onResolveFailed, 68 | )); 69 | break; 70 | case 'onDiscoveryStopped': 71 | _streamController.addError(NsdError( 72 | errorCode: NsdErrorCode.discoveryStopped, 73 | )); 74 | _channel.setMethodCallHandler(null); 75 | break; 76 | case 'onServiceResolved': 77 | final nsdServiceInfo = _parseArgs(call); 78 | _streamController.add(nsdServiceInfo); 79 | break; 80 | case 'onServiceLost': 81 | // TODO issue #28 82 | break; 83 | default: 84 | throw MissingPluginException(); 85 | } 86 | }); 87 | } 88 | 89 | NsdServiceInfo _parseArgs(MethodCall call) { 90 | final String hostname = call.arguments['hostname']; 91 | final int port = call.arguments['port']; 92 | final String name = call.arguments['name']; 93 | final Map txt = Map.from(call.arguments['txt']); 94 | List? hostAddresses; 95 | List? rawAddresses = call.arguments['hostAddresses']; 96 | if (rawAddresses != null) { 97 | hostAddresses = rawAddresses.where((e) => e != null).map((e) => e.toString()).toList(); 98 | } 99 | var nsdServiceInfo = NsdServiceInfo(hostname, port, name, txt, hostAddresses: hostAddresses); 100 | return nsdServiceInfo; 101 | } 102 | 103 | /// Stop network service discovery 104 | Future stopDiscovery() async { 105 | await _channel.invokeMethod('stopDiscovery'); 106 | } 107 | } 108 | 109 | /// Info class for holding discovered service 110 | class NsdServiceInfo { 111 | final String? hostname; 112 | /// A list of strings containing the known addresses for this host (Ipv4 and Ipv6). The iOS implementation currently returns null 113 | final List? hostAddresses; 114 | final int? port; 115 | final String? name; 116 | final Map? txt; 117 | 118 | NsdServiceInfo(this.hostname, this.port, this.name, this.txt, {this.hostAddresses}); 119 | } 120 | 121 | /// List of possible error codes of NsdError 122 | enum NsdErrorCode { 123 | startDiscoveryFailed, 124 | stopDiscoveryFailed, 125 | onResolveFailed, 126 | discoveryStopped, 127 | } 128 | 129 | // Generic error thrown when an error has occurred during discovery 130 | class NsdError extends Error { 131 | /// The cause of this [NsdError]. 132 | final NsdErrorCode errorCode; 133 | 134 | NsdError({required this.errorCode}); 135 | } 136 | -------------------------------------------------------------------------------- /macos/Classes/SwiftFlutterNsdPlugin.swift: -------------------------------------------------------------------------------- 1 | ../../apple/Classes/SwiftFlutterNsdPlugin.swift -------------------------------------------------------------------------------- /macos/flutter_nsd.podspec: -------------------------------------------------------------------------------- 1 | # 2 | # To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html. 3 | # Run `pod lib lint flutter_nsd.podspec` to validate before publishing. 4 | # 5 | Pod::Spec.new do |s| 6 | s.name = 'flutter_nsd' 7 | s.version = '0.0.1' 8 | s.summary = 'A new flutter plugin project.' 9 | s.description = <<-DESC 10 | A new flutter plugin project. 11 | DESC 12 | s.homepage = 'http://example.com' 13 | s.license = { :file => '../LICENSE' } 14 | s.author = { 'Your Company' => 'email@example.com' } 15 | s.source = { :path => '.' } 16 | s.source_files = 'Classes/**/*' 17 | s.dependency 'FlutterMacOS' 18 | 19 | s.platform = :osx, '10.11' 20 | s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES' } 21 | s.swift_version = '5.0' 22 | end 23 | -------------------------------------------------------------------------------- /pubspec.yaml: -------------------------------------------------------------------------------- 1 | name: flutter_nsd 2 | description: A Flutter plugin for Network Service Discovery (mDNS) that uses platform API on Android, iOS, MacOS and Windows. 3 | version: 1.6.0 4 | homepage: https://github.com/Nimrodda/flutter_nsd 5 | 6 | environment: 7 | sdk: ">=2.12.0 <4.0.0" 8 | flutter: ">=1.20.0" 9 | 10 | dependencies: 11 | flutter: 12 | sdk: flutter 13 | 14 | dev_dependencies: 15 | flutter_test: 16 | sdk: flutter 17 | flutter_lints: ^1.0.4 18 | 19 | flutter: 20 | plugin: 21 | platforms: 22 | android: 23 | package: com.nimroddayan.flutternsd 24 | pluginClass: FlutterNsdPlugin 25 | ios: 26 | pluginClass: SwiftFlutterNsdPlugin 27 | macos: 28 | pluginClass: SwiftFlutterNsdPlugin 29 | windows: 30 | fileName: flutter_nsd_plugin.cpp 31 | pluginClass: FlutterNsdPlugin 32 | -------------------------------------------------------------------------------- /test/flutter_nsd_test.dart: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2021 Nimrod Dayan nimroddayan.com 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | */ 17 | 18 | import 'package:flutter/services.dart'; 19 | import 'package:flutter_test/flutter_test.dart'; 20 | 21 | void main() { 22 | const MethodChannel channel = MethodChannel('flutter_nsd'); 23 | 24 | TestWidgetsFlutterBinding.ensureInitialized(); 25 | 26 | setUp(() { 27 | TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(channel, (MethodCall methodCall) async { 28 | return '42'; 29 | }); 30 | }); 31 | 32 | tearDown(() { 33 | TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(channel, null); 34 | }); 35 | 36 | test('getPlatformVersion', () async { 37 | //expect(await FlutterNsd.platformVersion, '42'); 38 | }); 39 | } 40 | -------------------------------------------------------------------------------- /windows/.gitignore: -------------------------------------------------------------------------------- 1 | flutter/ 2 | 3 | # Visual Studio user-specific files. 4 | *.suo 5 | *.user 6 | *.userosscache 7 | *.sln.docstates 8 | 9 | # Visual Studio build-related files. 10 | x64/ 11 | x86/ 12 | 13 | # Visual Studio cache files 14 | # files ending in .cache can be ignored 15 | *.[Cc]ache 16 | # but keep track of directories ending in .cache 17 | !*.[Cc]ache/ 18 | -------------------------------------------------------------------------------- /windows/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.15) 2 | set(PROJECT_NAME "flutter_nsd") 3 | project(${PROJECT_NAME} LANGUAGES CXX C) 4 | 5 | # This value is used when generating builds using this plugin, so it must 6 | # not be changed 7 | set(PLUGIN_NAME "flutter_nsd_plugin") 8 | 9 | add_library(${PLUGIN_NAME} SHARED 10 | "flutter_nsd_plugin.cpp" 11 | "mdns_impl.c" 12 | ) 13 | apply_standard_settings(${PLUGIN_NAME}) 14 | set_target_properties(${PLUGIN_NAME} PROPERTIES 15 | CXX_VISIBILITY_PRESET hidden) 16 | target_compile_definitions(${PLUGIN_NAME} PRIVATE FLUTTER_PLUGIN_IMPL) 17 | target_include_directories(${PLUGIN_NAME} INTERFACE 18 | "${CMAKE_CURRENT_SOURCE_DIR}/include") 19 | target_link_libraries(${PLUGIN_NAME} PRIVATE flutter flutter_wrapper_plugin iphlpapi ws2_32) 20 | 21 | 22 | # List of absolute paths to libraries that should be bundled with the plugin 23 | set(flutter_nsd_bundled_libraries 24 | "" 25 | PARENT_SCOPE 26 | ) 27 | -------------------------------------------------------------------------------- /windows/flutter_nsd_plugin.cpp: -------------------------------------------------------------------------------- 1 | #include "include/flutter_nsd/flutter_nsd_plugin.h" 2 | 3 | // This must be included before many other Windows headers. 4 | #include 5 | 6 | 7 | 8 | // For getPlatformVersion; remove unless needed for your plugin implementation. 9 | #include 10 | 11 | #include 12 | #include 13 | #include 14 | 15 | #include 16 | #include 17 | #include 18 | #include 19 | 20 | 21 | #include "mdns_impl.h" 22 | 23 | #if (_DEBUG == 0) 24 | #define printf 25 | #endif 26 | 27 | 28 | namespace { 29 | 30 | 31 | 32 | class MdnsResult { 33 | public: 34 | std::string name; 35 | std::string hostname; 36 | std::string dnsname; 37 | std::string servicename; 38 | std::string ipv4address; 39 | std::string ipv6address; 40 | flutter::EncodableList addressList; 41 | int port; 42 | std::map txt; 43 | }; 44 | 45 | class MdnsSentResult { 46 | public: 47 | std::chrono::steady_clock::time_point lastSeen; 48 | std::string name; 49 | std::string hostname; 50 | int port; 51 | }; 52 | 53 | class MdnsRequest { 54 | 55 | public: 56 | MdnsRequest(std::shared_ptr> _channel); 57 | void start(std::string serviceName); 58 | void stop(); 59 | void callbackPTR(const void* base, boolean last, STRING_ARG_DECL(service), STRING_ARG_DECL(name)); 60 | void callbackSRV(const void* base, boolean last, STRING_ARG_DECL(name), STRING_ARG_DECL(hostname), int port); 61 | void callbackA(const void* base, boolean last, STRING_ARG_DECL(service), STRING_ARG_DECL(address)); 62 | void callbackAAAA(const void* base, boolean last, STRING_ARG_DECL(service), STRING_ARG_DECL(address)); 63 | void callbackTXT(const void* base, boolean last, STRING_ARG_DECL(key), STRING_ARG_DECL(value)); 64 | void callbackU(const void* base, boolean last); 65 | 66 | void process(const void* base, boolean last); 67 | void send(MdnsResult&); 68 | 69 | 70 | private: 71 | void runner(std::string serviceName); 72 | static void ThreadFunc(MdnsRequest* p, std::string serviceName); 73 | volatile boolean keepRunning; 74 | std::shared_ptr> channel; 75 | std::map packets; 76 | std::map sent_results; 77 | 78 | }; 79 | 80 | 81 | MdnsRequest::MdnsRequest(std::shared_ptr> _channel) 82 | 83 | { 84 | channel = _channel; 85 | } 86 | 87 | 88 | void MdnsRequest::send(MdnsResult& packet) { 89 | auto digest = packet.name + packet.dnsname + packet.hostname + packet.ipv4address + packet.ipv6address + std::to_string(packet.port); 90 | auto time = std::chrono::steady_clock::now(); 91 | 92 | 93 | if (sent_results.find(digest) != sent_results.end()) { 94 | sent_results[digest].lastSeen = time; 95 | return; 96 | } 97 | 98 | 99 | if (packet.hostname.empty()) { 100 | packet.hostname = packet.ipv4address; 101 | } 102 | else { 103 | struct hostent* ent = gethostbyname(packet.hostname.c_str()); 104 | if (ent == NULL) { 105 | //printf("cannot resolve hostname %s, returning IP address %s", packet.hostname.c_str(), packet.ipv4address.c_str()); 106 | packet.hostname = packet.ipv4address; 107 | } 108 | } 109 | if (packet.hostname.empty()) { 110 | packet.hostname = packet.ipv6address; 111 | } 112 | std::string name = packet.name; 113 | if (!packet.servicename.empty()) { 114 | size_t pos = name.rfind("." + packet.servicename); 115 | if (pos > 0) { 116 | name = name.substr(0, pos); 117 | } 118 | 119 | } 120 | MdnsSentResult result; 121 | result.name = name; 122 | result.hostname = packet.hostname; 123 | result.port = packet.port; 124 | result.lastSeen = time; 125 | sent_results[digest] = result; 126 | 127 | 128 | channel->InvokeMethod("onServiceResolved", 129 | 130 | std::make_unique(flutter::EncodableValue(flutter::EncodableMap{ 131 | {flutter::EncodableValue("hostname"), flutter::EncodableValue(packet.hostname)}, 132 | {flutter::EncodableValue("ipv4address"), flutter::EncodableValue(packet.ipv4address)}, 133 | {flutter::EncodableValue("ipv6address"), flutter::EncodableValue(packet.ipv6address)}, 134 | {flutter::EncodableValue("hostAddresses"), packet.addressList}, 135 | {flutter::EncodableValue("port"), flutter::EncodableValue(packet.port)}, 136 | {flutter::EncodableValue("name"), flutter::EncodableValue(name)}, 137 | {flutter::EncodableValue("txt"), flutter::EncodableValue(packet.txt)} 138 | } 139 | )) 140 | ); 141 | 142 | } 143 | 144 | void MdnsRequest::process(const void* base, boolean last) { 145 | if (last) { 146 | auto packet = packets[base]; 147 | send(packet); 148 | packets.erase(base); 149 | } 150 | } 151 | 152 | 153 | 154 | void MdnsRequest::callbackPTR(const void* base, boolean last, STRING_ARG_DECL(service), STRING_ARG_DECL(name)) { 155 | MAKE_STRING(service); 156 | MAKE_STRING(name); 157 | MdnsResult& packet = packets[base]; 158 | packet.name = _name; 159 | packet.servicename = _service; 160 | process(base, last); 161 | } 162 | 163 | void MdnsRequest::callbackSRV(const void* base, boolean last, STRING_ARG_DECL(name), STRING_ARG_DECL(hostname), int port) { 164 | MAKE_STRING(name); 165 | MAKE_STRING(hostname); 166 | //printf("resolved: %s, %s\n\r", _name.c_str(), _hostname.c_str()); 167 | 168 | MdnsResult& packet = packets[base]; 169 | packet.name = _name; 170 | packet.hostname = _hostname; 171 | packet.port = port; 172 | process(base, last); 173 | 174 | } 175 | 176 | 177 | 178 | void MdnsRequest::callbackA(const void* base, boolean last, STRING_ARG_DECL(hostname), STRING_ARG_DECL(address)) { 179 | MAKE_STRING(hostname); 180 | MAKE_STRING(address); 181 | MdnsResult& packet = packets[base]; 182 | packet.dnsname = _hostname; 183 | packet.ipv4address = _address; 184 | packet.addressList.push_back(flutter::EncodableValue(_address)); 185 | process(base, last); 186 | 187 | } 188 | void MdnsRequest::callbackAAAA(const void* base, boolean last, STRING_ARG_DECL(hostname), STRING_ARG_DECL(address)) { 189 | MAKE_STRING(hostname); 190 | MAKE_STRING(address); 191 | MdnsResult& packet = packets[base]; 192 | packet.dnsname = _hostname; 193 | packet.ipv6address = _address; 194 | packet.addressList.push_back(flutter::EncodableValue(_address)); 195 | process(base, last); 196 | } 197 | void MdnsRequest::callbackTXT(const void* base, boolean last, STRING_ARG_DECL(key), STRING_ARG_DECL(value)) { 198 | MAKE_STRING(key); 199 | MAKE_STRING(value); 200 | std::vector _vector(_value.begin(), _value.end()); // flutter_nsd expects txt values as UInt8List not as string 201 | MdnsResult& packet = packets[base]; 202 | packet.txt[flutter::EncodableValue(_key)] = flutter::EncodableValue(_vector); 203 | process(base, last); 204 | } 205 | 206 | void MdnsRequest::callbackU(const void* base, boolean last) { 207 | 208 | } 209 | 210 | void MdnsRequest::runner(std::string serviceName) { 211 | while (keepRunning) { 212 | DWORD result = mdns_query(this, (serviceName + "local").c_str()); 213 | for (auto it = packets.begin(); it != packets.end(); it++) { 214 | send(it->second); 215 | } 216 | if (result == -1) return; 217 | auto time = std::chrono::steady_clock::now(); 218 | std::list toDelete; 219 | for (auto i = sent_results.begin(); i != sent_results.end(); i++) { 220 | if (time > (i->second.lastSeen + std::chrono::seconds(30))) { 221 | std::map empty_map; 222 | channel->InvokeMethod("onServiceLost", 223 | 224 | std::make_unique(flutter::EncodableValue(flutter::EncodableMap{ 225 | {flutter::EncodableValue("hostname"), flutter::EncodableValue(i->second.hostname)}, 226 | {flutter::EncodableValue("port"), flutter::EncodableValue(i->second.port)}, 227 | {flutter::EncodableValue("name"), flutter::EncodableValue(i->second.name)}, 228 | {flutter::EncodableValue("txt"), flutter::EncodableValue(empty_map)} 229 | } 230 | )) 231 | ); 232 | toDelete.push_back(i->first); 233 | } 234 | } 235 | for (auto i = toDelete.begin(); i != toDelete.end(); i++) { 236 | sent_results.erase(*i); 237 | } 238 | } 239 | delete this; 240 | } 241 | 242 | 243 | void MdnsRequest::ThreadFunc(MdnsRequest *p, std::string serviceName) 244 | { 245 | p->runner(serviceName); 246 | } 247 | 248 | 249 | void MdnsRequest::start(std::string serviceName) 250 | { 251 | keepRunning = TRUE; 252 | std::thread myThread(ThreadFunc, this, serviceName); 253 | myThread.detach(); 254 | } 255 | 256 | void MdnsRequest::stop() 257 | { 258 | keepRunning = false; 259 | } 260 | 261 | 262 | class FlutterNsdPlugin : public flutter::Plugin { 263 | public: 264 | static void RegisterWithRegistrar(flutter::PluginRegistrarWindows *registrar); 265 | 266 | FlutterNsdPlugin(std::shared_ptr>); 267 | 268 | virtual ~FlutterNsdPlugin(); 269 | 270 | private: 271 | // Called when a method is called on this plugin's channel from Dart. 272 | void HandleMethodCall( 273 | const flutter::MethodCall &method_call, 274 | std::unique_ptr> result); 275 | std::shared_ptr> channel; 276 | boolean wsaInitialized = false; 277 | 278 | MdnsRequest* currentRequest; 279 | 280 | }; 281 | 282 | // static 283 | void FlutterNsdPlugin::RegisterWithRegistrar( 284 | flutter::PluginRegistrarWindows *registrar) { 285 | auto channel = 286 | std::make_shared>( 287 | registrar->messenger(), "com.nimroddayan/flutter_nsd", 288 | &flutter::StandardMethodCodec::GetInstance()); 289 | 290 | auto plugin = std::make_unique(channel); 291 | 292 | channel->SetMethodCallHandler( 293 | [plugin_pointer = plugin.get()](const auto &call, auto result) { 294 | plugin_pointer->HandleMethodCall(call, std::move(result)); 295 | }); 296 | 297 | registrar->AddPlugin(std::move(plugin)); 298 | } 299 | 300 | 301 | 302 | FlutterNsdPlugin::FlutterNsdPlugin(std::shared_ptr> _channel) 303 | 304 | { 305 | channel = _channel; 306 | currentRequest = NULL; 307 | 308 | WORD versionWanted = MAKEWORD(1, 1); 309 | WSADATA wsaData; 310 | if (WSAStartup(versionWanted, &wsaData)) { 311 | 312 | printf("Failed to initialize WinSock\n"); 313 | } 314 | else { 315 | wsaInitialized = true; 316 | } 317 | } 318 | 319 | FlutterNsdPlugin::~FlutterNsdPlugin() { 320 | WSACleanup(); 321 | } 322 | 323 | 324 | 325 | void FlutterNsdPlugin::HandleMethodCall( 326 | const flutter::MethodCall& method_call, 327 | std::unique_ptr> result) { 328 | if (method_call.method_name().compare("startDiscovery") == 0) { 329 | if (!wsaInitialized) { 330 | result->Error("WSAError"); 331 | } 332 | else { 333 | const auto* arguments = std::get_if(method_call.arguments()); 334 | auto serviceType = arguments->find(flutter::EncodableValue("serviceType")); 335 | std::string type = ""; 336 | if (serviceType != arguments->end()) { 337 | type = std::get(serviceType->second); 338 | } 339 | 340 | if (currentRequest != NULL) { 341 | auto req = currentRequest; 342 | currentRequest = NULL; // request will delete itself after the thread exits, we can detach the pointer here 343 | req->stop(); // will stop the background thread after the next timeout; returns immediately 344 | } 345 | currentRequest = new MdnsRequest(channel); 346 | currentRequest->start(type); 347 | result->Success(); 348 | } 349 | } 350 | else if (method_call.method_name().compare("stopDiscovery") == 0) { 351 | if (currentRequest != NULL) { 352 | auto req = currentRequest; 353 | currentRequest = NULL; 354 | req->stop(); 355 | 356 | } 357 | result->Success(); 358 | } 359 | else { 360 | result->NotImplemented(); 361 | } 362 | } 363 | 364 | 365 | 366 | 367 | 368 | 369 | } // namespace 370 | 371 | 372 | 373 | void call_HandlePTRRecord(const void* p, const void* base, boolean last, STRING_ARG_DECL(service), STRING_ARG_DECL(name)) { 374 | ((MdnsRequest*)p)->callbackPTR(base, last, STRING_ARG_CALL(service), STRING_ARG_CALL(name)); 375 | } 376 | 377 | 378 | void call_HandleSRVRecord(const void* p, const void* base, boolean last, STRING_ARG_DECL(name), STRING_ARG_DECL(hostname), int port) { 379 | ((MdnsRequest*)p)->callbackSRV(base, last, STRING_ARG_CALL(name), STRING_ARG_CALL(hostname), port); 380 | } 381 | 382 | 383 | void call_HandleARecord(const void* p, const void* base, boolean last, STRING_ARG_DECL(hostname), STRING_ARG_DECL(address)) { 384 | ((MdnsRequest*)p)->callbackA(base, last, STRING_ARG_CALL(hostname), STRING_ARG_CALL(address)); 385 | } 386 | 387 | void call_HandleAAAARecord(const void* p, const void* base, boolean last, STRING_ARG_DECL(hostname), STRING_ARG_DECL(address)) { 388 | ((MdnsRequest*)p)->callbackAAAA(base, last, STRING_ARG_CALL(hostname), STRING_ARG_CALL(address)); 389 | } 390 | 391 | void call_HandleTXTRecord(const void* p, const void* base, boolean last, STRING_ARG_DECL(key), STRING_ARG_DECL(value)) { 392 | ((MdnsRequest*)p)->callbackTXT(base, last, STRING_ARG_CALL(key), STRING_ARG_CALL(value)); 393 | } 394 | 395 | 396 | void call_HandleURecord(const void* p, const void* base, boolean last) { 397 | ((MdnsRequest*)p)->callbackU(base, last); 398 | } 399 | 400 | 401 | void FlutterNsdPluginRegisterWithRegistrar( 402 | FlutterDesktopPluginRegistrarRef registrar) { 403 | FlutterNsdPlugin::RegisterWithRegistrar( 404 | flutter::PluginRegistrarManager::GetInstance() 405 | ->GetRegistrar(registrar)); 406 | } 407 | 408 | 409 | -------------------------------------------------------------------------------- /windows/include/flutter_nsd/flutter_nsd_plugin.h: -------------------------------------------------------------------------------- 1 | #ifndef FLUTTER_PLUGIN_FLUTTER_NSD_PLUGIN_H_ 2 | #define FLUTTER_PLUGIN_FLUTTER_NSD_PLUGIN_H_ 3 | 4 | #include 5 | 6 | #ifdef FLUTTER_PLUGIN_IMPL 7 | #define FLUTTER_PLUGIN_EXPORT __declspec(dllexport) 8 | #else 9 | #define FLUTTER_PLUGIN_EXPORT __declspec(dllimport) 10 | #endif 11 | 12 | #if defined(__cplusplus) 13 | extern "C" { 14 | #endif 15 | 16 | FLUTTER_PLUGIN_EXPORT void FlutterNsdPluginRegisterWithRegistrar( 17 | FlutterDesktopPluginRegistrarRef registrar); 18 | 19 | #if defined(__cplusplus) 20 | } // extern "C" 21 | #endif 22 | 23 | #endif // FLUTTER_PLUGIN_FLUTTER_NSD_PLUGIN_H_ 24 | -------------------------------------------------------------------------------- /windows/mdns_impl.h: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | #define STRING_ARG_DECL(s) const char *buf_##s, size_t sz_##s 7 | #define STRING_ARG_CALL(s) buf_##s, sz_##s 8 | #define MAKE_STRING(s) std::string _##s = std::string(buf_##s, sz_##s) 9 | 10 | #ifdef __cplusplus 11 | extern "C" { 12 | #endif 13 | extern void call_HandlePTRRecord (const void *p, const void *base, boolean last, STRING_ARG_DECL(service), STRING_ARG_DECL(name)); 14 | extern void call_HandleSRVRecord (const void *p, const void *base, boolean last, STRING_ARG_DECL(name), STRING_ARG_DECL(hostname), int port); 15 | extern void call_HandleARecord (const void *p, const void *base, boolean last, STRING_ARG_DECL(hostname), STRING_ARG_DECL(address)); 16 | extern void call_HandleAAAARecord(const void *p, const void *base, boolean last, STRING_ARG_DECL(hostname), STRING_ARG_DECL(address)); 17 | extern void call_HandleTXTRecord (const void *p, const void *base, boolean last, STRING_ARG_DECL(key), STRING_ARG_DECL(value)); 18 | extern void call_HandleURecord (const void *p, const void *base, boolean last); 19 | 20 | extern int mdns_query(const void* plugin, const char* service_name); 21 | 22 | 23 | #ifdef __cplusplus 24 | } 25 | #endif 26 | --------------------------------------------------------------------------------