diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 0000000..c72eb33 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,5 @@ +blank_issues_enabled: false +contact_links: + - name: Developer Support Forum + url: https://forum.flutterwave.com + about: If you're having general trouble with your integration, Kindly contact our support team. diff --git a/.github/workflows/change-review.yml b/.github/workflows/change-review.yml index 60a1fa5..016b3b1 100644 --- a/.github/workflows/change-review.yml +++ b/.github/workflows/change-review.yml @@ -1,48 +1,51 @@ -name: Code Quality Check +name: Review changes on Dev (Commits/PRs) on: push: - branched: ['develop'] + branches: ['dev'] pull_request: types: - opened jobs: version: - name: Code Checks + name: code-check runs-on: ubuntu-latest steps: - - uses: actions/checkout@v2 - - name: set up flutter environment + - name: checkout code + uses: actions/checkout@v2 + + - name: setup flutter environment uses: subosito/flutter-action@v2 with: flutter-version: '3.0.0' - - name: Install dependencies + - name: install flutter dependencies run: flutter pub get - - name: Run unit tests + - name: run coverage tests run: flutter test --coverage - - name: Install lcov + - name: install lcov for coverage reporting run: sudo apt-get install -y lcov - - name: Remove irrelevant files from coverage + - name: remove irrelevant files from coverage report run: lcov --remove coverage/lcov.info 'lib/view/*.dart' 'lib/*/*.freezed.dart' 'lib/*/*.g.dart' 'lib/*/*.part.dart' 'lib/generated/*.dart' 'lib/generated/*/*.dart' -o coverage/lcov.info - - name: Upload coverage report to Codecov + - name: upload coverage report to Codecov uses: codecov/codecov-action@v2 with: file: coverage/lcov.info token: ${{ secrets.CODECOV_TOKEN }} - - name: push build status to Slack + - name: push build status to slack uses: 8398a7/action-slack@v3 with: status: ${{ job.status }} fields: repo,message,commit,author,action,eventName,ref,workflow,job,took,pullRequest env: SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }} + MATRIX_CONTEXT: ${{ toJson(matrix) }} if: always() diff --git a/.github/workflows/package-publish.yml b/.github/workflows/package-publish.yml index 8ceb415..7992fb2 100644 --- a/.github/workflows/package-publish.yml +++ b/.github/workflows/package-publish.yml @@ -1,36 +1,59 @@ - -name: Publish to Pub.dev +name: Publish changes to Pub.dev on: - push: - branched: ['master'] + release: + types: [created] jobs: - version: - name: Code Checks + check-readme-and-changelog: + runs-on: ubuntu-latest + steps: + - name: checkout code + uses: actions/checkout@v2 + + - name: check for changes in readme and changelog files + run: | + if ! git diff --quiet HEAD~ HEAD -- README.md CHANGELOG.md; then + echo "README and/or CHANGELOG have been modified. Proceeding with deployment." + else + echo "README and/or CHANGELOG have not been modified. Terminating deployment." + exit 1 + fi + + - name: push build status to slack + uses: 8398a7/action-slack@v3 + with: + status: ${{ job.status }} + fields: repo,message,commit,author,action,eventName,ref,workflow,job,took,pullRequest + env: + SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }} + MATRIX_CONTEXT: ${{ toJson(matrix) }} + if: always() + + publish: + needs: check-readme-and-changelog runs-on: ubuntu-latest steps: - - uses: actions/checkout@v2 - - name: set up flutter environment + - name: checkout code + uses: actions/checkout@v2 + + - name: setup flutter environment uses: subosito/flutter-action@v2 with: flutter-version: '3.0.0' - - name: Install dependencies + - name: install flutter dependencies run: flutter pub get - - name: Run unit tests - run: flutter test --coverage - -# - name: Publish to Pub.dev -# run: pub publish --dry-run + - name: Publish to Pub.dev + run: pub publish --dry-run - name: push build status to Slack - uses: 8398a7/action-slack@v3 - with: - status: ${{ job.status }} - fields: repo,message,commit,author,action,eventName,ref,workflow,job,took,pullRequest - env: - SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }} - if: always() - + uses: 8398a7/action-slack@v3 + with: + status: ${{ job.status }} + fields: repo,message,commit,author,action,eventName,ref,workflow,job,took,pullRequest + env: + SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }} + MATRIX_CONTEXT: ${{ toJson(matrix) }} + if: always() diff --git a/CHANGELOG.md b/CHANGELOG.md index 7ed5cd9..4e68f3c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,31 +1,52 @@ +## [1.1.0] | 2025-04-10 + +### Version Changes + +- Modified `Flutterwave.charge()` method to accept a BuildContext parameter. +- Added context.mounted checks to prevent setState calls after widget disposal. +- Enhanced success status check logic to handle different status values ("success" and "completed"). +- Improved error handling and state management. +- Removed deprecated components: `flutterwave_style.dart` and `standard_webview.dart`. +- Updated SDK requirements to `>=2.17.0`. +- Upgraded dependencies to latest versions. +- Removed unused dependencies: webview_flutter, modal_bottom_sheet and uuid. + ## [1.0.7] - February, 2023 -* Fixed iOS bug where webview couldn't close when close buttons are clicked -* Removed required `name` and `phone number` fields in `Customer` object + +- Fixed iOS bug where webview couldn't close when close buttons are clicked +- Removed required `name` and `phone number` fields in `Customer` object ## [1.0.6] - October, 2022 -* Fixed bug where transaction gets stuck after redirecting on webview -* Fixed iOS build bug by removing inAppBrowser library + +- Fixed bug where transaction gets stuck after redirecting on webview +- Fixed iOS build bug by removing inAppBrowser library ## [1.0.5] - October, 2022 -* Fixed null when transaction is cancelled. -* Removed modal pop up before launching web view. -* Removed intermediate make payment screen before webview. -* Deprecated FlutterwaveStyle. -* Updated README file. + +- Fixed null when transaction is cancelled. +- Removed modal pop up before launching web view. +- Removed intermediate make payment screen before webview. +- Deprecated FlutterwaveStyle. +- Updated README file. ## [1.0.4] - July 4, 2022 -* Renamed property `isDebug` to `isTestMode` -* Made property `redirectUrl` required -* Updated README file + +- Renamed property `isDebug` to `isTestMode` +- Made property `redirectUrl` required +- Updated README file ## [1.0.3] - October 4, 2021. -* Fixed issue with webview + +- Fixed issue with webview ## [1.0.2] - September 23, 2021. -* Fixed bug where cancel payment buttons are not clickable on iOS devices. + +- Fixed bug where cancel payment buttons are not clickable on iOS devices. ## [1.0.1] - September 14, 2021. -* Fixed bug where response is not returned to initiating screen when user cancels transaction. + +- Fixed bug where response is not returned to initiating screen when user cancels transaction. ## [1.0.0] - September 9, 2021. -* Initial release \ No newline at end of file + +- Initial release diff --git a/README.md b/README.md index bf6e4f4..510e5ad 100644 --- a/README.md +++ b/README.md @@ -1,21 +1,17 @@ - -

-

+

# Flutterwave Flutter SDK (Standard) The Flutter library helps you create seamless payment experiences in your dart mobile app. By connecting to our modal, you can start collecting payment in no time. - Available features include: -- Collections: Card, Account, Mobile money, Bank Transfers, USSD, Barter. +- Collections: Card, Account, Mobile money, Bank Transfers, USSD. - Recurring payments: Tokenization and Subscriptions. - Split payments - ## Table of Contents 1. [Requirements](#requirements) @@ -25,26 +21,24 @@ Available features include: 5. [Contribution guidelines](#contribution-guidelines) 6. [License](#license) - ## Requirements 1. Flutterwave for business [API Keys](https://developer.flutterwave.com/docs/integration-guides/authentication) 2. Supported Flutter version >= 1.17.0 - +3. Dart SDK >= 2.17.0 +4. For Android: Ensure NDK version >= 27.0.12077973 on your project's android/app/build.gradle.kts file with android { ndkVersion = "27.0.12077973" } ## Installation -1. Add the dependency to your project. In your `pubspec.yaml` file add: `flutterwave_standard: 1.0.7` +1. Add the dependency to your project. In your `pubspec.yaml` file add: `flutterwave_standard: 1.1.0` 2. Run `flutter pub get` - ## Usage ### Initializing a Flutterwave instance To create an instance, you should call the Flutterwave constructor. This constructor accepts a mandatory instance of the following: -- The calling `Context` - `publicKey` - `Customer` - `amount` @@ -58,41 +52,48 @@ To create an instance, you should call the Flutterwave constructor. This constru It returns an instance of Flutterwave which we then call the async method `.charge()` on. -_ +\_ - handlePaymentInitialization() async { + handlePaymentInitialization() async { final Customer customer = Customer( name: "Flutterwave Developer", - phoneNumber: "1234566677777", - email: "customer@customer.com" - ); + phoneNumber: "1234566677777", + email: "customer@customer.com" + ); final Flutterwave flutterwave = Flutterwave( - context: context, publicKey: "Public Key-here", - currency: "currency-here", - redirectUrl: "add-your-redirect-url-here", - txRef: "add-your-unique-reference-here", - amount: "3000", - customer: customer, - paymentOptions: "ussd, card, barter, payattitude", + publicKey: "Public Key-here", + currency: "currency-here", + redirectUrl: "add-your-redirect-url-here", + txRef: "add-your-unique-reference-here", + amount: "3000", + customer: customer, + paymentOptions: "ussd, card, bank transfer", customization: Customization(title: "My Payment"), isTestMode: true ); - } -### Handling the response + final ChargeResponse response = await flutterwave.charge(context); -Calling the `.charge()` method returns a `Future` of `ChargeResponse` which we await for the actual response as seen above. + // Handle the response + if (response.success == true) { + // Payment was successful + } else { + // Payment failed or was cancelled + } + } +### Handling the response +Calling the `.charge()` method returns a `Future` of `ChargeResponse` which we await for the actual response as seen above. - final ChargeResponse response = await flutterwave.charge(); + final ChargeResponse response = await flutterwave.charge(context); -Call the verify transaction [endpoint](https://developer.flutterwave.com/docs/verifications/transaction) with the `transactionID` returned in `response.transactionId` or the `txRef` you provided to verify transaction before offering value to customer +Call the verify transaction [endpoint](https://developer.flutterwave.com/docs/transaction-verification) with the `transactionID` returned in `response.transactionId` or the `txRef` you provided to verify transaction before offering value to customer #### Note - `ChargeResponse` can be null, depending on if the user cancels the transaction by pressing back. -- You need to confirm the transaction is successful. Ensure that the txRef, amount, and status are correct and successful. Be sure to [verify the transaction details](https://developer.flutterwave.com/docs/verifications/transaction) before providing value. -- Some payment methods are not instant, such a `Pay with Bank Transfers, Pay with Bank`, and so you would need to rely on [webhooks](https://developer.flutterwave.com/docs/integration-guides/webhooks) or call the transaction verification service using the [`transactionId`](https://developer.flutterwave.com/reference/endpoints/transactions#verify-a-transaction), or transaction reference you created(`txRef`) +- You need to confirm the transaction is successful. Ensure that the txRef, amount, and status are correct and successful. Be sure to [verify the transaction details](https://developer.flutterwave.com/docs/transaction-verification) before providing value. +- Some payment methods are not instant, such a `Pay with Bank Transfers, Pay with Bank`, and so you would need to rely on [webhooks](https://developer.flutterwave.com/docs/webhooks) or call the transaction verification service using the [`transactionId`](https://developer.flutterwave.com/reference/verify-transaction), or transaction reference you created(`txRef`) - For such long payments like the above, closing the payment page returns a `cancelled` status, so your final source of truth has to be calling the transaction verification service. ## Support @@ -119,8 +120,9 @@ Copyright (c) Flutterwave Inc. - [fluttertoast](https://pub.dev/packages/fluttertoast) -## Flutterwave API References -- [Flutterwave API Doc](https://developer.flutterwave.com/docs) -- [Flutterwave Inline Payment Doc](https://developer.flutterwave.com/docs/flutterwave-inline) +## Flutterwave API References + +- [Flutterwave API Doc](https://developer.flutterwave.com) +- [Flutterwave Inline Payment Doc](https://developer.flutterwave.com/docs/inline) - [Flutterwave Dashboard](https://dashboard.flutterwave.com/login) diff --git a/example/.gitignore b/example/.gitignore index f3c2053..79c113f 100644 --- a/example/.gitignore +++ b/example/.gitignore @@ -5,9 +5,12 @@ *.swp .DS_Store .atom/ +.build/ .buildlog/ .history .svn/ +.swiftpm/ +migrate_working_dir/ # IntelliJ related *.iml @@ -26,19 +29,17 @@ .dart_tool/ .flutter-plugins .flutter-plugins-dependencies -.packages .pub-cache/ .pub/ /build/ -# Web related -lib/generated_plugin_registrant.dart - # Symbolication related app.*.symbols # Obfuscation related app.*.map.json -# Exceptions to above rules. -!/packages/flutter_tools/test/data/dart_dependencies_test/**/.packages +# Android Studio will place build artifacts here +/android/app/debug +/android/app/profile +/android/app/release diff --git a/example/.metadata b/example/.metadata index 245a8e8..d77a4e0 100644 --- a/example/.metadata +++ b/example/.metadata @@ -1,11 +1,11 @@ # This file tracks properties of this Flutter project. # Used by Flutter tool to assess capabilities and perform upgrades etc. # -# This file should be version controlled. +# This file should be version controlled and should not be manually edited. version: - revision: 85684f9300908116a78138ea4c6036c35c9a1236 - channel: stable + revision: "c23637390482d4cf9598c3ce3f2be31aa7332daf" + channel: "stable" project_type: app @@ -13,11 +13,26 @@ project_type: app migration: platforms: - platform: root - create_revision: 85684f9300908116a78138ea4c6036c35c9a1236 - base_revision: 85684f9300908116a78138ea4c6036c35c9a1236 + create_revision: c23637390482d4cf9598c3ce3f2be31aa7332daf + base_revision: c23637390482d4cf9598c3ce3f2be31aa7332daf - platform: android - create_revision: 85684f9300908116a78138ea4c6036c35c9a1236 - base_revision: 85684f9300908116a78138ea4c6036c35c9a1236 + create_revision: c23637390482d4cf9598c3ce3f2be31aa7332daf + base_revision: c23637390482d4cf9598c3ce3f2be31aa7332daf + - platform: ios + create_revision: c23637390482d4cf9598c3ce3f2be31aa7332daf + base_revision: c23637390482d4cf9598c3ce3f2be31aa7332daf + - platform: linux + create_revision: c23637390482d4cf9598c3ce3f2be31aa7332daf + base_revision: c23637390482d4cf9598c3ce3f2be31aa7332daf + - platform: macos + create_revision: c23637390482d4cf9598c3ce3f2be31aa7332daf + base_revision: c23637390482d4cf9598c3ce3f2be31aa7332daf + - platform: web + create_revision: c23637390482d4cf9598c3ce3f2be31aa7332daf + base_revision: c23637390482d4cf9598c3ce3f2be31aa7332daf + - platform: windows + create_revision: c23637390482d4cf9598c3ce3f2be31aa7332daf + base_revision: c23637390482d4cf9598c3ce3f2be31aa7332daf # User provided section diff --git a/example/README.md b/example/README.md index 81f23a1..2b3fce4 100644 --- a/example/README.md +++ b/example/README.md @@ -1,4 +1,4 @@ -# flutterwave_beta +# example A new Flutter project. @@ -8,9 +8,9 @@ This project is a starting point for a Flutter application. A few resources to get you started if this is your first Flutter project: -- [Lab: Write your first Flutter app](https://flutter.dev/docs/get-started/codelab) -- [Cookbook: Useful Flutter samples](https://flutter.dev/docs/cookbook) +- [Lab: Write your first Flutter app](https://docs.flutter.dev/get-started/codelab) +- [Cookbook: Useful Flutter samples](https://docs.flutter.dev/cookbook) -For help getting started with Flutter, view our -[online documentation](https://flutter.dev/docs), which offers tutorials, +For help getting started with Flutter development, view the +[online documentation](https://docs.flutter.dev/), which offers tutorials, samples, guidance on mobile development, and a full API reference. diff --git a/example/analysis_options.yaml b/example/analysis_options.yaml index 61b6c4d..0d29021 100644 --- a/example/analysis_options.yaml +++ b/example/analysis_options.yaml @@ -13,8 +13,7 @@ linter: # The lint rules applied to this project can be customized in the # section below to disable rules from the `package:flutter_lints/flutter.yaml` # included above or to enable additional rules. A list of all available lints - # and their documentation is published at - # https://dart-lang.github.io/linter/lints/index.html. + # and their documentation is published at https://dart.dev/lints. # # Instead of disabling a lint rule for the entire project in the # section below, it can also be suppressed for a single line of code diff --git a/example/android/.gitignore b/example/android/.gitignore index 6f56801..be3943c 100644 --- a/example/android/.gitignore +++ b/example/android/.gitignore @@ -5,9 +5,10 @@ gradle-wrapper.jar /gradlew.bat /local.properties GeneratedPluginRegistrant.java +.cxx/ # Remember to never publicly share your keystore. -# See https://flutter.dev/docs/deployment/android#reference-the-keystore-from-the-app +# See https://flutter.dev/to/reference-keystore key.properties **/*.keystore **/*.jks diff --git a/example/android/app/build.gradle b/example/android/app/build.gradle deleted file mode 100644 index ee6e033..0000000 --- a/example/android/app/build.gradle +++ /dev/null @@ -1,72 +0,0 @@ -def localProperties = new Properties() -def localPropertiesFile = rootProject.file('local.properties') -if (localPropertiesFile.exists()) { - localPropertiesFile.withReader('UTF-8') { reader -> - localProperties.load(reader) - } -} - -def flutterRoot = localProperties.getProperty('flutter.sdk') -if (flutterRoot == null) { - throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.") -} - -def flutterVersionCode = localProperties.getProperty('flutter.versionCode') -if (flutterVersionCode == null) { - flutterVersionCode = '1' -} - -def flutterVersionName = localProperties.getProperty('flutter.versionName') -if (flutterVersionName == null) { - flutterVersionName = '1.0' -} - -apply plugin: 'com.android.application' -apply plugin: 'kotlin-android' -apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle" - -android { -// compileSdkVersion flutter.compileSdkVersion - compileSdkVersion 32 - ndkVersion flutter.ndkVersion - - compileOptions { - sourceCompatibility JavaVersion.VERSION_1_8 - targetCompatibility JavaVersion.VERSION_1_8 - } - - kotlinOptions { - jvmTarget = '1.8' - } - - sourceSets { - main.java.srcDirs += 'src/main/kotlin' - } - - defaultConfig { - // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). - applicationId "com.example.example" - // You can update the following values to match your application needs. - // For more information, see: https://docs.flutter.dev/deployment/android#reviewing-the-build-configuration. - minSdkVersion 19 - targetSdkVersion flutter.targetSdkVersion - versionCode flutterVersionCode.toInteger() - versionName flutterVersionName - } - - buildTypes { - release { - // TODO: Add your own signing config for the release build. - // Signing with the debug keys for now, so `flutter run --release` works. - signingConfig signingConfigs.debug - } - } -} - -flutter { - source '../..' -} - -dependencies { - implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" -} diff --git a/example/android/app/build.gradle.kts b/example/android/app/build.gradle.kts new file mode 100644 index 0000000..d77dd1a --- /dev/null +++ b/example/android/app/build.gradle.kts @@ -0,0 +1,44 @@ +plugins { + id("com.android.application") + id("kotlin-android") + // The Flutter Gradle Plugin must be applied after the Android and Kotlin Gradle plugins. + id("dev.flutter.flutter-gradle-plugin") +} + +android { + namespace = "com.example.example" + compileSdk = flutter.compileSdkVersion + ndkVersion = "27.0.12077973" + + compileOptions { + sourceCompatibility = JavaVersion.VERSION_11 + targetCompatibility = JavaVersion.VERSION_11 + } + + kotlinOptions { + jvmTarget = JavaVersion.VERSION_11.toString() + } + + defaultConfig { + // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). + applicationId = "com.example.example" + // You can update the following values to match your application needs. + // For more information, see: https://flutter.dev/to/review-gradle-config. + minSdk = flutter.minSdkVersion + targetSdk = flutter.targetSdkVersion + versionCode = flutter.versionCode + versionName = flutter.versionName + } + + buildTypes { + release { + // TODO: Add your own signing config for the release build. + // Signing with the debug keys for now, so `flutter run --release` works. + signingConfig = signingConfigs.getByName("debug") + } + } +} + +flutter { + source = "../.." +} diff --git a/example/android/app/src/debug/AndroidManifest.xml b/example/android/app/src/debug/AndroidManifest.xml index 45d523a..399f698 100644 --- a/example/android/app/src/debug/AndroidManifest.xml +++ b/example/android/app/src/debug/AndroidManifest.xml @@ -1,5 +1,4 @@ - + + + + + + + diff --git a/example/android/app/src/main/kotlin/com/example/example/MainActivity.kt b/example/android/app/src/main/kotlin/com/example/example/MainActivity.kt index e793a00..ac81bae 100644 --- a/example/android/app/src/main/kotlin/com/example/example/MainActivity.kt +++ b/example/android/app/src/main/kotlin/com/example/example/MainActivity.kt @@ -2,5 +2,4 @@ package com.example.example import io.flutter.embedding.android.FlutterActivity -class MainActivity: FlutterActivity() { -} +class MainActivity : FlutterActivity() diff --git a/example/android/app/src/profile/AndroidManifest.xml b/example/android/app/src/profile/AndroidManifest.xml index 45d523a..399f698 100644 --- a/example/android/app/src/profile/AndroidManifest.xml +++ b/example/android/app/src/profile/AndroidManifest.xml @@ -1,5 +1,4 @@ - + + + + + + + + + + + + + + + + + example + + + + + + diff --git a/example/web/manifest.json b/example/web/manifest.json new file mode 100644 index 0000000..096edf8 --- /dev/null +++ b/example/web/manifest.json @@ -0,0 +1,35 @@ +{ + "name": "example", + "short_name": "example", + "start_url": ".", + "display": "standalone", + "background_color": "#0175C2", + "theme_color": "#0175C2", + "description": "A new Flutter project.", + "orientation": "portrait-primary", + "prefer_related_applications": false, + "icons": [ + { + "src": "icons/Icon-192.png", + "sizes": "192x192", + "type": "image/png" + }, + { + "src": "icons/Icon-512.png", + "sizes": "512x512", + "type": "image/png" + }, + { + "src": "icons/Icon-maskable-192.png", + "sizes": "192x192", + "type": "image/png", + "purpose": "maskable" + }, + { + "src": "icons/Icon-maskable-512.png", + "sizes": "512x512", + "type": "image/png", + "purpose": "maskable" + } + ] +} diff --git a/example/windows/.gitignore b/example/windows/.gitignore new file mode 100644 index 0000000..d492d0d --- /dev/null +++ b/example/windows/.gitignore @@ -0,0 +1,17 @@ +flutter/ephemeral/ + +# Visual Studio user-specific files. +*.suo +*.user +*.userosscache +*.sln.docstates + +# Visual Studio build-related files. +x64/ +x86/ + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!*.[Cc]ache/ diff --git a/example/windows/CMakeLists.txt b/example/windows/CMakeLists.txt new file mode 100644 index 0000000..d960948 --- /dev/null +++ b/example/windows/CMakeLists.txt @@ -0,0 +1,108 @@ +# Project-level configuration. +cmake_minimum_required(VERSION 3.14) +project(example LANGUAGES CXX) + +# The name of the executable created for the application. Change this to change +# the on-disk name of your application. +set(BINARY_NAME "example") + +# Explicitly opt in to modern CMake behaviors to avoid warnings with recent +# versions of CMake. +cmake_policy(VERSION 3.14...3.25) + +# Define build configuration option. +get_property(IS_MULTICONFIG GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG) +if(IS_MULTICONFIG) + set(CMAKE_CONFIGURATION_TYPES "Debug;Profile;Release" + CACHE STRING "" FORCE) +else() + if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) + set(CMAKE_BUILD_TYPE "Debug" CACHE + STRING "Flutter build mode" FORCE) + set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS + "Debug" "Profile" "Release") + endif() +endif() +# Define settings for the Profile build mode. +set(CMAKE_EXE_LINKER_FLAGS_PROFILE "${CMAKE_EXE_LINKER_FLAGS_RELEASE}") +set(CMAKE_SHARED_LINKER_FLAGS_PROFILE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE}") +set(CMAKE_C_FLAGS_PROFILE "${CMAKE_C_FLAGS_RELEASE}") +set(CMAKE_CXX_FLAGS_PROFILE "${CMAKE_CXX_FLAGS_RELEASE}") + +# Use Unicode for all projects. +add_definitions(-DUNICODE -D_UNICODE) + +# Compilation settings that should be applied to most targets. +# +# Be cautious about adding new options here, as plugins use this function by +# default. In most cases, you should add new options to specific targets instead +# of modifying this function. +function(APPLY_STANDARD_SETTINGS TARGET) + target_compile_features(${TARGET} PUBLIC cxx_std_17) + target_compile_options(${TARGET} PRIVATE /W4 /WX /wd"4100") + target_compile_options(${TARGET} PRIVATE /EHsc) + target_compile_definitions(${TARGET} PRIVATE "_HAS_EXCEPTIONS=0") + target_compile_definitions(${TARGET} PRIVATE "$<$:_DEBUG>") +endfunction() + +# Flutter library and tool build rules. +set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") +add_subdirectory(${FLUTTER_MANAGED_DIR}) + +# Application build; see runner/CMakeLists.txt. +add_subdirectory("runner") + + +# Generated plugin build rules, which manage building the plugins and adding +# them to the application. +include(flutter/generated_plugins.cmake) + + +# === Installation === +# Support files are copied into place next to the executable, so that it can +# run in place. This is done instead of making a separate bundle (as on Linux) +# so that building and running from within Visual Studio will work. +set(BUILD_BUNDLE_DIR "$") +# Make the "install" step default, as it's required to run. +set(CMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD 1) +if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) + set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) +endif() + +set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") +set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}") + +install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +if(PLUGIN_BUNDLED_LIBRARIES) + install(FILES "${PLUGIN_BUNDLED_LIBRARIES}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endif() + +# Copy the native assets provided by the build.dart from all packages. +set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/windows/") +install(DIRECTORY "${NATIVE_ASSETS_DIR}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +# Fully re-copy the assets directory on each build to avoid having stale files +# from a previous install. +set(FLUTTER_ASSET_DIR_NAME "flutter_assets") +install(CODE " + file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") + " COMPONENT Runtime) +install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" + DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) + +# Install the AOT library on non-Debug builds only. +install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + CONFIGURATIONS Profile;Release + COMPONENT Runtime) diff --git a/example/windows/flutter/CMakeLists.txt b/example/windows/flutter/CMakeLists.txt new file mode 100644 index 0000000..903f489 --- /dev/null +++ b/example/windows/flutter/CMakeLists.txt @@ -0,0 +1,109 @@ +# This file controls Flutter-level build steps. It should not be edited. +cmake_minimum_required(VERSION 3.14) + +set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") + +# Configuration provided via flutter tool. +include(${EPHEMERAL_DIR}/generated_config.cmake) + +# TODO: Move the rest of this into files in ephemeral. See +# https://github.com/flutter/flutter/issues/57146. +set(WRAPPER_ROOT "${EPHEMERAL_DIR}/cpp_client_wrapper") + +# Set fallback configurations for older versions of the flutter tool. +if (NOT DEFINED FLUTTER_TARGET_PLATFORM) + set(FLUTTER_TARGET_PLATFORM "windows-x64") +endif() + +# === Flutter Library === +set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/flutter_windows.dll") + +# Published to parent scope for install step. +set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) +set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) +set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) +set(AOT_LIBRARY "${PROJECT_DIR}/build/windows/app.so" PARENT_SCOPE) + +list(APPEND FLUTTER_LIBRARY_HEADERS + "flutter_export.h" + "flutter_windows.h" + "flutter_messenger.h" + "flutter_plugin_registrar.h" + "flutter_texture_registrar.h" +) +list(TRANSFORM FLUTTER_LIBRARY_HEADERS PREPEND "${EPHEMERAL_DIR}/") +add_library(flutter INTERFACE) +target_include_directories(flutter INTERFACE + "${EPHEMERAL_DIR}" +) +target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}.lib") +add_dependencies(flutter flutter_assemble) + +# === Wrapper === +list(APPEND CPP_WRAPPER_SOURCES_CORE + "core_implementations.cc" + "standard_codec.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_CORE PREPEND "${WRAPPER_ROOT}/") +list(APPEND CPP_WRAPPER_SOURCES_PLUGIN + "plugin_registrar.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_PLUGIN PREPEND "${WRAPPER_ROOT}/") +list(APPEND CPP_WRAPPER_SOURCES_APP + "flutter_engine.cc" + "flutter_view_controller.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_APP PREPEND "${WRAPPER_ROOT}/") + +# Wrapper sources needed for a plugin. +add_library(flutter_wrapper_plugin STATIC + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_PLUGIN} +) +apply_standard_settings(flutter_wrapper_plugin) +set_target_properties(flutter_wrapper_plugin PROPERTIES + POSITION_INDEPENDENT_CODE ON) +set_target_properties(flutter_wrapper_plugin PROPERTIES + CXX_VISIBILITY_PRESET hidden) +target_link_libraries(flutter_wrapper_plugin PUBLIC flutter) +target_include_directories(flutter_wrapper_plugin PUBLIC + "${WRAPPER_ROOT}/include" +) +add_dependencies(flutter_wrapper_plugin flutter_assemble) + +# Wrapper sources needed for the runner. +add_library(flutter_wrapper_app STATIC + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_APP} +) +apply_standard_settings(flutter_wrapper_app) +target_link_libraries(flutter_wrapper_app PUBLIC flutter) +target_include_directories(flutter_wrapper_app PUBLIC + "${WRAPPER_ROOT}/include" +) +add_dependencies(flutter_wrapper_app flutter_assemble) + +# === Flutter tool backend === +# _phony_ is a non-existent file to force this command to run every time, +# since currently there's no way to get a full input/output list from the +# flutter tool. +set(PHONY_OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/_phony_") +set_source_files_properties("${PHONY_OUTPUT}" PROPERTIES SYMBOLIC TRUE) +add_custom_command( + OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} + ${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_PLUGIN} + ${CPP_WRAPPER_SOURCES_APP} + ${PHONY_OUTPUT} + COMMAND ${CMAKE_COMMAND} -E env + ${FLUTTER_TOOL_ENVIRONMENT} + "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.bat" + ${FLUTTER_TARGET_PLATFORM} $ + VERBATIM +) +add_custom_target(flutter_assemble DEPENDS + "${FLUTTER_LIBRARY}" + ${FLUTTER_LIBRARY_HEADERS} + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_PLUGIN} + ${CPP_WRAPPER_SOURCES_APP} +) diff --git a/example/windows/flutter/generated_plugin_registrant.cc b/example/windows/flutter/generated_plugin_registrant.cc new file mode 100644 index 0000000..3b4ee90 --- /dev/null +++ b/example/windows/flutter/generated_plugin_registrant.cc @@ -0,0 +1,14 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#include "generated_plugin_registrant.h" + +#include + +void RegisterPlugins(flutter::PluginRegistry* registry) { + FlutterInappwebviewWindowsPluginCApiRegisterWithRegistrar( + registry->GetRegistrarForPlugin("FlutterInappwebviewWindowsPluginCApi")); +} diff --git a/example/windows/flutter/generated_plugin_registrant.h b/example/windows/flutter/generated_plugin_registrant.h new file mode 100644 index 0000000..dc139d8 --- /dev/null +++ b/example/windows/flutter/generated_plugin_registrant.h @@ -0,0 +1,15 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#ifndef GENERATED_PLUGIN_REGISTRANT_ +#define GENERATED_PLUGIN_REGISTRANT_ + +#include + +// Registers Flutter plugins. +void RegisterPlugins(flutter::PluginRegistry* registry); + +#endif // GENERATED_PLUGIN_REGISTRANT_ diff --git a/example/windows/flutter/generated_plugins.cmake b/example/windows/flutter/generated_plugins.cmake new file mode 100644 index 0000000..61c79a2 --- /dev/null +++ b/example/windows/flutter/generated_plugins.cmake @@ -0,0 +1,24 @@ +# +# Generated file, do not edit. +# + +list(APPEND FLUTTER_PLUGIN_LIST + flutter_inappwebview_windows +) + +list(APPEND FLUTTER_FFI_PLUGIN_LIST +) + +set(PLUGIN_BUNDLED_LIBRARIES) + +foreach(plugin ${FLUTTER_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/windows plugins/${plugin}) + target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) + list(APPEND PLUGIN_BUNDLED_LIBRARIES $) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) +endforeach(plugin) + +foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/windows plugins/${ffi_plugin}) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) +endforeach(ffi_plugin) diff --git a/example/windows/runner/CMakeLists.txt b/example/windows/runner/CMakeLists.txt new file mode 100644 index 0000000..394917c --- /dev/null +++ b/example/windows/runner/CMakeLists.txt @@ -0,0 +1,40 @@ +cmake_minimum_required(VERSION 3.14) +project(runner LANGUAGES CXX) + +# Define the application target. To change its name, change BINARY_NAME in the +# top-level CMakeLists.txt, not the value here, or `flutter run` will no longer +# work. +# +# Any new source files that you add to the application should be added here. +add_executable(${BINARY_NAME} WIN32 + "flutter_window.cpp" + "main.cpp" + "utils.cpp" + "win32_window.cpp" + "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" + "Runner.rc" + "runner.exe.manifest" +) + +# Apply the standard set of build settings. This can be removed for applications +# that need different build settings. +apply_standard_settings(${BINARY_NAME}) + +# Add preprocessor definitions for the build version. +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION=\"${FLUTTER_VERSION}\"") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MAJOR=${FLUTTER_VERSION_MAJOR}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MINOR=${FLUTTER_VERSION_MINOR}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_PATCH=${FLUTTER_VERSION_PATCH}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_BUILD=${FLUTTER_VERSION_BUILD}") + +# Disable Windows macros that collide with C++ standard library functions. +target_compile_definitions(${BINARY_NAME} PRIVATE "NOMINMAX") + +# Add dependency libraries and include directories. Add any application-specific +# dependencies here. +target_link_libraries(${BINARY_NAME} PRIVATE flutter flutter_wrapper_app) +target_link_libraries(${BINARY_NAME} PRIVATE "dwmapi.lib") +target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") + +# Run the Flutter tool portions of the build. This must not be removed. +add_dependencies(${BINARY_NAME} flutter_assemble) diff --git a/example/windows/runner/Runner.rc b/example/windows/runner/Runner.rc new file mode 100644 index 0000000..289fc7e --- /dev/null +++ b/example/windows/runner/Runner.rc @@ -0,0 +1,121 @@ +// Microsoft Visual C++ generated resource script. +// +#pragma code_page(65001) +#include "resource.h" + +#define APSTUDIO_READONLY_SYMBOLS +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 2 resource. +// +#include "winres.h" + +///////////////////////////////////////////////////////////////////////////// +#undef APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +// English (United States) resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) +LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US + +#ifdef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +1 TEXTINCLUDE +BEGIN + "resource.h\0" +END + +2 TEXTINCLUDE +BEGIN + "#include ""winres.h""\r\n" + "\0" +END + +3 TEXTINCLUDE +BEGIN + "\r\n" + "\0" +END + +#endif // APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// +// Icon +// + +// Icon with lowest ID value placed first to ensure application icon +// remains consistent on all systems. +IDI_APP_ICON ICON "resources\\app_icon.ico" + + +///////////////////////////////////////////////////////////////////////////// +// +// Version +// + +#if defined(FLUTTER_VERSION_MAJOR) && defined(FLUTTER_VERSION_MINOR) && defined(FLUTTER_VERSION_PATCH) && defined(FLUTTER_VERSION_BUILD) +#define VERSION_AS_NUMBER FLUTTER_VERSION_MAJOR,FLUTTER_VERSION_MINOR,FLUTTER_VERSION_PATCH,FLUTTER_VERSION_BUILD +#else +#define VERSION_AS_NUMBER 1,0,0,0 +#endif + +#if defined(FLUTTER_VERSION) +#define VERSION_AS_STRING FLUTTER_VERSION +#else +#define VERSION_AS_STRING "1.0.0" +#endif + +VS_VERSION_INFO VERSIONINFO + FILEVERSION VERSION_AS_NUMBER + PRODUCTVERSION VERSION_AS_NUMBER + FILEFLAGSMASK VS_FFI_FILEFLAGSMASK +#ifdef _DEBUG + FILEFLAGS VS_FF_DEBUG +#else + FILEFLAGS 0x0L +#endif + FILEOS VOS__WINDOWS32 + FILETYPE VFT_APP + FILESUBTYPE 0x0L +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904e4" + BEGIN + VALUE "CompanyName", "com.example" "\0" + VALUE "FileDescription", "example" "\0" + VALUE "FileVersion", VERSION_AS_STRING "\0" + VALUE "InternalName", "example" "\0" + VALUE "LegalCopyright", "Copyright (C) 2025 com.example. All rights reserved." "\0" + VALUE "OriginalFilename", "example.exe" "\0" + VALUE "ProductName", "example" "\0" + VALUE "ProductVersion", VERSION_AS_STRING "\0" + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x409, 1252 + END +END + +#endif // English (United States) resources +///////////////////////////////////////////////////////////////////////////// + + + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// + + +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED diff --git a/example/windows/runner/flutter_window.cpp b/example/windows/runner/flutter_window.cpp new file mode 100644 index 0000000..955ee30 --- /dev/null +++ b/example/windows/runner/flutter_window.cpp @@ -0,0 +1,71 @@ +#include "flutter_window.h" + +#include + +#include "flutter/generated_plugin_registrant.h" + +FlutterWindow::FlutterWindow(const flutter::DartProject& project) + : project_(project) {} + +FlutterWindow::~FlutterWindow() {} + +bool FlutterWindow::OnCreate() { + if (!Win32Window::OnCreate()) { + return false; + } + + RECT frame = GetClientArea(); + + // The size here must match the window dimensions to avoid unnecessary surface + // creation / destruction in the startup path. + flutter_controller_ = std::make_unique( + frame.right - frame.left, frame.bottom - frame.top, project_); + // Ensure that basic setup of the controller was successful. + if (!flutter_controller_->engine() || !flutter_controller_->view()) { + return false; + } + RegisterPlugins(flutter_controller_->engine()); + SetChildContent(flutter_controller_->view()->GetNativeWindow()); + + flutter_controller_->engine()->SetNextFrameCallback([&]() { + this->Show(); + }); + + // Flutter can complete the first frame before the "show window" callback is + // registered. The following call ensures a frame is pending to ensure the + // window is shown. It is a no-op if the first frame hasn't completed yet. + flutter_controller_->ForceRedraw(); + + return true; +} + +void FlutterWindow::OnDestroy() { + if (flutter_controller_) { + flutter_controller_ = nullptr; + } + + Win32Window::OnDestroy(); +} + +LRESULT +FlutterWindow::MessageHandler(HWND hwnd, UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + // Give Flutter, including plugins, an opportunity to handle window messages. + if (flutter_controller_) { + std::optional result = + flutter_controller_->HandleTopLevelWindowProc(hwnd, message, wparam, + lparam); + if (result) { + return *result; + } + } + + switch (message) { + case WM_FONTCHANGE: + flutter_controller_->engine()->ReloadSystemFonts(); + break; + } + + return Win32Window::MessageHandler(hwnd, message, wparam, lparam); +} diff --git a/example/windows/runner/flutter_window.h b/example/windows/runner/flutter_window.h new file mode 100644 index 0000000..6da0652 --- /dev/null +++ b/example/windows/runner/flutter_window.h @@ -0,0 +1,33 @@ +#ifndef RUNNER_FLUTTER_WINDOW_H_ +#define RUNNER_FLUTTER_WINDOW_H_ + +#include +#include + +#include + +#include "win32_window.h" + +// A window that does nothing but host a Flutter view. +class FlutterWindow : public Win32Window { + public: + // Creates a new FlutterWindow hosting a Flutter view running |project|. + explicit FlutterWindow(const flutter::DartProject& project); + virtual ~FlutterWindow(); + + protected: + // Win32Window: + bool OnCreate() override; + void OnDestroy() override; + LRESULT MessageHandler(HWND window, UINT const message, WPARAM const wparam, + LPARAM const lparam) noexcept override; + + private: + // The project to run. + flutter::DartProject project_; + + // The Flutter instance hosted by this window. + std::unique_ptr flutter_controller_; +}; + +#endif // RUNNER_FLUTTER_WINDOW_H_ diff --git a/example/windows/runner/main.cpp b/example/windows/runner/main.cpp new file mode 100644 index 0000000..a61bf80 --- /dev/null +++ b/example/windows/runner/main.cpp @@ -0,0 +1,43 @@ +#include +#include +#include + +#include "flutter_window.h" +#include "utils.h" + +int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev, + _In_ wchar_t *command_line, _In_ int show_command) { + // Attach to console when present (e.g., 'flutter run') or create a + // new console when running with a debugger. + if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) { + CreateAndAttachConsole(); + } + + // Initialize COM, so that it is available for use in the library and/or + // plugins. + ::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED); + + flutter::DartProject project(L"data"); + + std::vector command_line_arguments = + GetCommandLineArguments(); + + project.set_dart_entrypoint_arguments(std::move(command_line_arguments)); + + FlutterWindow window(project); + Win32Window::Point origin(10, 10); + Win32Window::Size size(1280, 720); + if (!window.Create(L"example", origin, size)) { + return EXIT_FAILURE; + } + window.SetQuitOnClose(true); + + ::MSG msg; + while (::GetMessage(&msg, nullptr, 0, 0)) { + ::TranslateMessage(&msg); + ::DispatchMessage(&msg); + } + + ::CoUninitialize(); + return EXIT_SUCCESS; +} diff --git a/example/windows/runner/resource.h b/example/windows/runner/resource.h new file mode 100644 index 0000000..66a65d1 --- /dev/null +++ b/example/windows/runner/resource.h @@ -0,0 +1,16 @@ +//{{NO_DEPENDENCIES}} +// Microsoft Visual C++ generated include file. +// Used by Runner.rc +// +#define IDI_APP_ICON 101 + +// Next default values for new objects +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NEXT_RESOURCE_VALUE 102 +#define _APS_NEXT_COMMAND_VALUE 40001 +#define _APS_NEXT_CONTROL_VALUE 1001 +#define _APS_NEXT_SYMED_VALUE 101 +#endif +#endif diff --git a/example/windows/runner/resources/app_icon.ico b/example/windows/runner/resources/app_icon.ico new file mode 100644 index 0000000..c04e20c Binary files /dev/null and b/example/windows/runner/resources/app_icon.ico differ diff --git a/example/windows/runner/runner.exe.manifest b/example/windows/runner/runner.exe.manifest new file mode 100644 index 0000000..153653e --- /dev/null +++ b/example/windows/runner/runner.exe.manifest @@ -0,0 +1,14 @@ + + + + + PerMonitorV2 + + + + + + + + + diff --git a/example/windows/runner/utils.cpp b/example/windows/runner/utils.cpp new file mode 100644 index 0000000..3a0b465 --- /dev/null +++ b/example/windows/runner/utils.cpp @@ -0,0 +1,65 @@ +#include "utils.h" + +#include +#include +#include +#include + +#include + +void CreateAndAttachConsole() { + if (::AllocConsole()) { + FILE *unused; + if (freopen_s(&unused, "CONOUT$", "w", stdout)) { + _dup2(_fileno(stdout), 1); + } + if (freopen_s(&unused, "CONOUT$", "w", stderr)) { + _dup2(_fileno(stdout), 2); + } + std::ios::sync_with_stdio(); + FlutterDesktopResyncOutputStreams(); + } +} + +std::vector GetCommandLineArguments() { + // Convert the UTF-16 command line arguments to UTF-8 for the Engine to use. + int argc; + wchar_t** argv = ::CommandLineToArgvW(::GetCommandLineW(), &argc); + if (argv == nullptr) { + return std::vector(); + } + + std::vector command_line_arguments; + + // Skip the first argument as it's the binary name. + for (int i = 1; i < argc; i++) { + command_line_arguments.push_back(Utf8FromUtf16(argv[i])); + } + + ::LocalFree(argv); + + return command_line_arguments; +} + +std::string Utf8FromUtf16(const wchar_t* utf16_string) { + if (utf16_string == nullptr) { + return std::string(); + } + unsigned int target_length = ::WideCharToMultiByte( + CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, + -1, nullptr, 0, nullptr, nullptr) + -1; // remove the trailing null character + int input_length = (int)wcslen(utf16_string); + std::string utf8_string; + if (target_length == 0 || target_length > utf8_string.max_size()) { + return utf8_string; + } + utf8_string.resize(target_length); + int converted_length = ::WideCharToMultiByte( + CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, + input_length, utf8_string.data(), target_length, nullptr, nullptr); + if (converted_length == 0) { + return std::string(); + } + return utf8_string; +} diff --git a/example/windows/runner/utils.h b/example/windows/runner/utils.h new file mode 100644 index 0000000..3879d54 --- /dev/null +++ b/example/windows/runner/utils.h @@ -0,0 +1,19 @@ +#ifndef RUNNER_UTILS_H_ +#define RUNNER_UTILS_H_ + +#include +#include + +// Creates a console for the process, and redirects stdout and stderr to +// it for both the runner and the Flutter library. +void CreateAndAttachConsole(); + +// Takes a null-terminated wchar_t* encoded in UTF-16 and returns a std::string +// encoded in UTF-8. Returns an empty std::string on failure. +std::string Utf8FromUtf16(const wchar_t* utf16_string); + +// Gets the command line arguments passed in as a std::vector, +// encoded in UTF-8. Returns an empty std::vector on failure. +std::vector GetCommandLineArguments(); + +#endif // RUNNER_UTILS_H_ diff --git a/example/windows/runner/win32_window.cpp b/example/windows/runner/win32_window.cpp new file mode 100644 index 0000000..60608d0 --- /dev/null +++ b/example/windows/runner/win32_window.cpp @@ -0,0 +1,288 @@ +#include "win32_window.h" + +#include +#include + +#include "resource.h" + +namespace { + +/// Window attribute that enables dark mode window decorations. +/// +/// Redefined in case the developer's machine has a Windows SDK older than +/// version 10.0.22000.0. +/// See: https://docs.microsoft.com/windows/win32/api/dwmapi/ne-dwmapi-dwmwindowattribute +#ifndef DWMWA_USE_IMMERSIVE_DARK_MODE +#define DWMWA_USE_IMMERSIVE_DARK_MODE 20 +#endif + +constexpr const wchar_t kWindowClassName[] = L"FLUTTER_RUNNER_WIN32_WINDOW"; + +/// Registry key for app theme preference. +/// +/// A value of 0 indicates apps should use dark mode. A non-zero or missing +/// value indicates apps should use light mode. +constexpr const wchar_t kGetPreferredBrightnessRegKey[] = + L"Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize"; +constexpr const wchar_t kGetPreferredBrightnessRegValue[] = L"AppsUseLightTheme"; + +// The number of Win32Window objects that currently exist. +static int g_active_window_count = 0; + +using EnableNonClientDpiScaling = BOOL __stdcall(HWND hwnd); + +// Scale helper to convert logical scaler values to physical using passed in +// scale factor +int Scale(int source, double scale_factor) { + return static_cast(source * scale_factor); +} + +// Dynamically loads the |EnableNonClientDpiScaling| from the User32 module. +// This API is only needed for PerMonitor V1 awareness mode. +void EnableFullDpiSupportIfAvailable(HWND hwnd) { + HMODULE user32_module = LoadLibraryA("User32.dll"); + if (!user32_module) { + return; + } + auto enable_non_client_dpi_scaling = + reinterpret_cast( + GetProcAddress(user32_module, "EnableNonClientDpiScaling")); + if (enable_non_client_dpi_scaling != nullptr) { + enable_non_client_dpi_scaling(hwnd); + } + FreeLibrary(user32_module); +} + +} // namespace + +// Manages the Win32Window's window class registration. +class WindowClassRegistrar { + public: + ~WindowClassRegistrar() = default; + + // Returns the singleton registrar instance. + static WindowClassRegistrar* GetInstance() { + if (!instance_) { + instance_ = new WindowClassRegistrar(); + } + return instance_; + } + + // Returns the name of the window class, registering the class if it hasn't + // previously been registered. + const wchar_t* GetWindowClass(); + + // Unregisters the window class. Should only be called if there are no + // instances of the window. + void UnregisterWindowClass(); + + private: + WindowClassRegistrar() = default; + + static WindowClassRegistrar* instance_; + + bool class_registered_ = false; +}; + +WindowClassRegistrar* WindowClassRegistrar::instance_ = nullptr; + +const wchar_t* WindowClassRegistrar::GetWindowClass() { + if (!class_registered_) { + WNDCLASS window_class{}; + window_class.hCursor = LoadCursor(nullptr, IDC_ARROW); + window_class.lpszClassName = kWindowClassName; + window_class.style = CS_HREDRAW | CS_VREDRAW; + window_class.cbClsExtra = 0; + window_class.cbWndExtra = 0; + window_class.hInstance = GetModuleHandle(nullptr); + window_class.hIcon = + LoadIcon(window_class.hInstance, MAKEINTRESOURCE(IDI_APP_ICON)); + window_class.hbrBackground = 0; + window_class.lpszMenuName = nullptr; + window_class.lpfnWndProc = Win32Window::WndProc; + RegisterClass(&window_class); + class_registered_ = true; + } + return kWindowClassName; +} + +void WindowClassRegistrar::UnregisterWindowClass() { + UnregisterClass(kWindowClassName, nullptr); + class_registered_ = false; +} + +Win32Window::Win32Window() { + ++g_active_window_count; +} + +Win32Window::~Win32Window() { + --g_active_window_count; + Destroy(); +} + +bool Win32Window::Create(const std::wstring& title, + const Point& origin, + const Size& size) { + Destroy(); + + const wchar_t* window_class = + WindowClassRegistrar::GetInstance()->GetWindowClass(); + + const POINT target_point = {static_cast(origin.x), + static_cast(origin.y)}; + HMONITOR monitor = MonitorFromPoint(target_point, MONITOR_DEFAULTTONEAREST); + UINT dpi = FlutterDesktopGetDpiForMonitor(monitor); + double scale_factor = dpi / 96.0; + + HWND window = CreateWindow( + window_class, title.c_str(), WS_OVERLAPPEDWINDOW, + Scale(origin.x, scale_factor), Scale(origin.y, scale_factor), + Scale(size.width, scale_factor), Scale(size.height, scale_factor), + nullptr, nullptr, GetModuleHandle(nullptr), this); + + if (!window) { + return false; + } + + UpdateTheme(window); + + return OnCreate(); +} + +bool Win32Window::Show() { + return ShowWindow(window_handle_, SW_SHOWNORMAL); +} + +// static +LRESULT CALLBACK Win32Window::WndProc(HWND const window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + if (message == WM_NCCREATE) { + auto window_struct = reinterpret_cast(lparam); + SetWindowLongPtr(window, GWLP_USERDATA, + reinterpret_cast(window_struct->lpCreateParams)); + + auto that = static_cast(window_struct->lpCreateParams); + EnableFullDpiSupportIfAvailable(window); + that->window_handle_ = window; + } else if (Win32Window* that = GetThisFromHandle(window)) { + return that->MessageHandler(window, message, wparam, lparam); + } + + return DefWindowProc(window, message, wparam, lparam); +} + +LRESULT +Win32Window::MessageHandler(HWND hwnd, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + switch (message) { + case WM_DESTROY: + window_handle_ = nullptr; + Destroy(); + if (quit_on_close_) { + PostQuitMessage(0); + } + return 0; + + case WM_DPICHANGED: { + auto newRectSize = reinterpret_cast(lparam); + LONG newWidth = newRectSize->right - newRectSize->left; + LONG newHeight = newRectSize->bottom - newRectSize->top; + + SetWindowPos(hwnd, nullptr, newRectSize->left, newRectSize->top, newWidth, + newHeight, SWP_NOZORDER | SWP_NOACTIVATE); + + return 0; + } + case WM_SIZE: { + RECT rect = GetClientArea(); + if (child_content_ != nullptr) { + // Size and position the child window. + MoveWindow(child_content_, rect.left, rect.top, rect.right - rect.left, + rect.bottom - rect.top, TRUE); + } + return 0; + } + + case WM_ACTIVATE: + if (child_content_ != nullptr) { + SetFocus(child_content_); + } + return 0; + + case WM_DWMCOLORIZATIONCOLORCHANGED: + UpdateTheme(hwnd); + return 0; + } + + return DefWindowProc(window_handle_, message, wparam, lparam); +} + +void Win32Window::Destroy() { + OnDestroy(); + + if (window_handle_) { + DestroyWindow(window_handle_); + window_handle_ = nullptr; + } + if (g_active_window_count == 0) { + WindowClassRegistrar::GetInstance()->UnregisterWindowClass(); + } +} + +Win32Window* Win32Window::GetThisFromHandle(HWND const window) noexcept { + return reinterpret_cast( + GetWindowLongPtr(window, GWLP_USERDATA)); +} + +void Win32Window::SetChildContent(HWND content) { + child_content_ = content; + SetParent(content, window_handle_); + RECT frame = GetClientArea(); + + MoveWindow(content, frame.left, frame.top, frame.right - frame.left, + frame.bottom - frame.top, true); + + SetFocus(child_content_); +} + +RECT Win32Window::GetClientArea() { + RECT frame; + GetClientRect(window_handle_, &frame); + return frame; +} + +HWND Win32Window::GetHandle() { + return window_handle_; +} + +void Win32Window::SetQuitOnClose(bool quit_on_close) { + quit_on_close_ = quit_on_close; +} + +bool Win32Window::OnCreate() { + // No-op; provided for subclasses. + return true; +} + +void Win32Window::OnDestroy() { + // No-op; provided for subclasses. +} + +void Win32Window::UpdateTheme(HWND const window) { + DWORD light_mode; + DWORD light_mode_size = sizeof(light_mode); + LSTATUS result = RegGetValue(HKEY_CURRENT_USER, kGetPreferredBrightnessRegKey, + kGetPreferredBrightnessRegValue, + RRF_RT_REG_DWORD, nullptr, &light_mode, + &light_mode_size); + + if (result == ERROR_SUCCESS) { + BOOL enable_dark_mode = light_mode == 0; + DwmSetWindowAttribute(window, DWMWA_USE_IMMERSIVE_DARK_MODE, + &enable_dark_mode, sizeof(enable_dark_mode)); + } +} diff --git a/example/windows/runner/win32_window.h b/example/windows/runner/win32_window.h new file mode 100644 index 0000000..e901dde --- /dev/null +++ b/example/windows/runner/win32_window.h @@ -0,0 +1,102 @@ +#ifndef RUNNER_WIN32_WINDOW_H_ +#define RUNNER_WIN32_WINDOW_H_ + +#include + +#include +#include +#include + +// A class abstraction for a high DPI-aware Win32 Window. Intended to be +// inherited from by classes that wish to specialize with custom +// rendering and input handling +class Win32Window { + public: + struct Point { + unsigned int x; + unsigned int y; + Point(unsigned int x, unsigned int y) : x(x), y(y) {} + }; + + struct Size { + unsigned int width; + unsigned int height; + Size(unsigned int width, unsigned int height) + : width(width), height(height) {} + }; + + Win32Window(); + virtual ~Win32Window(); + + // Creates a win32 window with |title| that is positioned and sized using + // |origin| and |size|. New windows are created on the default monitor. Window + // sizes are specified to the OS in physical pixels, hence to ensure a + // consistent size this function will scale the inputted width and height as + // as appropriate for the default monitor. The window is invisible until + // |Show| is called. Returns true if the window was created successfully. + bool Create(const std::wstring& title, const Point& origin, const Size& size); + + // Show the current window. Returns true if the window was successfully shown. + bool Show(); + + // Release OS resources associated with window. + void Destroy(); + + // Inserts |content| into the window tree. + void SetChildContent(HWND content); + + // Returns the backing Window handle to enable clients to set icon and other + // window properties. Returns nullptr if the window has been destroyed. + HWND GetHandle(); + + // If true, closing this window will quit the application. + void SetQuitOnClose(bool quit_on_close); + + // Return a RECT representing the bounds of the current client area. + RECT GetClientArea(); + + protected: + // Processes and route salient window messages for mouse handling, + // size change and DPI. Delegates handling of these to member overloads that + // inheriting classes can handle. + virtual LRESULT MessageHandler(HWND window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept; + + // Called when CreateAndShow is called, allowing subclass window-related + // setup. Subclasses should return false if setup fails. + virtual bool OnCreate(); + + // Called when Destroy is called. + virtual void OnDestroy(); + + private: + friend class WindowClassRegistrar; + + // OS callback called by message pump. Handles the WM_NCCREATE message which + // is passed when the non-client area is being created and enables automatic + // non-client DPI scaling so that the non-client area automatically + // responds to changes in DPI. All other messages are handled by + // MessageHandler. + static LRESULT CALLBACK WndProc(HWND const window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept; + + // Retrieves a class instance pointer for |window| + static Win32Window* GetThisFromHandle(HWND const window) noexcept; + + // Update the window frame's theme to match the system theme. + static void UpdateTheme(HWND const window); + + bool quit_on_close_ = false; + + // window handle for top level window. + HWND window_handle_ = nullptr; + + // window handle for hosted content. + HWND child_content_ = nullptr; +}; + +#endif // RUNNER_WIN32_WINDOW_H_ diff --git a/lib/core/flutterwave.dart b/lib/core/flutterwave.dart index 1480a32..cfdcba8 100644 --- a/lib/core/flutterwave.dart +++ b/lib/core/flutterwave.dart @@ -5,14 +5,11 @@ import 'package:flutterwave_standard/models/requests/standard_request.dart'; import 'package:flutterwave_standard/models/responses/charge_response.dart'; import 'package:flutterwave_standard/models/responses/standard_response.dart'; import 'package:flutterwave_standard/models/subaccount.dart'; -import 'package:flutterwave_standard/utils.dart'; -import 'package:flutterwave_standard/view/flutterwave_style.dart'; import 'package:flutterwave_standard/view/standard_widget.dart'; import 'package:flutterwave_standard/view/view_utils.dart'; import 'package:http/http.dart'; class Flutterwave { - BuildContext context; String txRef; String amount; Customization customization; @@ -25,12 +22,9 @@ class Flutterwave { String? paymentPlanId; List? subAccounts; Map? meta; - FlutterwaveStyle? style; - ChargeResponse? response; Flutterwave( - {required this.context, - required this.publicKey, + {required this.publicKey, required this.txRef, required this.amount, required this.customer, @@ -41,11 +35,10 @@ class Flutterwave { required this.currency, this.paymentPlanId, this.subAccounts, - this.meta, - this.style}); + this.meta}); /// Starts a transaction by calling the Standard service - Future charge() async { + Future charge(BuildContext context) async { final request = StandardRequest( txRef: txRef, amount: amount, @@ -64,14 +57,32 @@ class Flutterwave { try { standardResponse = await request.execute(Client()); + + if (!context.mounted) { + return ChargeResponse( + txRef: request.txRef, + status: "error", + success: false, + ); + } + if ("error" == standardResponse.status) { - FlutterwaveViewUtils.showToast(context, standardResponse.message!); + FlutterwaveViewUtils.showToast( + context, standardResponse.message!); return ChargeResponse( txRef: request.txRef, status: "error", success: false); } if (standardResponse.data?.link == null || standardResponse.data?.link?.isEmpty == true) { + if (!context.mounted) { + return ChargeResponse( + txRef: request.txRef, + status: "error", + success: false, + ); + } + FlutterwaveViewUtils.showToast( context, "Unable to process this transaction. " + @@ -80,22 +91,38 @@ class Flutterwave { txRef: request.txRef, status: "error", success: false); } } catch (error) { + if (!context.mounted) { + return ChargeResponse( + txRef: request.txRef, + status: "error", + success: false, + ); + } + FlutterwaveViewUtils.showToast(context, error.toString()); return ChargeResponse( txRef: request.txRef, status: "error", success: false); } + if (!context.mounted) { + return ChargeResponse( + txRef: request.txRef, + status: "error", + success: false, + ); + } + final response = await Navigator.push( - context, - MaterialPageRoute( - builder: (context) => StandardPaymentWidget( - webUrl: standardResponse!.data!.link!, - ), + context, + MaterialPageRoute( + builder: (context) => StandardPaymentWidget( + webUrl: standardResponse!.data!.link!, ), - ); + ), + ); if (response != null) return response!; - return ChargeResponse(txRef: request.txRef, status: "cancelled", success: false); - } - + return ChargeResponse( + txRef: request.txRef, status: "cancelled", success: false); + } } diff --git a/lib/models/TransactionError.dart b/lib/models/TransactionError.dart index 9ec6fd1..ff4c09e 100644 --- a/lib/models/TransactionError.dart +++ b/lib/models/TransactionError.dart @@ -4,15 +4,15 @@ class TransactionError implements Exception { TransactionError(this.message); @override - String toString() => this.message; + String toString() => message; static String formatError(dynamic error) { try { - if(error["errors"] != null) { + if (error["errors"] != null) { final errorList = error["errors"] as List; return "${errorList.first["message"]}"; } - if(error["message"] != null) { + if (error["message"] != null) { return error["message"]; } return "An unexpected error occurred. Please try again."; @@ -20,4 +20,4 @@ class TransactionError implements Exception { return "An unexpected error occurred. Please try again."; } } -} \ No newline at end of file +} diff --git a/lib/models/requests/customer.dart b/lib/models/requests/customer.dart index 151f809..8ec3e3e 100644 --- a/lib/models/requests/customer.dart +++ b/lib/models/requests/customer.dart @@ -1,4 +1,4 @@ -import '../../utils.dart'; +import 'package:flutterwave_standard/utils.dart'; class Customer { String email; @@ -9,11 +9,11 @@ class Customer { /// Converts instance of Customer to json Map toJson() { - final customer = { - "email": this.email, - "phonenumber": this.phoneNumber ?? "", - "name": this.name ?? "" + final customer = { + "email": email, + "phonenumber": phoneNumber ?? "", + "name": name ?? "" }; return Utils.removeKeysWithEmptyValues(customer); } -} \ No newline at end of file +} diff --git a/lib/models/requests/customizations.dart b/lib/models/requests/customizations.dart index 8906ace..7b22723 100644 --- a/lib/models/requests/customizations.dart +++ b/lib/models/requests/customizations.dart @@ -10,10 +10,10 @@ class Customization { /// Converts instance of Customization to json Map toJson() { final customization = { - "title": this.title != null ? this.title : "", - "description": this.description != null ? this.description : "", - "logo": this.logo != null ? this.logo : "" + "title": title ?? "", + "description": description ?? "", + "logo": logo ?? "", }; return Utils.removeKeysWithEmptyValues(customization); } -} \ No newline at end of file +} diff --git a/lib/models/requests/standard_request.dart b/lib/models/requests/standard_request.dart index 10634bb..a7a839e 100644 --- a/lib/models/requests/standard_request.dart +++ b/lib/models/requests/standard_request.dart @@ -23,19 +23,21 @@ class StandardRequest { List? subAccounts; Map? meta; - StandardRequest({required this.txRef, - required this.amount, - required this.customer, - required this.paymentOptions, - required this.customization, - required this.isTestMode, - required this.publicKey, - required this.redirectUrl, - this.currency, - this.paymentPlanId, - this.subAccounts, - this.meta}); + StandardRequest( + {required this.txRef, + required this.amount, + required this.customer, + required this.paymentOptions, + required this.customization, + required this.isTestMode, + required this.publicKey, + required this.redirectUrl, + this.currency, + this.paymentPlanId, + this.subAccounts, + this.meta}); + @override String toString() => jsonEncode(this._toJson()); /// Converts this instance to json @@ -49,7 +51,8 @@ class StandardRequest { "payment_plan": this.paymentPlanId, "redirect_url": this.redirectUrl, "customer": this.customer.toJson(), - "subaccounts": this.subAccounts?.map((e) => e.toJson()).toList(), + "subaccounts": + this.subAccounts?.map((e) => e.toJson()).toList(), "meta": this.meta, "customizations": customization.toJson() }; @@ -58,19 +61,20 @@ class StandardRequest { /// Executes network call to initiate transactions Future execute(Client client) async { - final url = Utils.getBaseUrl(this.isTestMode) + Utils.STANDARD_PAYMENT; + final url = Utils.getBaseUrl(isTestMode) + Utils.STANDARD_PAYMENT; final uri = Uri.parse(url); try { final response = await client.post(uri, headers: { - HttpHeaders.authorizationHeader: this.publicKey, + HttpHeaders.authorizationHeader: publicKey, HttpHeaders.contentTypeHeader: 'application/json' }, - body: json.encode(this._toJson())); + body: json.encode(_toJson())); final responseBody = json.decode(response.body); if (responseBody["status"] == "error") { - throw TransactionError(TransactionError.formatError(responseBody)); + throw TransactionError( + TransactionError.formatError(responseBody)); } return StandardResponse.fromJson(responseBody); } catch (error) { diff --git a/lib/models/responses/charge_response.dart b/lib/models/responses/charge_response.dart index fd2ea2a..bee3008 100644 --- a/lib/models/responses/charge_response.dart +++ b/lib/models/responses/charge_response.dart @@ -1,4 +1,3 @@ - import 'package:flutterwave_standard/core/transaction_status.dart'; class ChargeResponse { @@ -7,26 +6,26 @@ class ChargeResponse { String? transactionId; String? txRef; - ChargeResponse({this.status, this.success, this.transactionId, this.txRef}); + ChargeResponse( + {this.status, this.success, this.transactionId, this.txRef}); ChargeResponse.fromJson(Map json) { - status = json['status'] == null ? TransactionStatus.ERROR : json['status']; - success = json['success'] == null ? false : json['success'] ; + status = json['status'] ?? TransactionStatus.ERROR; + success = json['success'] ?? false; transactionId = json['transaction_id']; txRef = json['tx_ref']; } /// Converts this instance to json Map toJson() { - final Map data = new Map(); - data['status'] = this.status; - data['success'] = this.success; - data['transaction_id'] = this.transactionId; - data['tx_ref'] = this.txRef; + final Map data = Map(); + data['status'] = status; + data['success'] = success; + data['transaction_id'] = transactionId; + data['tx_ref'] = txRef; return data; } @override String toString() => toJson().toString(); } - diff --git a/lib/models/responses/standard_response.dart b/lib/models/responses/standard_response.dart index ab0cd3f..894b42a 100644 --- a/lib/models/responses/standard_response.dart +++ b/lib/models/responses/standard_response.dart @@ -6,17 +6,17 @@ class StandardResponse { StandardResponse({this.status, this.data, this.message}); StandardResponse.fromJson(Map json) { - this.status = json["status"]; - this.message = json["message"]; - this.data = StandardResponseData.fromJson(json["data"]); + status = json["status"]; + message = json["message"]; + data = StandardResponseData.fromJson(json["data"]); } /// Converts this instance to json Map toJson() { return { - "status": this.status, - "message": this.message, - "data": this.data?.toJson() + "status": status, + "message": message, + "data": data?.toJson() }; } } @@ -27,13 +27,11 @@ class StandardResponseData { StandardResponseData([this.link = ""]); StandardResponseData.fromJson(Map json) { - this.link = json["link"]; + link = json["link"]; } /// Converts this instance to json Map toJson() { - return { - "link": this.link - }; + return {"link": link}; } } diff --git a/lib/models/subaccount.dart b/lib/models/subaccount.dart index ea29fad..a14b1da 100644 --- a/lib/models/subaccount.dart +++ b/lib/models/subaccount.dart @@ -1,24 +1,22 @@ - class SubAccount { String id; int? transactionSplitRatio; String? transactionChargeType; double? transactionPercentage; - SubAccount({ - required this.id, - this.transactionSplitRatio, - this.transactionChargeType, - this.transactionPercentage - }); + SubAccount( + {required this.id, + this.transactionSplitRatio, + this.transactionChargeType, + this.transactionPercentage}); /// Converts this instance to json Map toJson() { return { - "id": this.id, - "transaction_split_ratio": this.transactionSplitRatio, - "transaction_charge_type": this.transactionChargeType, - "transaction_charge": this.transactionPercentage + "id": id, + "transaction_split_ratio": transactionSplitRatio, + "transaction_charge_type": transactionChargeType, + "transaction_charge": transactionPercentage }; } } diff --git a/lib/view/flutterwave_in_app_browser.dart b/lib/view/flutterwave_in_app_browser.dart index 82cb28f..86eee36 100644 --- a/lib/view/flutterwave_in_app_browser.dart +++ b/lib/view/flutterwave_in_app_browser.dart @@ -3,10 +3,9 @@ import 'dart:convert'; import 'package:flutter_inappwebview/flutter_inappwebview.dart'; import 'package:flutterwave_standard/core/TransactionCallBack.dart'; -import '../models/responses/charge_response.dart'; +import 'package:flutterwave_standard/models/responses/charge_response.dart'; class FlutterwaveInAppBrowser extends InAppBrowser { - final TransactionCallBack callBack; FlutterwaveInAppBrowser({required this.callBack}); @@ -63,8 +62,8 @@ class FlutterwaveInAppBrowser extends InAppBrowser { status: status, transactionId: "$id", txRef: txRef, - success: status?.contains("success") == true - ); + success: status?.toString().toLowerCase() == "success" || + status?.toString().toLowerCase() == "completed"); _closeTransactionScreen(chargeResponse); // callBack.onTransactionComplete(chargeResponse); // close(); @@ -78,8 +77,8 @@ class FlutterwaveInAppBrowser extends InAppBrowser { status: status, transactionId: id, txRef: txRef, - success: status?.contains("success") == true - ); + success: status?.toLowerCase() == "success" || + status?.toLowerCase() == "completed"); _closeTransactionScreen(chargeResponse); // callBack.onTransactionComplete(chargeResponse); // close(); @@ -89,4 +88,4 @@ class FlutterwaveInAppBrowser extends InAppBrowser { _chargeResponse = chargeResponse; close(); } -} \ No newline at end of file +} diff --git a/lib/view/flutterwave_style.dart b/lib/view/flutterwave_style.dart index 6b2a81c..28d31b9 100644 --- a/lib/view/flutterwave_style.dart +++ b/lib/view/flutterwave_style.dart @@ -1,98 +1,98 @@ -import 'package:flutter/material.dart'; +// import 'package:flutter/material.dart'; -@deprecated -/// No longer needed since the intermediate screen was removed. -/// Will be removed in further releases. -class FlutterwaveStyle { - final String? appBarText; - final Color? buttonColor; - final TextStyle? buttonTextStyle; - final Color? appBarColor; - final TextStyle? appBarTitleTextStyle; - final Icon? appBarIcon; - final Color? mainBackgroundColor; - final TextStyle? mainTextStyle; - final Color? dialogBackgroundColor; - final TextStyle? dialogCancelTextStyle; - final TextStyle? dialogContinueTextStyle; - final String? buttonText; +// @deprecated +// /// No longer needed since the intermediate screen was removed. +// /// Will be removed in further releases. +// class FlutterwaveStyle { +// final String? appBarText; +// final Color? buttonColor; +// final TextStyle? buttonTextStyle; +// final Color? appBarColor; +// final TextStyle? appBarTitleTextStyle; +// final Icon? appBarIcon; +// final Color? mainBackgroundColor; +// final TextStyle? mainTextStyle; +// final Color? dialogBackgroundColor; +// final TextStyle? dialogCancelTextStyle; +// final TextStyle? dialogContinueTextStyle; +// final String? buttonText; - FlutterwaveStyle( - {this.buttonColor, - this.buttonTextStyle, - this.appBarText, - this.appBarTitleTextStyle, - this.appBarColor, - this.appBarIcon, - this.mainBackgroundColor, - this.mainTextStyle, - this.dialogBackgroundColor, - this.dialogCancelTextStyle, - this.dialogContinueTextStyle, - this.buttonText}); +// FlutterwaveStyle( +// {this.buttonColor, +// this.buttonTextStyle, +// this.appBarText, +// this.appBarTitleTextStyle, +// this.appBarColor, +// this.appBarIcon, +// this.mainBackgroundColor, +// this.mainTextStyle, +// this.dialogBackgroundColor, +// this.dialogCancelTextStyle, +// this.dialogContinueTextStyle, +// this.buttonText}); - /// Returns app bar text text or default - String getAppBarText() { - return appBarText ?? "Flutterwave"; - } +// /// Returns app bar text text or default +// String getAppBarText() { +// return appBarText ?? "Flutterwave"; +// } - /// Returns button color or default - Color getButtonColor() { - return buttonColor ?? Color(0xFFfff1d0); - } +// /// Returns button color or default +// Color getButtonColor() { +// return buttonColor ?? Color(0xFFfff1d0); +// } - /// Returns button text style or default - TextStyle getButtonTextStyle() { - return buttonTextStyle ?? - TextStyle( - color: Colors.black, fontSize: 18, fontWeight: FontWeight.bold); - } +// /// Returns button text style or default +// TextStyle getButtonTextStyle() { +// return buttonTextStyle ?? +// TextStyle( +// color: Colors.black, fontSize: 18, fontWeight: FontWeight.bold); +// } - /// Returns app bar color or default - Color getAppBarColor() { - return appBarColor ?? Color(0xFFfff1d0); - } +// /// Returns app bar color or default +// Color getAppBarColor() { +// return appBarColor ?? Color(0xFFfff1d0); +// } - /// Returns app bar text style or default - TextStyle getAppBarTextStyle() { - return appBarTitleTextStyle ?? - TextStyle( - fontSize: 20, color: Colors.black, fontWeight: FontWeight.bold); - } +// /// Returns app bar text style or default +// TextStyle getAppBarTextStyle() { +// return appBarTitleTextStyle ?? +// TextStyle( +// fontSize: 20, color: Colors.black, fontWeight: FontWeight.bold); +// } - /// Returns app bar icon or default - Icon getAppBarIcon() { - return appBarIcon ?? Icon(Icons.arrow_back, color: Colors.black); - } +// /// Returns app bar icon or default +// Icon getAppBarIcon() { +// return appBarIcon ?? Icon(Icons.arrow_back, color: Colors.black); +// } - /// Returns background color or default - Color getMainBackgroundColor() { - return mainBackgroundColor ?? Colors.white; - } +// /// Returns background color or default +// Color getMainBackgroundColor() { +// return mainBackgroundColor ?? Colors.white; +// } - /// Returns dialog text style or default - TextStyle getMainTextStyle() { - return mainTextStyle ?? - TextStyle(color: Colors.black, fontSize: 18, letterSpacing: 1.2); - } +// /// Returns dialog text style or default +// TextStyle getMainTextStyle() { +// return mainTextStyle ?? +// TextStyle(color: Colors.black, fontSize: 18, letterSpacing: 1.2); +// } - /// Returns dialog background color or default - Color getDialogBackgroundColor() { - return dialogBackgroundColor ?? Colors.white; - } +// /// Returns dialog background color or default +// Color getDialogBackgroundColor() { +// return dialogBackgroundColor ?? Colors.white; +// } - /// Returns dialog's cancel text style or default - TextStyle getDialogCancelTextStyle() { - return dialogCancelTextStyle ?? TextStyle(fontSize: 18, color: Colors.red); - } +// /// Returns dialog's cancel text style or default +// TextStyle getDialogCancelTextStyle() { +// return dialogCancelTextStyle ?? TextStyle(fontSize: 18, color: Colors.red); +// } - /// Returns dialog's continue text style or default - TextStyle getDialogContinueTextStyle() { - return dialogContinueTextStyle ?? TextStyle(fontSize: 18, color: Colors.blue); - } +// /// Returns dialog's continue text style or default +// TextStyle getDialogContinueTextStyle() { +// return dialogContinueTextStyle ?? TextStyle(fontSize: 18, color: Colors.blue); +// } - /// Returns button text or default - String getButtonText() { - return buttonText ?? "Make Payment"; - } -} +// /// Returns button text or default +// String getButtonText() { +// return buttonText ?? "Make Payment"; +// } +// } diff --git a/lib/view/standard_webview.dart b/lib/view/standard_webview.dart index b950d61..d26eb0b 100644 --- a/lib/view/standard_webview.dart +++ b/lib/view/standard_webview.dart @@ -1,126 +1,126 @@ -import 'dart:convert'; -import 'dart:io'; - -import 'package:flutter/foundation.dart'; -import 'package:flutter/gestures.dart'; -import 'package:flutter/material.dart'; -import 'package:flutterwave_standard/models/responses/charge_response.dart'; -import 'package:webview_flutter/webview_flutter.dart'; - -import 'flutterwave_style.dart'; - -@deprecated -class StandardWebView extends StatefulWidget { - final String url; - final FlutterwaveStyle? style; - const StandardWebView({required this.url, this.style}); - - @override - State createState() => _StandardWebViewAppState(); -} - -class _StandardWebViewAppState extends State { - - @override - void initState() { - if (Platform.isAndroid) { - WebView.platform = SurfaceAndroidWebView(); - } - super.initState(); - } - - @override - Widget build(BuildContext context) { - - final Set> gestureRecognizers = { - Factory(() => EagerGestureRecognizer()) - }; - - UniqueKey _key = UniqueKey(); - - AppBar? appBar; - if (widget.style != null) { - appBar = AppBar( - title: Text( - widget.style!.getAppBarText(), - style: widget.style!.getAppBarTextStyle(), - ), - ); - } - - return SafeArea( - child: Scaffold( - key: _key, - appBar: appBar, - body: WebView( - initialUrl: widget.url, - javascriptMode: JavascriptMode.unrestricted, - gestureRecognizers: gestureRecognizers, - onPageStarted: (webUrl) { - final url = Uri.parse(webUrl); - _processUrl(url); - }, - ), - ) - ); - } - - _processUrl(Uri uri) { - if (_checkHasAppendedWithResponse(uri)) { - _finishWithAppendedResponse(uri); - } else { - _checkHasCompletedProcessing(uri); - } - } - - _checkHasCompletedProcessing(final Uri uri) { - final status = uri.queryParameters["status"]; - final txRef = uri.queryParameters["tx_ref"]; - final id = uri.queryParameters["transaction_id"]; - if (status != null && txRef != null) { - _finish(uri); - } - } - - bool _checkHasAppendedWithResponse(final Uri uri) { - final response = uri.queryParameters["response"]; - if (response != null) { - final json = jsonDecode(response); - final status = json["status"]; - final txRef = json["txRef"]; - return status != null && txRef != null; - } - return false; - } - - _finishWithAppendedResponse(Uri uri) { - final response = uri.queryParameters["response"]; - final decoded = Uri.decodeFull(response!); - final json = jsonDecode(decoded); - final status = json["status"]; - final txRef = json["txRef"]; - final id = json["id"]; - - final ChargeResponse chargeResponse = ChargeResponse( - status: status, - transactionId: "$id", - txRef: txRef, - success: status?.contains("success") == true - ); - Navigator.pop(context, chargeResponse); - } - - _finish(final Uri uri) { - final status = uri.queryParameters["status"]; - final txRef = uri.queryParameters["tx_ref"]; - final id = uri.queryParameters["transaction_id"]; - final ChargeResponse chargeResponse = ChargeResponse( - status: status, - transactionId: id, - txRef: txRef, - success: status?.contains("success") == true - ); - Navigator.pop(context, chargeResponse); - } -} \ No newline at end of file +// import 'dart:convert'; +// import 'dart:io'; + +// import 'package:flutter/foundation.dart'; +// import 'package:flutter/gestures.dart'; +// import 'package:flutter/material.dart'; +// import 'package:flutterwave_standard/models/responses/charge_response.dart'; +// import 'package:webview_flutter/webview_flutter.dart'; + +// import 'flutterwave_style.dart'; + +// @deprecated +// class StandardWebView extends StatefulWidget { +// final String url; +// final FlutterwaveStyle? style; +// const StandardWebView({required this.url, this.style}); + +// @override +// State createState() => _StandardWebViewAppState(); +// } + +// class _StandardWebViewAppState extends State { + +// @override +// void initState() { +// if (Platform.isAndroid) { +// WebView.platform = SurfaceAndroidWebView(); +// } +// super.initState(); +// } + +// @override +// Widget build(BuildContext context) { + +// final Set> gestureRecognizers = { +// Factory(() => EagerGestureRecognizer()) +// }; + +// UniqueKey _key = UniqueKey(); + +// AppBar? appBar; +// if (widget.style != null) { +// appBar = AppBar( +// title: Text( +// widget.style!.getAppBarText(), +// style: widget.style!.getAppBarTextStyle(), +// ), +// ); +// } + +// return SafeArea( +// child: Scaffold( +// key: _key, +// appBar: appBar, +// body: WebView( +// initialUrl: widget.url, +// javascriptMode: JavascriptMode.unrestricted, +// gestureRecognizers: gestureRecognizers, +// onPageStarted: (webUrl) { +// final url = Uri.parse(webUrl); +// _processUrl(url); +// }, +// ), +// ) +// ); +// } + +// _processUrl(Uri uri) { +// if (_checkHasAppendedWithResponse(uri)) { +// _finishWithAppendedResponse(uri); +// } else { +// _checkHasCompletedProcessing(uri); +// } +// } + +// _checkHasCompletedProcessing(final Uri uri) { +// final status = uri.queryParameters["status"]; +// final txRef = uri.queryParameters["tx_ref"]; +// final id = uri.queryParameters["transaction_id"]; +// if (status != null && txRef != null) { +// _finish(uri); +// } +// } + +// bool _checkHasAppendedWithResponse(final Uri uri) { +// final response = uri.queryParameters["response"]; +// if (response != null) { +// final json = jsonDecode(response); +// final status = json["status"]; +// final txRef = json["txRef"]; +// return status != null && txRef != null; +// } +// return false; +// } + +// _finishWithAppendedResponse(Uri uri) { +// final response = uri.queryParameters["response"]; +// final decoded = Uri.decodeFull(response!); +// final json = jsonDecode(decoded); +// final status = json["status"]; +// final txRef = json["txRef"]; +// final id = json["id"]; + +// final ChargeResponse chargeResponse = ChargeResponse( +// status: status, +// transactionId: "$id", +// txRef: txRef, +// success: status?.contains("success") == true +// ); +// Navigator.pop(context, chargeResponse); +// } + +// _finish(final Uri uri) { +// final status = uri.queryParameters["status"]; +// final txRef = uri.queryParameters["tx_ref"]; +// final id = uri.queryParameters["transaction_id"]; +// final ChargeResponse chargeResponse = ChargeResponse( +// status: status, +// transactionId: id, +// txRef: txRef, +// success: status?.contains("success") == true +// ); +// Navigator.pop(context, chargeResponse); +// } +// } \ No newline at end of file diff --git a/lib/view/standard_widget.dart b/lib/view/standard_widget.dart index c733656..30184c3 100644 --- a/lib/view/standard_widget.dart +++ b/lib/view/standard_widget.dart @@ -1,35 +1,35 @@ import 'package:flutter/material.dart'; -import 'package:flutter/widgets.dart'; import 'package:flutter_inappwebview/flutter_inappwebview.dart'; import 'package:flutterwave_standard/core/TransactionCallBack.dart'; import 'package:flutterwave_standard/models/responses/charge_response.dart'; -import 'flutterwave_in_app_browser.dart'; +import 'package:flutterwave_standard/view/flutterwave_in_app_browser.dart'; class StandardPaymentWidget extends StatefulWidget { - final String webUrl; - StandardPaymentWidget({ required this.webUrl }); + StandardPaymentWidget({required this.webUrl}); @override - _StandardPaymentWidgetAppState createState() => new _StandardPaymentWidgetAppState(); + State createState() => + new _StandardPaymentWidgetAppState(); } -class _StandardPaymentWidgetAppState extends State implements TransactionCallBack { - - var options = InAppBrowserClassOptions( - crossPlatform: InAppBrowserOptions(hideUrlBar: true), - inAppWebViewGroupOptions: InAppWebViewGroupOptions( - crossPlatform: InAppWebViewOptions(javaScriptEnabled: true), - ), +class _StandardPaymentWidgetAppState + extends State + implements TransactionCallBack { + InAppBrowserClassSettings settings = InAppBrowserClassSettings( + browserSettings: InAppBrowserSettings(hideUrlBar: true), + webViewSettings: InAppWebViewSettings(javaScriptEnabled: true), ); @override void initState() { super.initState(); final browser = FlutterwaveInAppBrowser(callBack: this); - browser.openUrlRequest(urlRequest: URLRequest(url: Uri.parse(widget.webUrl)), options: options); + browser.openUrlRequest( + urlRequest: URLRequest(url: WebUri(widget.webUrl)), + settings: settings); } @override @@ -44,5 +44,4 @@ class _StandardPaymentWidgetAppState extends State implem backgroundColor: Colors.white, ); } - -} \ No newline at end of file +} diff --git a/lib/view/view_utils.dart b/lib/view/view_utils.dart index 4d852fe..0254b85 100644 --- a/lib/view/view_utils.dart +++ b/lib/view/view_utils.dart @@ -2,138 +2,136 @@ import 'package:flutter/material.dart'; import 'package:fluttertoast/fluttertoast.dart'; class FlutterwaveViewUtils { - /// Displays a modal to confirm payment - static Future showConfirmPaymentModal( - final BuildContext context, - final String? currency, - final String amount, - final TextStyle textStyle, - final Color? dialogBackgroundColor, - final TextStyle modalCancelTextStyle, - final TextStyle modalContinueTextStyle, - final Function onContinuePressed, - ) async { + // static Future showConfirmPaymentModal( + // final BuildContext context, + // final String? currency, + // final String amount, + // final TextStyle textStyle, + // final Color? dialogBackgroundColor, + // final TextStyle modalCancelTextStyle, + // final TextStyle modalContinueTextStyle, + // final Function onContinuePressed, + // ) async { - return showDialog( - context: context, - barrierDismissible: false, - builder: (BuildContext buildContext) { - final transactionCurrency = currency ?? "NGN"; - return AlertDialog( - backgroundColor: dialogBackgroundColor, - content: Container( - margin: EdgeInsets.fromLTRB(20, 5, 20, 5), - child: Text( - "You will be charged a total of $transactionCurrency " - "$amount. Do you wish to continue? ", - textAlign: TextAlign.center, - style: textStyle, - // style: TextStyle( - // color: Colors.black, - // fontSize: 18, - // letterSpacing: 1.2, - // ), - ), - ), - actions: [ - TextButton( - onPressed: () => {Navigator.of(context).pop()}, - child: Text( - "CANCEL", - style: modalCancelTextStyle, - ), - ), - TextButton( - onPressed: () => onContinuePressed(), - child: Text( - "CONTINUE", - style: modalContinueTextStyle, - ), - ), - ], - ); - }, - ); - } + // return showDialog( + // context: context, + // barrierDismissible: false, + // builder: (BuildContext buildContext) { + // final transactionCurrency = currency ?? "NGN"; + // return AlertDialog( + // backgroundColor: dialogBackgroundColor, + // content: Container( + // margin: EdgeInsets.fromLTRB(20, 5, 20, 5), + // child: Text( + // "You will be charged a total of $transactionCurrency " + // "$amount. Do you wish to continue? ", + // textAlign: TextAlign.center, + // style: textStyle, + // // style: TextStyle( + // // color: Colors.black, + // // fontSize: 18, + // // letterSpacing: 1.2, + // // ), + // ), + // ), + // actions: [ + // TextButton( + // onPressed: () => {Navigator.of(context).pop()}, + // child: Text( + // "CANCEL", + // style: modalCancelTextStyle, + // ), + // ), + // TextButton( + // onPressed: () => onContinuePressed(), + // child: Text( + // "CONTINUE", + // style: modalContinueTextStyle, + // ), + // ), + // ], + // ); + // }, + // ); + // } - /// Shows progress dialog - Future showProgressDialog( - final String message, - final BuildContext context, - final bool dismissible, - final Widget? progressIndicator, - final TextStyle? textStyle, - final Color? dialogBackgroundColor) { - final Widget indicator = progressIndicator != null - ? progressIndicator - : CircularProgressIndicator(backgroundColor: Colors.orangeAccent); + // /// Shows progress dialog + // Future showProgressDialog( + // final String message, + // final BuildContext context, + // final bool dismissible, + // final Widget? progressIndicator, + // final TextStyle? textStyle, + // final Color? dialogBackgroundColor) { + // final Widget indicator = progressIndicator != null + // ? progressIndicator + // : CircularProgressIndicator(backgroundColor: Colors.orangeAccent); - final style = - textStyle != null ? textStyle : TextStyle(color: Colors.black); - - return showDialog( - context: context, - barrierDismissible: dismissible, - builder: (BuildContext context) { - return AlertDialog( - backgroundColor: dialogBackgroundColor, - content: Row( - mainAxisAlignment: MainAxisAlignment.spaceEvenly, - children: [ - indicator, - Text( - message, - textAlign: TextAlign.center, - style: style, - ) - ], - ), - ); - }, - ); - } + // final style = + // textStyle != null ? textStyle : TextStyle(color: Colors.black); - static void _goBackToPaymentScreen(final BuildContext context) { - Navigator.of(context).pop(); - } + // return showDialog( + // context: context, + // barrierDismissible: dismissible, + // builder: (BuildContext context) { + // return AlertDialog( + // backgroundColor: dialogBackgroundColor, + // content: Row( + // mainAxisAlignment: MainAxisAlignment.spaceEvenly, + // children: [ + // indicator, + // Text( + // message, + // textAlign: TextAlign.center, + // style: style, + // ) + // ], + // ), + // ); + // }, + // ); + // } - /// Cretaes a customised Appbar - static AppBar appBar( - final BuildContext context, - final String title, - final TextStyle appBarTitleTextStyle, - final Icon appBarIcon, - final Color appBarColor, - [final Function? handleBackPress]) { + // static void _goBackToPaymentScreen(final BuildContext context) { + // Navigator.of(context).pop(); + // } - return AppBar( - backgroundColor: appBarColor, - titleTextStyle: appBarTitleTextStyle, - leading: IconButton( - icon: appBarIcon, - onPressed: () => handleBackPress == null - ? _goBackToPaymentScreen(context) - : handleBackPress(), - ), - title: Text(title, style: appBarTitleTextStyle), - ); - } + // /// Cretaes a customised Appbar + // static AppBar appBar( + // final BuildContext context, + // final String title, + // final TextStyle appBarTitleTextStyle, + // final Icon appBarIcon, + // final Color appBarColor, + // [final Function? handleBackPress]) { - /// Displays a Snackbar - static showSnackBar(BuildContext context, String text) { - final snackBar = SnackBar(content: Text(text)); - ScaffoldMessenger.of(context).showSnackBar(snackBar); - } + // return AppBar( + // backgroundColor: appBarColor, + // titleTextStyle: appBarTitleTextStyle, + // leading: IconButton( + // icon: appBarIcon, + // onPressed: () => handleBackPress == null + // ? _goBackToPaymentScreen(context) + // : handleBackPress(), + // ), + // title: Text(title, style: appBarTitleTextStyle), + // ); + // } + // /// Displays a Snackbar + // static showSnackBar(BuildContext context, String text) { + // final snackBar = SnackBar(content: Text(text)); + // ScaffoldMessenger.of(context).showSnackBar(snackBar); + // } /// Displays a toast notification static void showToast(BuildContext context, String text) { Fluttertoast.showToast( - msg: text, - timeInSecForIosWeb: 1, - backgroundColor: Color(0xAA383737), - textColor: Colors.white, + msg: text, + timeInSecForIosWeb: 1, + backgroundColor: Color(0xAA383737), + textColor: Colors.white, ); } } diff --git a/pubspec.lock b/pubspec.lock index 290e073..033ce84 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -5,140 +5,157 @@ packages: dependency: transitive description: name: _fe_analyzer_shared - url: "https://pub.dartlang.org" + sha256: "16e298750b6d0af7ce8a3ba7c18c69c3785d11b15ec83f6dcd0ad2a0009b3cab" + url: "https://pub.dev" source: hosted - version: "25.0.0" + version: "76.0.0" + _macros: + dependency: transitive + description: dart + source: sdk + version: "0.3.3" analyzer: dependency: transitive description: name: analyzer - url: "https://pub.dartlang.org" + sha256: "1f14db053a8c23e260789e9b0980fa27f2680dd640932cae5e1137cce0e46e1e" + url: "https://pub.dev" source: hosted - version: "2.2.0" + version: "6.11.0" args: dependency: transitive description: name: args - url: "https://pub.dartlang.org" + sha256: "3d82ff8620ec576fd38f6cec0df45a7c088b8704eb1c63d4c336392e5efca6ca" + url: "https://pub.dev" source: hosted version: "2.2.0" async: dependency: transitive description: name: async - url: "https://pub.dartlang.org" + sha256: d2872f9c19731c2e5f10444b14686eb7cc85c76274bd6c16e1816bff9a3bab63 + url: "https://pub.dev" source: hosted - version: "2.8.2" + version: "2.12.0" boolean_selector: dependency: transitive description: name: boolean_selector - url: "https://pub.dartlang.org" + sha256: "8aab1771e1243a5063b8b0ff68042d67334e3feab9e95b9490f9a6ebf73b42ea" + url: "https://pub.dev" source: hosted - version: "2.1.0" + version: "2.1.2" build: dependency: transitive description: name: build - url: "https://pub.dartlang.org" + sha256: cef23f1eda9b57566c81e2133d196f8e3df48f244b317368d65c5943d91148f0 + url: "https://pub.dev" source: hosted - version: "2.1.0" + version: "2.4.2" built_collection: dependency: transitive description: name: built_collection - url: "https://pub.dartlang.org" + sha256: "376e3dd27b51ea877c28d525560790aee2e6fbb5f20e2f85d5081027d94e2100" + url: "https://pub.dev" source: hosted version: "5.1.1" built_value: dependency: transitive description: name: built_value - url: "https://pub.dartlang.org" + sha256: ce70206f4116029cec77802dd5b5987e32c30ab491af6e3e49410b7457ebfc64 + url: "https://pub.dev" source: hosted version: "8.1.2" characters: dependency: transitive description: name: characters - url: "https://pub.dartlang.org" + sha256: f71061c654a3380576a52b451dd5532377954cf9dbd272a78fc8479606670803 + url: "https://pub.dev" source: hosted - version: "1.2.0" + version: "1.4.0" charcode: dependency: transitive description: name: charcode - url: "https://pub.dartlang.org" + sha256: fb98c0f6d12c920a02ee2d998da788bca066ca5f148492b7085ee23372b12306 + url: "https://pub.dev" source: hosted version: "1.3.1" - cli_util: - dependency: transitive - description: - name: cli_util - url: "https://pub.dartlang.org" - source: hosted - version: "0.3.3" clock: dependency: transitive description: name: clock - url: "https://pub.dartlang.org" + sha256: fddb70d9b5277016c77a80201021d40a2247104d9f4aa7bab7157b7e3f05b84b + url: "https://pub.dev" source: hosted - version: "1.1.0" + version: "1.1.2" code_builder: dependency: transitive description: name: code_builder - url: "https://pub.dartlang.org" + sha256: "0ec10bf4a89e4c613960bf1e8b42c64127021740fb21640c29c909826a5eea3e" + url: "https://pub.dev" source: hosted - version: "4.1.0" + version: "4.10.1" collection: dependency: transitive description: name: collection - url: "https://pub.dartlang.org" + sha256: "2f5709ae4d3d59dd8f7cd309b4e023046b57d8a6c82130785d2b0e5868084e76" + url: "https://pub.dev" source: hosted - version: "1.16.0" + version: "1.19.1" convert: dependency: transitive description: name: convert - url: "https://pub.dartlang.org" + sha256: f08428ad63615f96a27e34221c65e1a451439b5f26030f78d790f461c686d65d + url: "https://pub.dev" source: hosted version: "3.0.1" crypto: dependency: transitive description: name: crypto - url: "https://pub.dartlang.org" + sha256: cf75650c66c0316274e21d7c43d3dea246273af5955bd94e8184837cd577575c + url: "https://pub.dev" source: hosted version: "3.0.1" dart_style: dependency: transitive description: name: dart_style - url: "https://pub.dartlang.org" + sha256: "7306ab8a2359a48d22310ad823521d723acfed60ee1f7e37388e8986853b6820" + url: "https://pub.dev" source: hosted - version: "2.1.0" + version: "2.3.8" fake_async: dependency: transitive description: name: fake_async - url: "https://pub.dartlang.org" + sha256: "6a95e56b2449df2273fd8c45a662d6947ce1ebb7aafe80e550a3f68297f3cacc" + url: "https://pub.dev" source: hosted - version: "1.3.0" + version: "1.3.2" file: dependency: transitive description: name: file - url: "https://pub.dartlang.org" + sha256: b69516f2c26a5bcac4eee2e32512e1a5205ab312b3536c1c1227b2b942b5f9ad + url: "https://pub.dev" source: hosted version: "6.1.2" fixnum: dependency: transitive description: name: fixnum - url: "https://pub.dartlang.org" + sha256: "6a2ef17156f4dc49684f9d99aaf4a93aba8ac49f5eac861755f5730ddf6e2e4e" + url: "https://pub.dev" source: hosted version: "1.0.0" flutter: @@ -150,9 +167,66 @@ packages: dependency: "direct main" description: name: flutter_inappwebview - url: "https://pub.dartlang.org" + sha256: "80092d13d3e29b6227e25b67973c67c7210bd5e35c4b747ca908e31eb71a46d5" + url: "https://pub.dev" + source: hosted + version: "6.1.5" + flutter_inappwebview_android: + dependency: transitive + description: + name: flutter_inappwebview_android + sha256: "62557c15a5c2db5d195cb3892aab74fcaec266d7b86d59a6f0027abd672cddba" + url: "https://pub.dev" + source: hosted + version: "1.1.3" + flutter_inappwebview_internal_annotations: + dependency: transitive + description: + name: flutter_inappwebview_internal_annotations + sha256: "787171d43f8af67864740b6f04166c13190aa74a1468a1f1f1e9ee5b90c359cd" + url: "https://pub.dev" source: hosted - version: "5.7.2+3" + version: "1.2.0" + flutter_inappwebview_ios: + dependency: transitive + description: + name: flutter_inappwebview_ios + sha256: "5818cf9b26cf0cbb0f62ff50772217d41ea8d3d9cc00279c45f8aabaa1b4025d" + url: "https://pub.dev" + source: hosted + version: "1.1.2" + flutter_inappwebview_macos: + dependency: transitive + description: + name: flutter_inappwebview_macos + sha256: c1fbb86af1a3738e3541364d7d1866315ffb0468a1a77e34198c9be571287da1 + url: "https://pub.dev" + source: hosted + version: "1.1.2" + flutter_inappwebview_platform_interface: + dependency: transitive + description: + name: flutter_inappwebview_platform_interface + sha256: cf5323e194096b6ede7a1ca808c3e0a078e4b33cc3f6338977d75b4024ba2500 + url: "https://pub.dev" + source: hosted + version: "1.3.0+1" + flutter_inappwebview_web: + dependency: transitive + description: + name: flutter_inappwebview_web + sha256: "55f89c83b0a0d3b7893306b3bb545ba4770a4df018204917148ebb42dc14a598" + url: "https://pub.dev" + source: hosted + version: "1.1.2" + flutter_inappwebview_windows: + dependency: transitive + description: + name: flutter_inappwebview_windows + sha256: "8b4d3a46078a2cdc636c4a3d10d10f2a16882f6be607962dbfff8874d1642055" + url: "https://pub.dev" + source: hosted + version: "0.6.0" flutter_test: dependency: "direct dev" description: flutter @@ -167,224 +241,255 @@ packages: dependency: "direct main" description: name: fluttertoast - url: "https://pub.dartlang.org" + sha256: "25e51620424d92d3db3832464774a6143b5053f15e382d8ffbfd40b6e795dcf1" + url: "https://pub.dev" source: hosted - version: "8.0.8" + version: "8.2.12" glob: dependency: transitive description: name: glob - url: "https://pub.dartlang.org" + sha256: dda85ce2aefce16f7e75586acbcb1e8320bf176f69fd94082e31945d6de67f3e + url: "https://pub.dev" source: hosted version: "2.0.1" http: dependency: "direct main" description: name: http - url: "https://pub.dartlang.org" + sha256: fe7ab022b76f3034adc518fb6ea04a82387620e19977665ea18d30a1cf43442f + url: "https://pub.dev" source: hosted - version: "0.13.3" + version: "1.3.0" http_parser: dependency: transitive description: name: http_parser - url: "https://pub.dartlang.org" + sha256: e362d639ba3bc07d5a71faebb98cde68c05bfbcfbbb444b60b6f60bb67719185 + url: "https://pub.dev" source: hosted version: "4.0.0" - js: + leak_tracker: dependency: transitive description: - name: js - url: "https://pub.dartlang.org" + name: leak_tracker + sha256: c35baad643ba394b40aac41080300150a4f08fd0fd6a10378f8f7c6bc161acec + url: "https://pub.dev" source: hosted - version: "0.6.4" + version: "10.0.8" + leak_tracker_flutter_testing: + dependency: transitive + description: + name: leak_tracker_flutter_testing + sha256: f8b613e7e6a13ec79cfdc0e97638fddb3ab848452eff057653abd3edba760573 + url: "https://pub.dev" + source: hosted + version: "3.0.9" + leak_tracker_testing: + dependency: transitive + description: + name: leak_tracker_testing + sha256: "6ba465d5d76e67ddf503e1161d1f4a6bc42306f9d66ca1e8f079a47290fb06d3" + url: "https://pub.dev" + source: hosted + version: "3.0.1" logging: dependency: transitive description: name: logging - url: "https://pub.dartlang.org" + sha256: "0520a4826042a8a5d09ddd4755623a50d37ee536d79a70452aff8c8ad7bb6c27" + url: "https://pub.dev" source: hosted version: "1.0.1" + macros: + dependency: transitive + description: + name: macros + sha256: "1d9e801cd66f7ea3663c45fc708450db1fa57f988142c64289142c9b7ee80656" + url: "https://pub.dev" + source: hosted + version: "0.1.3-main.0" matcher: dependency: transitive description: name: matcher - url: "https://pub.dartlang.org" + sha256: dc58c723c3c24bf8d3e2d3ad3f2f9d7bd9cf43ec6feaa64181775e60190153f2 + url: "https://pub.dev" source: hosted - version: "0.12.11" + version: "0.12.17" material_color_utilities: dependency: transitive description: name: material_color_utilities - url: "https://pub.dartlang.org" + sha256: f7142bb1154231d7ea5f96bc7bde4bda2a0945d2806bb11670e30b850d56bdec + url: "https://pub.dev" source: hosted - version: "0.1.4" + version: "0.11.1" meta: dependency: transitive description: name: meta - url: "https://pub.dartlang.org" + sha256: e3641ec5d63ebf0d9b41bd43201a66e3fc79a65db5f61fc181f04cd27aab950c + url: "https://pub.dev" source: hosted - version: "1.7.0" + version: "1.16.0" mockito: dependency: "direct dev" description: name: mockito - url: "https://pub.dartlang.org" + sha256: f99d8d072e249f719a5531735d146d8cf04c580d93920b04de75bef6dfb2daf6 + url: "https://pub.dev" source: hosted - version: "5.0.15" - modal_bottom_sheet: - dependency: "direct main" - description: - name: modal_bottom_sheet - url: "https://pub.dartlang.org" - source: hosted - version: "2.1.0" + version: "5.4.5" package_config: dependency: transitive description: name: package_config - url: "https://pub.dartlang.org" + sha256: f096c55ebb7deb7e384101542bfba8c52696c1b56fca2eb62827989ef2353bbc + url: "https://pub.dev" source: hosted - version: "2.0.0" + version: "2.2.0" path: dependency: transitive description: name: path - url: "https://pub.dartlang.org" + sha256: "75cca69d1490965be98c73ceaea117e8a04dd21217b37b292c9ddbec0d955bc5" + url: "https://pub.dev" source: hosted - version: "1.8.1" + version: "1.9.1" pedantic: dependency: transitive description: name: pedantic - url: "https://pub.dartlang.org" + sha256: "67fc27ed9639506c856c840ccce7594d0bdcd91bc8d53d6e52359449a1d50602" + url: "https://pub.dev" source: hosted version: "1.11.1" plugin_platform_interface: dependency: transitive description: name: plugin_platform_interface - url: "https://pub.dartlang.org" + sha256: "4820fbfdb9478b1ebae27888254d445073732dae3d6ea81f0b7e06d5dedc3f02" + url: "https://pub.dev" source: hosted - version: "2.1.2" + version: "2.1.8" pub_semver: dependency: transitive description: name: pub_semver - url: "https://pub.dartlang.org" + sha256: "5bfcf68ca79ef689f8990d1160781b4bad40a3bd5e5218ad4076ddb7f4081585" + url: "https://pub.dev" source: hosted - version: "2.0.0" + version: "2.2.0" sky_engine: dependency: transitive description: flutter source: sdk - version: "0.0.99" + version: "0.0.0" source_gen: dependency: transitive description: name: source_gen - url: "https://pub.dartlang.org" + sha256: "35c8150ece9e8c8d263337a265153c3329667640850b9304861faea59fc98f6b" + url: "https://pub.dev" source: hosted - version: "1.0.3" + version: "2.0.0" source_span: dependency: transitive description: name: source_span - url: "https://pub.dartlang.org" + sha256: "254ee5351d6cb365c859e20ee823c3bb479bf4a293c22d17a9f1bf144ce86f7c" + url: "https://pub.dev" source: hosted - version: "1.8.2" + version: "1.10.1" stack_trace: dependency: transitive description: name: stack_trace - url: "https://pub.dartlang.org" + sha256: "8b27215b45d22309b5cddda1aa2b19bdfec9df0e765f2de506401c071d38d1b1" + url: "https://pub.dev" source: hosted - version: "1.10.0" + version: "1.12.1" stream_channel: dependency: transitive description: name: stream_channel - url: "https://pub.dartlang.org" + sha256: "969e04c80b8bcdf826f8f16579c7b14d780458bd97f56d107d3950fdbeef059d" + url: "https://pub.dev" source: hosted - version: "2.1.0" + version: "2.1.4" string_scanner: dependency: transitive description: name: string_scanner - url: "https://pub.dartlang.org" + sha256: "921cd31725b72fe181906c6a94d987c78e3b98c2e205b397ea399d4054872b43" + url: "https://pub.dev" source: hosted - version: "1.1.0" + version: "1.4.1" term_glyph: dependency: transitive description: name: term_glyph - url: "https://pub.dartlang.org" + sha256: "7f554798625ea768a7518313e58f83891c7f5024f88e46e7182a4558850a4b8e" + url: "https://pub.dev" source: hosted - version: "1.2.0" + version: "1.2.2" test_api: dependency: transitive description: name: test_api - url: "https://pub.dartlang.org" + sha256: fb31f383e2ee25fbbfe06b40fe21e1e458d14080e3c67e7ba0acfde4df4e0bbd + url: "https://pub.dev" source: hosted - version: "0.4.9" + version: "0.7.4" typed_data: dependency: transitive description: name: typed_data - url: "https://pub.dartlang.org" + sha256: "53bdf7e979cfbf3e28987552fd72f637e63f3c8724c9e56d9246942dc2fa36ee" + url: "https://pub.dev" source: hosted version: "1.3.0" vector_math: dependency: transitive description: name: vector_math - url: "https://pub.dartlang.org" + sha256: "80b3257d1492ce4d091729e3a67a60407d227c27241d6927be0130c98e741803" + url: "https://pub.dev" source: hosted - version: "2.1.2" - watcher: + version: "2.1.4" + vm_service: dependency: transitive description: - name: watcher - url: "https://pub.dartlang.org" + name: vm_service + sha256: "0968250880a6c5fe7edc067ed0a13d4bae1577fe2771dcf3010d52c4a9d3ca14" + url: "https://pub.dev" source: hosted - version: "1.0.0" - webview_flutter: - dependency: "direct main" - description: - name: webview_flutter - url: "https://pub.dartlang.org" - source: hosted - version: "3.0.4" - webview_flutter_android: - dependency: transitive - description: - name: webview_flutter_android - url: "https://pub.dartlang.org" - source: hosted - version: "2.8.14" - webview_flutter_platform_interface: + version: "14.3.1" + watcher: dependency: transitive description: - name: webview_flutter_platform_interface - url: "https://pub.dartlang.org" + name: watcher + sha256: "69da27e49efa56a15f8afe8f4438c4ec02eff0a117df1b22ea4aad194fe1c104" + url: "https://pub.dev" source: hosted - version: "1.9.1" - webview_flutter_wkwebview: + version: "1.1.1" + web: dependency: transitive description: - name: webview_flutter_wkwebview - url: "https://pub.dartlang.org" + name: web + sha256: "868d88a33d8a87b18ffc05f9f030ba328ffefba92d6c127917a2ba740f9cfe4a" + url: "https://pub.dev" source: hosted - version: "2.8.1" + version: "1.1.1" yaml: dependency: transitive description: name: yaml - url: "https://pub.dartlang.org" + sha256: "3cee79b1715110341012d27756d9bae38e650588acd38d3f3c610822e1337ace" + url: "https://pub.dev" source: hosted version: "3.1.0" sdks: - dart: ">=2.17.0 <3.0.0" - flutter: ">=3.0.0" + dart: ">=3.7.0-0 <4.0.0" + flutter: ">=3.24.0" diff --git a/pubspec.yaml b/pubspec.yaml index 1d4718d..02fec2c 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -3,18 +3,16 @@ description: Flutterwave's official library that wraps the standard implementati version: 1.0.7 homepage: https://github.com/Flutterwave/flutter_standard environment: - sdk: ">=2.12.0 <3.0.0" + sdk: ">=2.17.0 <4.0.0" flutter: ">=1.17.0" dependencies: flutter: sdk: flutter - http: ^0.13.0 - fluttertoast: ^8.0.8 - webview_flutter: ^3.0.4 - modal_bottom_sheet: ^2.1.0 - flutter_inappwebview: ^5.7.2+3 + http: ^1.3.0 + fluttertoast: ^8.2.12 + flutter_inappwebview: ^6.1.5 dev_dependencies: flutter_test: diff --git a/test/flutterwave_style_test.dart b/test/flutterwave_style_test.dart index 9a9fe45..5906019 100644 --- a/test/flutterwave_style_test.dart +++ b/test/flutterwave_style_test.dart @@ -1,61 +1,60 @@ - -import 'package:flutter/material.dart'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:flutterwave_standard/flutterwave.dart'; - -main() { - group("Flutterwave Style should", () { - - final buttonTextStyle = TextStyle( - color: Colors.deepOrangeAccent, - fontSize: 16, - ); - - var style = FlutterwaveStyle( - appBarText: "My Standard Blue", - buttonColor: Color(0xffd0ebff), - buttonTextStyle: buttonTextStyle, - appBarColor: Color(0xff8fa33b), - dialogCancelTextStyle: TextStyle( - color: Colors.brown, - fontSize: 18, - ), - dialogContinueTextStyle: TextStyle( - color: Colors.purpleAccent, - fontSize: 18, - ), - mainBackgroundColor: Colors.indigo, - mainTextStyle: TextStyle( - color: Colors.indigo, - fontSize: 19, - letterSpacing: 2 - ), - dialogBackgroundColor: Colors.greenAccent, - appBarIcon: Icon(Icons.message, color: Colors.purple), - buttonText: "Pay", - appBarTitleTextStyle: TextStyle( - color: Colors.purpleAccent, - fontSize: 18, - ), - ); - - test("return correct style properties", () { - expect(Colors.greenAccent, style.getDialogBackgroundColor()); - expect("My Standard Blue", style.getAppBarText()); - expect(Colors.indigo, style.getMainBackgroundColor()); - expect("Pay", style.getButtonText()); - expect(buttonTextStyle, style.getButtonTextStyle()); - }); - - test("return default style properties if style properties are not set", () { - style = FlutterwaveStyle(); - expect(Colors.white, style.getDialogBackgroundColor()); - expect("Flutterwave", style.getAppBarText()); - expect(Colors.white, style.getMainBackgroundColor()); - expect("Make Payment", style.getButtonText()); - expect(Color(0xFFfff1d0), style.getAppBarColor()); - }); - - }); - -} +// import 'package:flutter/material.dart'; +// import 'package:flutter_test/flutter_test.dart'; +// import 'package:flutterwave_standard/flutterwave.dart'; + +// main() { +// group("Flutterwave Style should", () { + +// final buttonTextStyle = TextStyle( +// color: Colors.deepOrangeAccent, +// fontSize: 16, +// ); + +// var style = FlutterwaveStyle( +// appBarText: "My Standard Blue", +// buttonColor: Color(0xffd0ebff), +// buttonTextStyle: buttonTextStyle, +// appBarColor: Color(0xff8fa33b), +// dialogCancelTextStyle: TextStyle( +// color: Colors.brown, +// fontSize: 18, +// ), +// dialogContinueTextStyle: TextStyle( +// color: Colors.purpleAccent, +// fontSize: 18, +// ), +// mainBackgroundColor: Colors.indigo, +// mainTextStyle: TextStyle( +// color: Colors.indigo, +// fontSize: 19, +// letterSpacing: 2 +// ), +// dialogBackgroundColor: Colors.greenAccent, +// appBarIcon: Icon(Icons.message, color: Colors.purple), +// buttonText: "Pay", +// appBarTitleTextStyle: TextStyle( +// color: Colors.purpleAccent, +// fontSize: 18, +// ), +// ); + +// test("return correct style properties", () { +// expect(Colors.greenAccent, style.getDialogBackgroundColor()); +// expect("My Standard Blue", style.getAppBarText()); +// expect(Colors.indigo, style.getMainBackgroundColor()); +// expect("Pay", style.getButtonText()); +// expect(buttonTextStyle, style.getButtonTextStyle()); +// }); + +// test("return default style properties if style properties are not set", () { +// style = FlutterwaveStyle(); +// expect(Colors.white, style.getDialogBackgroundColor()); +// expect("Flutterwave", style.getAppBarText()); +// expect(Colors.white, style.getMainBackgroundColor()); +// expect("Make Payment", style.getButtonText()); +// expect(Color(0xFFfff1d0), style.getAppBarColor()); +// }); + +// }); + +// }