diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..675427c --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,44 @@ +name: CI + +on: + push: + pull_request: + +permissions: + contents: read + +jobs: + test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7.0.1 + - uses: subosito/flutter-action@v2.23.0 + with: + flutter-version: '3.50.0' + channel: stable + cache: true + - run: flutter pub get + - run: flutter analyze --no-pub + - run: ./scripts/runTests.sh + - name: Check formatting + run: dart format --output=none --set-exit-if-changed lib test example/lib example/test + - name: Build web example + working-directory: example + run: flutter build web --release --no-pub + + android: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7.0.1 + - uses: actions/setup-java@v6.3.0 + with: + distribution: temurin + java-version: '17' + - uses: subosito/flutter-action@v2.23.0 + with: + flutter-version: '3.50.0' + channel: stable + cache: true + - name: Build Android example + working-directory: example + run: flutter build apk --debug diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 149588e..0000000 --- a/.travis.yml +++ /dev/null @@ -1,155 +0,0 @@ -jobs: - include: - - - &unit-test-stage - stage: Unit Testing - language: generic - os: linux - env: channel=stable - before_install: # runs on linux only - - sudo apt-get install -y --no-install-recommends lib32stdc++6 libstdc++6 > /dev/null - before_script: - # install pre-compiled flutter - - FLUTTER_VERSION=1.2.1-${channel} - - | - if [ $TRAVIS_OS_NAME == "osx" ]; then - wget --quiet --output-document=flutter.zip https://storage.googleapis.com/flutter_infra/releases/${channel}/macos/flutter_macos_v${FLUTTER_VERSION}.zip && unzip -qq flutter.zip > /dev/null && rm flutter.zip - else - wget --quiet --output-document=flutter.tar.xz https://storage.googleapis.com/flutter_infra/releases/${channel}/linux/flutter_linux_v${FLUTTER_VERSION}.tar.xz && tar xf flutter.tar.xz > /dev/null && rm flutter.tar.xz - fi - - export PATH="$PATH":"$HOME/.pub-cache/bin" - - export PATH=$PWD/flutter/bin:$PWD/flutter/bin/cache/dart-sdk/bin:$PATH - - flutter doctor -v - - | - [[ $TRAVIS_OS_NAME != "linux" && channel != "stable" ]] || pub global activate coverage - script: ./scripts/runTests.sh - after_success: bash <(curl -s https://codecov.io/bash) -f lcov.info - - <<: *unit-test-stage - os: osx - before_install: - after_success: - env: channel=stable - - <<: *unit-test-stage - env: channel=beta - after_success: - - <<: *unit-test-stage - os: osx - env: channel=beta - before_install: - after_success: - env: channel=beta - - <<: *unit-test-stage - env: channel=dev - after_success: - - <<: *unit-test-stage - os: osx - env: channel=dev - before_install: - after_success: - - <<: *unit-test-stage - env: branch=master - before_script: - - git clone https://github.com/flutter/flutter.git -b $branch - - export PATH="$PATH":"$HOME/.pub-cache/bin" - - export PATH=$PWD/flutter/bin:$PWD/flutter/bin/cache/dart-sdk/bin:$PATH - - flutter precache - - flutter doctor -v - - pub global activate coverage - after_success: - - <<: *unit-test-stage - os: osx - env: branch=master - before_install: - before_script: - - git clone https://github.com/flutter/flutter.git -b $branch - - export PATH="$PATH":"$HOME/.pub-cache/bin" - - export PATH=$PWD/flutter/bin:$PWD/flutter/bin/cache/dart-sdk/bin:$PATH - - flutter precache - - flutter doctor -v - - pub global activate coverage - after_success: - - - &integration-test-stage - stage: Integration Testing - sudo: true - dist: trusty - language: generic - os: linux - env: integration-test-linux - # Run integration tests on android - before_install: &before_install_linux - # Install the Android SDK Dependency. - - export ANDROID_HOME=/opt/android-sdk-linux - - cd /opt - - wget -q https://dl.google.com/android/repository/sdk-tools-linux-4333796.zip -O android-sdk-tools.zip - - unzip -q android-sdk-tools.zip -d ${ANDROID_HOME} - - rm android-sdk-tools.zip - - cd - - - PATH=${PATH}:${ANDROID_HOME}/tools:${ANDROID_HOME}/tools/bin:${ANDROID_HOME}/platform-tools - # Silence warning. - - mkdir -p ~/.android - - touch ~/.android/repositories.cfg - # Accept licenses before installing components, no need to echo y for each component - - yes | sdkmanager --licenses - # Platform tools - - sdkmanager "emulator" "tools" "platform-tools" > /dev/null - - sdkmanager --list | head -15 - # install older packages (for emulator) - - sdkmanager "build-tools;25.0.2" "platforms;android-25" > /dev/null - # Create and start emulator. - - EMULATOR_API_LEVEL=22 - - ANDROID_ABI="default;armeabi-v7a" - - sdkmanager "system-images;android-$EMULATOR_API_LEVEL;$ANDROID_ABI" > /dev/null - - sdkmanager --list | head -15 - - echo no | avdmanager create avd --force -n test -k "system-images;android-$EMULATOR_API_LEVEL;$ANDROID_ABI" - - $ANDROID_HOME/emulator/emulator -avd test -no-audio -no-window -gpu swiftshader & - # install pre-compiled flutter - - sudo apt-get install -y --no-install-recommends lib32stdc++6 libstdc++6 > /dev/null - - sdkmanager "platforms;android-28" "build-tools;28.0.3" > /dev/null # required by flutter - - channel=stable - - FLUTTER_VERSION=1.2.1-${channel} - - wget --quiet --output-document=flutter.tar.xz https://storage.googleapis.com/flutter_infra/releases/${channel}/linux/flutter_linux_v${FLUTTER_VERSION}.tar.xz && tar xf flutter.tar.xz > /dev/null && rm flutter.tar.xz - - export PATH="$PATH":"$HOME/.pub-cache/bin" - - export PATH=$PWD/flutter/bin:$PWD/flutter/bin/cache/dart-sdk/bin:$PATH - - flutter doctor -v - # Wait for emulator to finish startup. - - ./scripts/android-wait-for-emulator.sh - - adb shell input keyevent 82 - - flutter devices - script: travis_retry ./scripts/ci.sh ./example - - <<: *integration-test-stage - os: osx - # use oldest flutter supported version of xcode - osx_image: xcode8.0 - env: integration-test-ios - # Run integration tests on ios - before_install: &before_install_osx - - open /Applications/Xcode.app/Contents/Developer/Applications/Simulator.app - # skip homebrew update - - export HOMEBREW_NO_AUTO_UPDATE=1 -# - brew update - - brew install libimobiledevice - - brew install ideviceinstaller - - brew install ios-deploy - - brew install cocoapods || echo 'ignore exit(1)' - - brew link --overwrite cocoapods - # install pre-compiled flutter - - channel=stable - - FLUTTER_VERSION=1.2.1-${channel} - - wget --quiet --output-document=flutter.zip https://storage.googleapis.com/flutter_infra/releases/${channel}/macos/flutter_macos_v${FLUTTER_VERSION}.zip && unzip -qq flutter.zip > /dev/null && rm flutter.zip - - export PATH="$PATH":"$HOME/.pub-cache/bin" - - export PATH=$PWD/flutter/bin:$PWD/flutter/bin/cache/dart-sdk/bin:$PATH - - flutter doctor -v - - flutter devices - script: travis_retry ./scripts/ci.sh ./example - - - stage: Ready to deploy - os: osx - language: generic - env: not implemented 🤓 - script: echo "Deploying to store ..." - - - allow_failures: - - env: channel=dev - - env: branch=master diff --git a/CHANGELOG.md b/CHANGELOG.md index fec90dc..eae3b08 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,4 +1,33 @@ -## [Unreleased] +## [0.6.0] + +* **Breaking:** require Flutter 3.50+ and Dart `^3.14.0`. + Apps on older Flutter versions can continue using 0.5.x. +* **Breaking:** the default spinner now uses `material_ui` and no longer reads + themes from `package:flutter/material.dart`. To retain legacy spinner styling, + pass your own `progressIndicator` or + [migrate your Material theme](https://docs.flutter.dev/release/breaking-changes/material-ui-and-cupertino-ui). + `material_ui` is installed transitively; apps only need to declare it directly + if they import it. + +* Fix stale future completions hiding newer loading operations or overriding + manually controlled visibility. +* Fix switching from future-controlled loading to `isLoading: true` after the + future has completed. +* Handle future errors without creating unhandled errors on an ignored completion + future, and ignore callbacks after disposal. The original future's result is + preserved for callers. +* Preserve both constructors, default colours and the 300 ms fade. + Replace deprecated `withOpacity` usage with the equivalent constant colour. +* Expand widget coverage for animation, interaction, customisation, future + replacement, errors, disposal and switching visibility controls. +* Update example lint tooling, remove unused Cupertino icons, refresh lockfiles, + add login tests, prevent duplicate sign-ins and dispose the example's + controllers safely. +* Replace obsolete Travis CI with GitHub Actions using Flutter 3.50 for tests + and web/Android example builds. Update the Android example to + AGP 9.3.1, Gradle 9.5 and built-in Kotlin with Java 17. +* Simplify the README and document future ownership, migration requirements and + keyboard/accessibility interaction limitations. ## [0.5.0] * New: `LoadingOverlay.withFuture` constructor to display the overlay until a diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..622ec58 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,18 @@ +# Contributing + +Use Flutter 3.50 / Dart 3.14 to match CI. Android builds also require JDK 17 +or newer; see the [example instructions](example/README.md). + +Run checks from the repository root: + +```sh +flutter pub get +flutter analyze +./scripts/runTests.sh +dart format --output=none --set-exit-if-changed lib test example/lib example/test +``` + +CI runs these checks and builds the web and Android examples on Flutter 3.50. + +Include regression tests for behavior changes and describe the change in +[CHANGELOG.md](CHANGELOG.md). diff --git a/README.md b/README.md index c936546..a5555ba 100644 --- a/README.md +++ b/README.md @@ -1,98 +1,85 @@ # loading_overlay -A simple widget wrapper to enable modal progress HUD (a modal progress indicator, HUD = Heads Up Display). +A Flutter loading overlay with a dimmed backdrop and a 300 ms fade. +Control it with a boolean or let it follow a `Future`. -Started as a fork of [modal_progress_hud](https://pub.dev/packages/modal_progress_hud) -Inspired by [this](https://codingwithjoe.com/flutter-how-to-build-a-modal-progress-indicator/) article. +[pub.dev](https://pub.dev/packages/loading_overlay) · +[API reference](https://pub.dev/documentation/loading_overlay/latest/) +![Loading overlay on a login form](https://raw.githubusercontent.com/java-james/loading_overlay/master/loading_overlay.gif) -## Demo +## Install -![Demo](https://raw.githubusercontent.com/java-james/loading_overlay/master/loading_overlay.gif) +Add to your `pubspec.yaml`, then run `flutter pub get`: -*See example for details* - - -## Usage - -Add the package to your `pubspec.yml` file. - -```yml +```yaml dependencies: - loading_overlay: ^0.4.0 + loading_overlay: ^0.6.0 ``` -Next, import the library into your widget. +## Usage + +Import the package: ```dart +import 'package:flutter/widgets.dart'; import 'package:loading_overlay/loading_overlay.dart'; ``` -Now, all you have to do is simply wrap your widget as a child of `LoadingOverlay`, typically a form, together with a boolean that is maintained in local state. +Wrap your content and rebuild when your `isSaving` boolean changes: ```dart -... -bool _isSaving_ = false -... - -@override -Widget build(BuildContext context) { - return Scaffold( - body: LoadingOverlay( - color: Colors.black.withOpacity(0.5), - child: Container( - Form(...) - ), - isLoading: _isSaving_ - ), - ); -} +return LoadingOverlay( + isLoading: isSaving, + child: const Center(child: Text('Your content')), +); ``` -Alternatively, show the overlay until a Future completes (non-breaking new feature): +### Follow a future -```dart -// Start an async operation -final saveFuture = _saveFormAsync(); +Create and retain `saveFuture` (`Future`) before `build`, for example in +`initState` or an event handler: +```dart return LoadingOverlay.withFuture( future: saveFuture, - color: Colors.black.withOpacity(0.5), - child: Form(...), + child: const Center(child: Text('Your content')), ); ``` +Success and failure both dismiss the overlay. Handle errors on the original +future. Only the latest future controls visibility; rebuilding with the same +completed future keeps the overlay hidden. -## Options +### Interaction -The current parameters are customizable in the constructor -```dart -LoadingOverlay({ - required bool isLoading, - required Widget child, - Widget progressIndicator = const CircularProgressIndicator(), - Color? color, -}); - -// New: show overlay until a Future completes -LoadingOverlay.withFuture({ - required Future future, - required Widget child, - Widget progressIndicator = const CircularProgressIndicator(), - Color? color, -}); -``` +The overlay blocks pointer taps, including during fade-out. Keyboard and +accessibility actions remain available, so guard async handlers against duplicate +submissions. The [login example](example/lib/main.dart) shows how. + +## Customize + +Both constructors accept these optional parameters: + +| Parameter | Default | +| --- | --- | +| `color` | Translucent black: `const Color(0x80000000)` | +| `progressIndicator` | White `CircularProgressIndicator` | + +## Compatibility -Update: See this [article](https://medium.com/@nocnoc/the-secret-to-async-validation-on-flutter-forms-4b273c667c03) on Medium about async form validation +Requires Flutter 3.50+ and Dart `^3.14.0`. -See the [example application](https://github.com/java-james/loading_overlay/tree/master/example) source -for a complete sample app using the modal progress HUD. Included in the -example is a method for using a form's validators while making async -calls (see [flutter/issues/9688](https://github.com/flutter/flutter/issues/9688) for details). +**Upgrading from 0.5.x:** the default spinner now uses `material_ui` and no longer +reads themes from `package:flutter/material.dart`. To retain legacy spinner +styling, pass your own `progressIndicator` or +[migrate your Material theme](https://docs.flutter.dev/release/breaking-changes/material-ui-and-cupertino-ui). +See [Contributing](CONTRIBUTING.md) for development requirements and checks. -### Issues and feedback +[Changelog](CHANGELOG.md) · +[Report an issue](https://github.com/java-james/loading_overlay/issues) -Please file [issues](https://github.com/java-james/loading_overlay/issues/new) -to send feedback or report a bug. Thank you! +[MIT licensed](LICENSE). Forked from +[modal_progress_hud](https://pub.dev/packages/modal_progress_hud). diff --git a/analysis_options.yaml b/analysis_options.yaml index 0d29021..55b180c 100644 --- a/analysis_options.yaml +++ b/analysis_options.yaml @@ -7,6 +7,9 @@ # The following line activates a set of recommended lints for Flutter apps, # packages, and plugins designed to encourage good coding practices. +analyzer: + exclude: + - build/** include: package:flutter_lints/flutter.yaml linter: diff --git a/example/README.md b/example/README.md index 2b3fce4..5ee4c26 100644 --- a/example/README.md +++ b/example/README.md @@ -1,16 +1,23 @@ -# example +# loading_overlay example -A new Flutter project. +This login form shows how to keep the form visible while blocking pointer taps +and preventing duplicate sign-ins during an asynchronous operation. It also +demonstrates safely disposing the form's controllers and leaving the page while +a request is pending. -## Getting Started +Run from this directory: -This project is a starting point for a Flutter application. +```sh +flutter pub get +flutter run -d chrome +flutter test +``` -A few resources to get you started if this is your first Flutter project: +The library and example require Flutter 3.50+ / Dart 3.14+ and use `material_ui`. -- [Lab: Write your first Flutter app](https://docs.flutter.dev/get-started/codelab) -- [Cookbook: Useful Flutter samples](https://docs.flutter.dev/cookbook) +The Android project targets Flutter 3.50 with AGP 9.3.1, Gradle 9.5 and JDK 17 or +newer. It uses AGP's built-in Kotlin support. Build it with: -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. +```sh +flutter build apk --debug +``` diff --git a/example/analysis_options.yaml b/example/analysis_options.yaml index 0d29021..bf8d421 100644 --- a/example/analysis_options.yaml +++ b/example/analysis_options.yaml @@ -7,6 +7,15 @@ # The following line activates a set of recommended lints for Flutter apps, # packages, and plugins designed to encourage good coding practices. +analyzer: + exclude: + - build/** + - android/** + - ios/** + - web/** + - windows/** + - macos/** + - linux/** include: package:flutter_lints/flutter.yaml linter: diff --git a/example/android/.gitignore b/example/android/.gitignore index 55afd91..1986846 100644 --- a/example/android/.gitignore +++ b/example/android/.gitignore @@ -1,8 +1,5 @@ -gradle-wrapper.jar /.gradle /captures/ -/gradlew -/gradlew.bat /local.properties GeneratedPluginRegistrant.java diff --git a/example/android/app/build.gradle b/example/android/app/build.gradle index b5511a9..696b882 100644 --- a/example/android/app/build.gradle +++ b/example/android/app/build.gradle @@ -1,7 +1,6 @@ plugins { id "com.android.application" - id "kotlin-android" - // The Flutter Gradle Plugin must be applied after the Android and Kotlin Gradle plugins. + // AGP supplies built-in Kotlin; apply the Flutter plugin after AGP. id "dev.flutter.flutter-gradle-plugin" } @@ -11,12 +10,8 @@ android { ndkVersion = flutter.ndkVersion compileOptions { - sourceCompatibility = JavaVersion.VERSION_1_8 - targetCompatibility = JavaVersion.VERSION_1_8 - } - - kotlinOptions { - jvmTarget = JavaVersion.VERSION_1_8 + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 } defaultConfig { @@ -39,6 +34,12 @@ android { } } +kotlin { + compilerOptions { + jvmTarget = org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17 + } +} + flutter { source = "../.." } diff --git a/example/android/gradle.properties b/example/android/gradle.properties index 2597170..5b7be60 100644 --- a/example/android/gradle.properties +++ b/example/android/gradle.properties @@ -1,3 +1,6 @@ org.gradle.jvmargs=-Xmx4G -XX:MaxMetaspaceSize=2G -XX:+HeapDumpOnOutOfMemoryError android.useAndroidX=true android.enableJetifier=true +# Flutter still requires the legacy AGP DSL, but supports built-in Kotlin. +android.newDsl=false +android.builtInKotlin=true diff --git a/example/android/gradle/wrapper/gradle-wrapper.properties b/example/android/gradle/wrapper/gradle-wrapper.properties index 7bb2df6..76d4386 100644 --- a/example/android/gradle/wrapper/gradle-wrapper.properties +++ b/example/android/gradle/wrapper/gradle-wrapper.properties @@ -2,4 +2,4 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.3-all.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-9.5.0-all.zip diff --git a/example/android/settings.gradle b/example/android/settings.gradle index b9e43bd..ad8129d 100644 --- a/example/android/settings.gradle +++ b/example/android/settings.gradle @@ -18,8 +18,7 @@ pluginManagement { plugins { id "dev.flutter.flutter-plugin-loader" version "1.0.0" - id "com.android.application" version "8.1.0" apply false - id "org.jetbrains.kotlin.android" version "1.8.22" apply false + id "com.android.application" version "9.3.1" apply false } include ":app" diff --git a/example/example.iml b/example/example.iml deleted file mode 100644 index f66303d..0000000 --- a/example/example.iml +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - - - - - - - - - - - - diff --git a/example/lib/main.dart b/example/lib/main.dart index 39fc0e7..64afe4e 100644 --- a/example/lib/main.dart +++ b/example/lib/main.dart @@ -1,7 +1,8 @@ -import 'package:flutter/material.dart'; -import 'package:loading_overlay/loading_overlay.dart'; import 'dart:async'; +import 'package:loading_overlay/loading_overlay.dart'; +import 'package:material_ui/material_ui.dart'; + void main() => runApp(const MyApp()); class MyApp extends StatelessWidget { @@ -15,9 +16,7 @@ class MyApp extends StatelessWidget { colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple), useMaterial3: true, ), - home: LoginPage( - onSignIn: () => print('login successful!'), - ), + home: LoginPage(onSignIn: () => debugPrint('login successful!')), ); } } @@ -37,25 +36,37 @@ class LoginPageState extends State { bool _isLoading = false; Future signIn() async { + // Also guard keyboard activation and taps before the next frame is drawn. + if (_isLoading) return; + setState(() { _isLoading = true; }); await Future.delayed(const Duration(seconds: 2)); + if (!mounted) return; widget.onSignIn(); + if (!mounted) return; setState(() { _isLoading = false; }); } + @override + void dispose() { + _usernameController.dispose(); + _passwordController.dispose(); + super.dispose(); + } + @override Widget build(BuildContext context) { return Scaffold( // Optionally can use [LoadingOverlay.withFuture] and pass in the Future from signIn too! body: LoadingOverlay( - color: Colors.black.withOpacity(0.5), + color: const Color(0x80000000), isLoading: _isLoading, child: SafeArea( child: Column( @@ -69,10 +80,7 @@ class LoginPageState extends State { decoration: const InputDecoration(labelText: 'Password'), obscureText: true, ), - ElevatedButton( - onPressed: signIn, - child: const Text('Login'), - ), + ElevatedButton(onPressed: signIn, child: const Text('Login')), ], ), ), diff --git a/example/pubspec.lock b/example/pubspec.lock index adb824d..bc48911 100644 --- a/example/pubspec.lock +++ b/example/pubspec.lock @@ -5,10 +5,10 @@ packages: dependency: transitive description: name: async - sha256: "758e6d74e971c3e5aceb4110bfd6698efc7f501675bcfe0c775459a8140750eb" + sha256: e2eb0491ba5ddb6177742d2da23904574082139b07c1e33b8503b9f46f3e1a37 url: "https://pub.dev" source: hosted - version: "2.13.0" + version: "2.13.1" boolean_selector: dependency: transitive description: @@ -21,18 +21,18 @@ packages: dependency: transitive description: name: characters - sha256: f71061c654a3380576a52b451dd5532377954cf9dbd272a78fc8479606670803 + sha256: faf38497bda5ead2a8c7615f4f7939df04333478bf32e4173fcb06d428b5716b url: "https://pub.dev" source: hosted - version: "1.4.0" + version: "1.4.1" clock: dependency: transitive description: name: clock - sha256: fddb70d9b5277016c77a80201021d40a2247104d9f4aa7bab7157b7e3f05b84b + sha256: e51d50bca3217c9a9fa2b41a30e4a38971133f5f9ec7a3d57bae095007f1d28e url: "https://pub.dev" source: hosted - version: "1.1.2" + version: "1.1.3" collection: dependency: transitive description: @@ -41,14 +41,14 @@ packages: url: "https://pub.dev" source: hosted version: "1.19.1" - cupertino_icons: - dependency: "direct main" + cupertino_ui: + dependency: transitive description: - name: cupertino_icons - sha256: ba631d1c7f7bef6b729a622b7b752645a2d076dba9976925b8f25725a30e1ee6 + name: cupertino_ui + sha256: "369e39a1c5c030a6212589c3da1809920b1c2cfade7b02aade7695bfa4b88c3a" url: "https://pub.dev" source: hosted - version: "1.0.8" + version: "1.1.6" fake_async: dependency: transitive description: @@ -66,15 +66,28 @@ packages: dependency: "direct dev" description: name: flutter_lints - sha256: "3f41d009ba7172d5ff9be5f6e6e6abb4300e263aab8866d2a0842ed2a70f8f0c" + sha256: "3105dc8492f6183fb076ccf1f351ac3d60564bff92e20bfc4af9cc1651f4e7e1" url: "https://pub.dev" source: hosted - version: "4.0.0" + version: "6.0.0" + flutter_localizations: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" flutter_test: dependency: "direct dev" description: flutter source: sdk version: "0.0.0" + intl: + dependency: transitive + description: + name: intl + sha256: "1ca20c894b1717686a2319b8548763d812bc0aabdac580420a44c5178c57a867" + url: "https://pub.dev" + source: hosted + version: "0.20.3" leak_tracker: dependency: transitive description: @@ -103,41 +116,57 @@ packages: dependency: transitive description: name: lints - sha256: "976c774dd944a42e83e2467f4cc670daef7eed6295b10b36ae8c85bcbf828235" + sha256: "12f842a479589fea194fe5c5a3095abc7be0c1f2ddfa9a0e76aed1dbd26a87df" + url: "https://pub.dev" + source: hosted + version: "6.1.0" + listen: + dependency: transitive + description: + name: listen + sha256: "47501a08016a43fcad79252439d723f50f14f88fa7bfd8a177e0a417e5c9e1f2" url: "https://pub.dev" source: hosted - version: "4.0.0" + version: "1.0.1" loading_overlay: dependency: "direct main" description: path: ".." relative: true source: path - version: "0.4.3" + version: "0.6.0" matcher: dependency: transitive description: name: matcher - sha256: dc58c723c3c24bf8d3e2d3ad3f2f9d7bd9cf43ec6feaa64181775e60190153f2 + sha256: "31bd099b47c10cd1aeb55146a2d46ce0277630ecef3f7dae54ad7873f36696cd" url: "https://pub.dev" source: hosted - version: "0.12.17" + version: "0.12.20" material_color_utilities: dependency: transitive description: name: material_color_utilities - sha256: f7142bb1154231d7ea5f96bc7bde4bda2a0945d2806bb11670e30b850d56bdec + sha256: "9c337007e82b1889149c82ed242ed1cb24a66044e30979c44912381e9be4c48b" + url: "https://pub.dev" + source: hosted + version: "0.13.0" + material_ui: + dependency: "direct main" + description: + name: material_ui + sha256: "474c135fd46b56ff1d35ca982155e8863d28fbc6464d1192acf4ee53a738680e" url: "https://pub.dev" source: hosted - version: "0.11.1" + version: "1.11.0" meta: dependency: transitive description: name: meta - sha256: e3641ec5d63ebf0d9b41bd43201a66e3fc79a65db5f61fc181f04cd27aab950c + sha256: "307249ce4ff29d58a18e97f6345f539382eb9c9c29ecda628900f31de0443dd9" url: "https://pub.dev" source: hosted - version: "1.16.0" + version: "1.19.0" path: dependency: transitive description: @@ -155,18 +184,18 @@ packages: dependency: transitive description: name: source_span - sha256: "254ee5351d6cb365c859e20ee823c3bb479bf4a293c22d17a9f1bf144ce86f7c" + sha256: "56a02f1f4cd1a2d96303c0144c93bd6d909eea6bee6bf5a0e0b685edbd4c47ab" url: "https://pub.dev" source: hosted - version: "1.10.1" + version: "1.10.2" stack_trace: dependency: transitive description: name: stack_trace - sha256: "8b27215b45d22309b5cddda1aa2b19bdfec9df0e765f2de506401c071d38d1b1" + sha256: "277654b3034d17ac6f9f1cb5595db011b1d5d41e8806866db28e0abaa101c490" url: "https://pub.dev" source: hosted - version: "1.12.1" + version: "1.12.2" stream_channel: dependency: transitive description: @@ -195,26 +224,26 @@ packages: dependency: transitive description: name: test_api - sha256: "522f00f556e73044315fa4585ec3270f1808a4b186c936e612cab0b565ff1e00" + sha256: "0a10344e901e5b2e63819567951cb6a06673ed6b84f40462188ff5a0c41f371f" url: "https://pub.dev" source: hosted - version: "0.7.6" + version: "0.7.14" vector_math: dependency: transitive description: name: vector_math - sha256: d530bd74fea330e6e364cda7a85019c434070188383e1cd8d9777ee586914c5b + sha256: fa49e1674cb84acb900141714e6c6e1f9ae099827c24d141430ff6819db4e1bc url: "https://pub.dev" source: hosted - version: "2.2.0" + version: "2.4.4" vm_service: dependency: transitive description: name: vm_service - sha256: "45caa6c5917fa127b5dbcfbd1fa60b14e583afdc08bfc96dda38886ca252eb60" + sha256: "89b11d62e1040ee681af3b4f1c97a803ecbf010c6e8b9c5896ee5b08c3bf7b78" url: "https://pub.dev" source: hosted - version: "15.0.2" + version: "15.4.0" sdks: - dart: ">=3.8.0-0 <4.0.0" - flutter: ">=3.18.0-18.0.pre.54" + dart: ">=3.14.0 <4.0.0" + flutter: ">=3.50.0" diff --git a/example/pubspec.yaml b/example/pubspec.yaml index 4e306e4..a6616bf 100644 --- a/example/pubspec.yaml +++ b/example/pubspec.yaml @@ -1,93 +1,23 @@ name: example -description: "A new Flutter project." -# The following line prevents the package from being accidentally published to -# pub.dev using `flutter pub publish`. This is preferred for private packages. -publish_to: 'none' # Remove this line if you wish to publish to pub.dev - -# The following defines the version and build number for your application. -# A version number is three numbers separated by dots, like 1.2.43 -# followed by an optional build number separated by a +. -# Both the version and the builder number may be overridden in flutter -# build by specifying --build-name and --build-number, respectively. -# In Android, build-name is used as versionName while build-number used as versionCode. -# Read more about Android versioning at https://developer.android.com/studio/publish/versioning -# In iOS, build-name is used as CFBundleShortVersionString while build-number is used as CFBundleVersion. -# Read more about iOS versioning at -# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html -# In Windows, build-name is used as the major, minor, and patch parts -# of the product and file versions while build-number is used as the build suffix. +description: A login form demonstrating loading_overlay. +publish_to: none version: 1.0.0+1 environment: - sdk: ^3.5.3 + sdk: ^3.14.0 + flutter: '>=3.50.0' -# Dependencies specify other packages that your package needs in order to work. -# To automatically upgrade your package dependencies to the latest versions -# consider running `flutter pub upgrade --major-versions`. Alternatively, -# dependencies can be manually updated by changing the version numbers below to -# the latest version available on pub.dev. To see which dependencies have newer -# versions available, run `flutter pub outdated`. dependencies: flutter: sdk: flutter - - - # The following adds the Cupertino Icons font to your application. - # Use with the CupertinoIcons class for iOS style icons. - cupertino_icons: ^1.0.8 - loading_overlay: path: ../ + material_ui: ^1.11.0 dev_dependencies: flutter_test: sdk: flutter + flutter_lints: ^6.0.0 - # The "flutter_lints" package below contains a set of recommended lints to - # encourage good coding practices. The lint set provided by the package is - # activated in the `analysis_options.yaml` file located at the root of your - # package. See that file for information about deactivating specific lint - # rules and activating additional ones. - flutter_lints: ^4.0.0 - -# For information on the generic Dart part of this file, see the -# following page: https://dart.dev/tools/pub/pubspec - -# The following section is specific to Flutter packages. flutter: - - # The following line ensures that the Material Icons font is - # included with your application, so that you can use the icons in - # the material Icons class. uses-material-design: true - - # To add assets to your application, add an assets section, like this: - # assets: - # - images/a_dot_burr.jpeg - # - images/a_dot_ham.jpeg - - # An image asset can refer to one or more resolution-specific "variants", see - # https://flutter.dev/to/resolution-aware-images - - # For details regarding adding assets from package dependencies, see - # https://flutter.dev/to/asset-from-package - - # To add custom fonts to your application, add a fonts section here, - # in this "flutter" section. Each entry in this list should have a - # "family" key with the font family name, and a "fonts" key with a - # list giving the asset and other descriptors for the font. For - # example: - # fonts: - # - family: Schyler - # fonts: - # - asset: fonts/Schyler-Regular.ttf - # - asset: fonts/Schyler-Italic.ttf - # style: italic - # - family: Trajan Pro - # fonts: - # - asset: fonts/TrajanPro.ttf - # - asset: fonts/TrajanPro_Bold.ttf - # weight: 700 - # - # For details regarding fonts from package dependencies, - # see https://flutter.dev/to/font-from-package diff --git a/example/test/widget_test.dart b/example/test/widget_test.dart index 2a2b819..59c73f6 100644 --- a/example/test/widget_test.dart +++ b/example/test/widget_test.dart @@ -1,8 +1,92 @@ -// This is a basic Flutter widget test. -// -// To perform an interaction with a widget in your test, use the WidgetTester -// utility in the flutter_test package. For example, you can send tap and scroll -// gestures. You can also use WidgetTester to find child widgets in the widget -// tree, read text, and verify that the values of widget properties are correct. - -void main() {} +import 'package:example/main.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:material_ui/material_ui.dart'; + +void main() { + testWidgets('login blocks duplicate taps and restores the form', ( + tester, + ) async { + var signIns = 0; + await tester.pumpWidget( + MaterialApp(home: LoginPage(onSignIn: () => signIns++)), + ); + await tester.enterText(find.byType(TextField).first, 'james'); + await tester.enterText(find.byType(TextField).last, 'password'); + + final loginPosition = tester.getCenter(find.text('Login')); + await tester.tapAt(loginPosition); + await tester.pump(); + expect(find.byType(CircularProgressIndicator), findsOneWidget); + await tester.tapAt(loginPosition); + await tester.pump(const Duration(seconds: 2)); + await tester.pumpAndSettle(); + + expect(signIns, 1); + expect(find.byType(CircularProgressIndicator), findsNothing); + expect( + tester.widget(find.byType(TextField).first).controller!.text, + 'james', + ); + + await tester.tapAt(loginPosition); + await tester.pump(const Duration(seconds: 2)); + await tester.pumpAndSettle(); + expect(signIns, 2); + }); + + testWidgets('leaving the page during login does not update disposed state', ( + tester, + ) async { + var signIns = 0; + await tester.pumpWidget( + MaterialApp(home: LoginPage(onSignIn: () => signIns++)), + ); + await tester.tap(find.text('Login')); + await tester.pump(); + await tester.pumpWidget(const SizedBox()); + await tester.pump(const Duration(seconds: 2)); + + expect(signIns, 0); + expect(tester.takeException(), isNull); + }); + + testWidgets('login ignores repeated taps before the overlay is drawn', ( + tester, + ) async { + var signIns = 0; + await tester.pumpWidget( + MaterialApp(home: LoginPage(onSignIn: () => signIns++)), + ); + + final loginPosition = tester.getCenter(find.text('Login')); + await tester.tapAt(loginPosition); + await tester.tapAt(loginPosition); + await tester.pump(const Duration(seconds: 2)); + await tester.pumpAndSettle(); + + expect(signIns, 1); + expect(find.byType(CircularProgressIndicator), findsNothing); + }); + + testWidgets('login ignores repeated keyboard activation while loading', ( + tester, + ) async { + var signIns = 0; + await tester.pumpWidget( + MaterialApp(home: LoginPage(onSignIn: () => signIns++)), + ); + + Focus.of(tester.element(find.text('Login'))).requestFocus(); + await tester.pump(); + await tester.sendKeyEvent(LogicalKeyboardKey.enter); + await tester.pump(); + expect(find.byType(CircularProgressIndicator), findsOneWidget); + await tester.sendKeyEvent(LogicalKeyboardKey.enter); + await tester.pump(const Duration(seconds: 2)); + await tester.pumpAndSettle(); + + expect(signIns, 1); + expect(find.byType(CircularProgressIndicator), findsNothing); + }); +} diff --git a/lib/loading_overlay.dart b/lib/loading_overlay.dart index a03564b..283acc9 100644 --- a/lib/loading_overlay.dart +++ b/lib/loading_overlay.dart @@ -1,4 +1,4 @@ -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; /// Our custom fork of https://pub.dev/packages/modal_progress_hud adding a fading effect /// @@ -12,7 +12,8 @@ import 'package:flutter/material.dart'; /// /// The color of the modal barrier can be set using [color] /// -/// The opacity of the modal barrier can be set using color.withOpacity(0.5) +/// The opacity of the modal barrier is the alpha channel of [color], for example +/// `const Color(0x80000000)` for a translucent black backdrop. /// /// HUD=Heads Up Display /// @@ -28,20 +29,26 @@ class LoadingOverlay extends StatefulWidget { final bool _managedByFuture; const LoadingOverlay({ - Key? key, + super.key, required this.isLoading, required this.child, this.progressIndicator = const CircularProgressIndicator( valueColor: AlwaysStoppedAnimation(Colors.white), ), this.color, - }) : _future = null, - _managedByFuture = false, - super(key: key); + }) : _future = null, + _managedByFuture = false; /// Constructs a LoadingOverlay that is shown immediately and remains - /// visible until [future] completes (success or error). This is a - /// non-breaking alternative to controlling visibility with [isLoading]. + /// visible until [future] completes (success or error). This is an + /// alternative to controlling visibility with [isLoading]. + /// + /// Obtain the future before building this widget, so rebuilds do not restart + /// the operation. Replacing it starts a new loading cycle; completion of a + /// previous future does not hide the new cycle. + /// + /// This widget observes errors only to hide the overlay. Callers can still + /// await or handle errors on the original future to display an error message. factory LoadingOverlay.withFuture({ Key? key, required Future future, @@ -55,9 +62,9 @@ class LoadingOverlay extends StatefulWidget { key: key, // Start visible and let the State hide when future completes. isLoading: true, - child: child, progressIndicator: progressIndicator, color: color, + child: child, )._withFuture(future); } @@ -66,26 +73,24 @@ class LoadingOverlay extends StatefulWidget { return LoadingOverlay._internal( key: key, isLoading: isLoading, - child: child, progressIndicator: progressIndicator, color: color, future: future, managedByFuture: true, + child: child, ); } // Private internal constructor used by the factory to carry the future. const LoadingOverlay._internal({ - Key? key, + super.key, required this.isLoading, required this.child, required this.progressIndicator, this.color, - required Future future, - required bool managedByFuture, - }) : _future = future, - _managedByFuture = managedByFuture, - super(key: key); + required this._future, + required this._managedByFuture, + }); @override LoadingOverlayState createState() => LoadingOverlayState(); @@ -95,95 +100,110 @@ class LoadingOverlayState extends State with SingleTickerProviderStateMixin { late AnimationController _controller; late Animation _animation; - bool? _overlayVisible; + bool _overlayVisible = false; + Object? _activeCallbackIdentity; LoadingOverlayState(); @override void initState() { super.initState(); - _overlayVisible = false; _controller = AnimationController( - vsync: this, duration: const Duration(milliseconds: 300)); + vsync: this, + duration: const Duration(milliseconds: 300), + ); _animation = Tween(begin: 0.0, end: 1.0).animate(_controller); _animation.addStatusListener((status) { - // ignore: unnecessary_statements - status == AnimationStatus.forward - ? setState(() { - _overlayVisible = true; - }) - : null; - // ignore: unnecessary_statements - status == AnimationStatus.dismissed - ? setState(() { - _overlayVisible = false; - }) - : null; + if (status != AnimationStatus.forward && + status != AnimationStatus.dismissed) { + return; + } + setState(() { + _overlayVisible = status == AnimationStatus.forward; + }); }); if (widget.isLoading) { _controller.forward(); } - // If managed by a Future, hide the overlay when the Future completes - // regardless of success or error. - if (widget._managedByFuture && widget._future != null) { - widget._future!.whenComplete(() { - if (!mounted) return; - _controller.reverse(); - }); + if (widget._managedByFuture) { + _subscribeToFuture(); } } @override void didUpdateWidget(LoadingOverlay oldWidget) { super.didUpdateWidget(oldWidget); - if (!oldWidget.isLoading && widget.isLoading) { + if (widget._managedByFuture && + oldWidget._managedByFuture && + oldWidget._future == widget._future) { + return; + } + + if (widget._managedByFuture) { _controller.forward(); + _subscribeToFuture(); + return; } - if (oldWidget.isLoading && !widget.isLoading) { - _controller.reverse(); + // A pending future no longer controls visibility after switching modes. + _activeCallbackIdentity = null; + if (!oldWidget._managedByFuture && + oldWidget.isLoading == widget.isLoading) { + return; } - // If managed by Future and the Future instance changed, show overlay - // and wire up completion to hide it again. - if (widget._managedByFuture && oldWidget._future != widget._future) { + if (widget.isLoading) { _controller.forward(); - widget._future?.whenComplete(() { - if (!mounted) return; - _controller.reverse(); - }); + return; } + + _controller.reverse(); + } + + void _subscribeToFuture() { + final callbackIdentity = Object(); + _activeCallbackIdentity = callbackIdentity; + + void onComplete() { + if (!mounted || _activeCallbackIdentity != callbackIdentity) return; + _activeCallbackIdentity = null; + _controller.reverse(); + } + + // Handle both outcomes on this subscription. An ignored whenComplete() + // future would otherwise propagate errors as uncaught asynchronous errors. + widget._future!.then( + (_) => onComplete(), + onError: (Object error, StackTrace stackTrace) => onComplete(), + ); } @override void dispose() { + _activeCallbackIdentity = null; _controller.dispose(); super.dispose(); } @override - Widget build(BuildContext context) { - var widgets = []; - widgets.add(widget.child); - - if (_overlayVisible == true) { - final modal = FadeTransition( - opacity: _animation, - child: Stack( - children: [ - SizedBox.expand( - child: ColoredBox( - color: widget.color ?? Colors.black.withOpacity(0.5), + Widget build(BuildContext context) => Stack( + children: [ + widget.child, + if (_overlayVisible) + FadeTransition( + opacity: _animation, + child: Stack( + children: [ + SizedBox.expand( + child: ColoredBox( + color: widget.color ?? const Color(0x80000000), + ), ), - ), - Center(child: widget.progressIndicator), - ], + Center(child: widget.progressIndicator), + ], + ), ), - ); - widgets.add(modal); - } - - return Stack(children: widgets); - } + ], + ); } diff --git a/pubspec.lock b/pubspec.lock index 0f56103..8b268fa 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -5,10 +5,10 @@ packages: dependency: transitive description: name: async - sha256: "758e6d74e971c3e5aceb4110bfd6698efc7f501675bcfe0c775459a8140750eb" + sha256: e2eb0491ba5ddb6177742d2da23904574082139b07c1e33b8503b9f46f3e1a37 url: "https://pub.dev" source: hosted - version: "2.13.0" + version: "2.13.1" boolean_selector: dependency: transitive description: @@ -21,18 +21,18 @@ packages: dependency: transitive description: name: characters - sha256: f71061c654a3380576a52b451dd5532377954cf9dbd272a78fc8479606670803 + sha256: faf38497bda5ead2a8c7615f4f7939df04333478bf32e4173fcb06d428b5716b url: "https://pub.dev" source: hosted - version: "1.4.0" + version: "1.4.1" clock: dependency: transitive description: name: clock - sha256: fddb70d9b5277016c77a80201021d40a2247104d9f4aa7bab7157b7e3f05b84b + sha256: e51d50bca3217c9a9fa2b41a30e4a38971133f5f9ec7a3d57bae095007f1d28e url: "https://pub.dev" source: hosted - version: "1.1.2" + version: "1.1.3" collection: dependency: transitive description: @@ -41,6 +41,14 @@ packages: url: "https://pub.dev" source: hosted version: "1.19.1" + cupertino_ui: + dependency: transitive + description: + name: cupertino_ui + sha256: "369e39a1c5c030a6212589c3da1809920b1c2cfade7b02aade7695bfa4b88c3a" + url: "https://pub.dev" + source: hosted + version: "1.1.6" fake_async: dependency: transitive description: @@ -62,11 +70,24 @@ packages: url: "https://pub.dev" source: hosted version: "6.0.0" + flutter_localizations: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" flutter_test: dependency: "direct dev" description: flutter source: sdk version: "0.0.0" + intl: + dependency: transitive + description: + name: intl + sha256: "1ca20c894b1717686a2319b8548763d812bc0aabdac580420a44c5178c57a867" + url: "https://pub.dev" + source: hosted + version: "0.20.3" leak_tracker: dependency: transitive description: @@ -95,34 +116,50 @@ packages: dependency: transitive description: name: lints - sha256: a5e2b223cb7c9c8efdc663ef484fdd95bb243bff242ef5b13e26883547fce9a0 + sha256: "12f842a479589fea194fe5c5a3095abc7be0c1f2ddfa9a0e76aed1dbd26a87df" url: "https://pub.dev" source: hosted - version: "6.0.0" + version: "6.1.0" + listen: + dependency: transitive + description: + name: listen + sha256: "47501a08016a43fcad79252439d723f50f14f88fa7bfd8a177e0a417e5c9e1f2" + url: "https://pub.dev" + source: hosted + version: "1.0.1" matcher: dependency: transitive description: name: matcher - sha256: dc58c723c3c24bf8d3e2d3ad3f2f9d7bd9cf43ec6feaa64181775e60190153f2 + sha256: "31bd099b47c10cd1aeb55146a2d46ce0277630ecef3f7dae54ad7873f36696cd" url: "https://pub.dev" source: hosted - version: "0.12.17" + version: "0.12.20" material_color_utilities: dependency: transitive description: name: material_color_utilities - sha256: f7142bb1154231d7ea5f96bc7bde4bda2a0945d2806bb11670e30b850d56bdec + sha256: "9c337007e82b1889149c82ed242ed1cb24a66044e30979c44912381e9be4c48b" + url: "https://pub.dev" + source: hosted + version: "0.13.0" + material_ui: + dependency: "direct main" + description: + name: material_ui + sha256: "474c135fd46b56ff1d35ca982155e8863d28fbc6464d1192acf4ee53a738680e" url: "https://pub.dev" source: hosted - version: "0.11.1" + version: "1.11.0" meta: dependency: transitive description: name: meta - sha256: e3641ec5d63ebf0d9b41bd43201a66e3fc79a65db5f61fc181f04cd27aab950c + sha256: "307249ce4ff29d58a18e97f6345f539382eb9c9c29ecda628900f31de0443dd9" url: "https://pub.dev" source: hosted - version: "1.16.0" + version: "1.19.0" path: dependency: transitive description: @@ -140,18 +177,18 @@ packages: dependency: transitive description: name: source_span - sha256: "254ee5351d6cb365c859e20ee823c3bb479bf4a293c22d17a9f1bf144ce86f7c" + sha256: "56a02f1f4cd1a2d96303c0144c93bd6d909eea6bee6bf5a0e0b685edbd4c47ab" url: "https://pub.dev" source: hosted - version: "1.10.1" + version: "1.10.2" stack_trace: dependency: transitive description: name: stack_trace - sha256: "8b27215b45d22309b5cddda1aa2b19bdfec9df0e765f2de506401c071d38d1b1" + sha256: "277654b3034d17ac6f9f1cb5595db011b1d5d41e8806866db28e0abaa101c490" url: "https://pub.dev" source: hosted - version: "1.12.1" + version: "1.12.2" stream_channel: dependency: transitive description: @@ -180,26 +217,26 @@ packages: dependency: transitive description: name: test_api - sha256: "522f00f556e73044315fa4585ec3270f1808a4b186c936e612cab0b565ff1e00" + sha256: "0a10344e901e5b2e63819567951cb6a06673ed6b84f40462188ff5a0c41f371f" url: "https://pub.dev" source: hosted - version: "0.7.6" + version: "0.7.14" vector_math: dependency: transitive description: name: vector_math - sha256: d530bd74fea330e6e364cda7a85019c434070188383e1cd8d9777ee586914c5b + sha256: fa49e1674cb84acb900141714e6c6e1f9ae099827c24d141430ff6819db4e1bc url: "https://pub.dev" source: hosted - version: "2.2.0" + version: "2.4.4" vm_service: dependency: transitive description: name: vm_service - sha256: "45caa6c5917fa127b5dbcfbd1fa60b14e583afdc08bfc96dda38886ca252eb60" + sha256: "89b11d62e1040ee681af3b4f1c97a803ecbf010c6e8b9c5896ee5b08c3bf7b78" url: "https://pub.dev" source: hosted - version: "15.0.2" + version: "15.4.0" sdks: - dart: ">=3.8.0 <4.0.0" - flutter: ">=3.18.0-18.0.pre.54" + dart: ">=3.14.0 <4.0.0" + flutter: ">=3.50.0" diff --git a/pubspec.yaml b/pubspec.yaml index 1fe360c..0fa7096 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,59 +1,18 @@ name: loading_overlay -description: A modal progress indicator widget that fades in and out. Wrap around another widget to block access to widget during an async call. -version: 0.5.0 +description: A Flutter loading overlay with a dimmed backdrop and a fade animation, controlled by a boolean or a Future. +version: 0.6.0 homepage: https://github.com/java-james/loading_overlay environment: - sdk: '>=2.12.0 <4.0.0' + sdk: ^3.14.0 + flutter: '>=3.50.0' dependencies: flutter: sdk: flutter + material_ui: ^1.11.0 dev_dependencies: flutter_test: sdk: flutter - - # The "flutter_lints" package below contains a set of recommended lints to - # encourage good coding practices. The lint set provided by the package is - # activated in the `analysis_options.yaml` file located at the root of your - # package. See that file for information about deactivating specific lint - # rules and activating additional ones. flutter_lints: ^6.0.0 - -# For information on the generic Dart part of this file, see the -# following page: https://www.dartlang.org/tools/pub/pubspec - -# The following section is specific to Flutter. -flutter: - - # To add assets to your package, add an assets section, like this: - # assets: - # - images/a_dot_burr.jpeg - # - images/a_dot_ham.jpeg - # - # For details regarding assets in packages, see - # https://flutter.io/assets-and-images/#from-packages - # - # An image asset can refer to one or more resolution-specific "variants", see - # https://flutter.io/assets-and-images/#resolution-aware. - - # To add custom fonts to your package, add a fonts section here, - # in this "flutter" section. Each entry in this list should have a - # "family" key with the font family name, and a "fonts" key with a - # list giving the asset and other descriptors for the font. For - # example: - # fonts: - # - family: Schyler - # fonts: - # - asset: fonts/Schyler-Regular.ttf - # - asset: fonts/Schyler-Italic.ttf - # style: italic - # - family: Trajan Pro - # fonts: - # - asset: fonts/TrajanPro.ttf - # - asset: fonts/TrajanPro_Bold.ttf - # weight: 700 - # - # For details regarding fonts in packages, see - # https://flutter.io/custom-fonts/#from-packages diff --git a/scripts/android-wait-for-emulator.sh b/scripts/android-wait-for-emulator.sh deleted file mode 100755 index 1e0b76b..0000000 --- a/scripts/android-wait-for-emulator.sh +++ /dev/null @@ -1,26 +0,0 @@ -#!/bin/bash - -# Originally written by Ralf Kistner , but placed in the public domain - -set +e - -bootanim="" -failcounter=0 -timeout_in_sec=360 - -until [[ "$bootanim" =~ "stopped" ]]; do - bootanim=`adb -e shell getprop init.svc.bootanim 2>&1 &` - if [[ "$bootanim" =~ "device not found" || "$bootanim" =~ "device offline" - || "$bootanim" =~ "running" ]]; then - let "failcounter += 1" - let "remaining = $timeout_in_sec - $failcounter" - echo "Waiting for emulator to start: $remaining : status: $bootanim" - if [[ $failcounter -gt timeout_in_sec ]]; then - echo "Timeout ($timeout_in_sec seconds) reached; failed to start emulator" - exit 1 - fi - fi - sleep 1 -done - -echo "Emulator is ready" \ No newline at end of file diff --git a/scripts/ci.sh b/scripts/ci.sh deleted file mode 100755 index cdcbc44..0000000 --- a/scripts/ci.sh +++ /dev/null @@ -1,120 +0,0 @@ -#!/usr/bin/env bash -set -e - -show_help() { - printf "\n\nusage: $0 [--get] [--analyze] [--ios] [--apk] [--driver] [--clean] [] - -Tool for managing CI builds. -(run from root of repo) - -where: - --get - get all dependencies - --analyze - analyze dart code for all packages - --ios - build ios release for all apps - --apk - build android release for all apps - --driver - run integration tests for all apps - (expects a single running emulator/simulator) - --clean - clean all builds - - run flutter driver for app at path -" - exit 1 -} - -# run integration tests -runDriver () { - cd $1 - if [ -f "test_driver/main.dart" ]; then - echo "Running integration tests in $1..." - flutter driver test_driver/main.dart - fi - exitCode=$? - cd - > /dev/null - return $exitCode -} - -# run function in all dirs -# expects a function name -allDirs() { - dirs=(`find . -maxdepth 1 -type d`) - for dir in "${dirs[@]}"; do - $1 $dir - done -} - -runGet() { - cd $1 - if [ -f "pubspec.yaml" ]; then - flutter packages get - fi - cd - > /dev/null -} - -runIos() { - cd $1; - if [ -f "lib/main.dart" ]; then - flutter build ios - fi - cd - > /dev/null -} - -runApk() { - cd $1; - if [ -f "lib/main.dart" ]; then - echo "build apk in $1" - flutter build apk - fi - cd - > /dev/null -} - -runClean() { - cd $1; - if [ -f "pubspec.yaml" ]; then - echo "run clean in $1" - flutter clean > /dev/null - rm -rf ios/Pods ios/Podfile.lock - rm -rf android/.gradle - rm -rf coverage - fi - cd - > /dev/null -} - -# if no arguments passed -if [ -z $1 ]; then show_help; fi - -if ! [ -d .git ]; then printf "\nError: not in root of repo"; show_help; fi - -case $1 in - --get) - allDirs "runGet" - ;; - --analyze) - flutter analyze - ;; - --ios) - allDirs "runIos" - ;; - --apk) - allDirs "runApk" - ;; - --driver) - allDirs "runDriver" - ;; - --clean) - allDirs "runClean" - ;; - *) - if [[ -d "$1" ]]; then - runDriver $1 - else - printf "\nError: not a directory: $1" - show_help - fi - ;; -esac \ No newline at end of file diff --git a/scripts/runTests.sh b/scripts/runTests.sh index 295fc80..e84fbe7 100755 --- a/scripts/runTests.sh +++ b/scripts/runTests.sh @@ -1,19 +1,15 @@ #!/usr/bin/env bash -set -e +set -euo pipefail -runTests () { - cd $1; - echo "Running tests in $1 ..." - flutter test --coverage - # combine line coverage info from package tests to a common file - sed "s/^SF:lib/SF:$1\/lib/g" coverage/lcov.info >> $2/lcov.info - cd - > /dev/null -} +project_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +: > "$project_root/lcov.info" -# if running locally -if [ -f "lcov.info" ]; then - rm lcov.info -fi - -runTests . `pwd` -runTests example `pwd` +for package in . example; do + ( + cd "$project_root/$package" + echo "Running tests in $package ..." + flutter test --coverage + # Keep package and example coverage paths relative to the repository. + sed "s|^SF:lib|SF:$package/lib|g" coverage/lcov.info >> "$project_root/lcov.info" + ) +done diff --git a/test/loading_overlay_test.dart b/test/loading_overlay_test.dart index 6474020..e26db0d 100644 --- a/test/loading_overlay_test.dart +++ b/test/loading_overlay_test.dart @@ -1,16 +1,31 @@ import 'dart:async'; -import 'package:flutter/material.dart'; + +import 'package:flutter/foundation.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:loading_overlay/loading_overlay.dart'; +import 'package:material_ui/material_ui.dart'; + +Widget manualOverlay(bool isLoading) => MaterialApp( + home: LoadingOverlay(isLoading: isLoading, child: const Text('child')), +); + +Widget futureOverlay(Future future) => MaterialApp( + home: LoadingOverlay.withFuture(future: future, child: const Text('child')), +); + +Future finishFade(WidgetTester tester) async { + // Process future callbacks, start the animation's first frame, then finish it. + await tester.pump(); + await tester.pump(); + // Allow the frame after the exact endpoint to deliver AnimationStatus.dismissed. + await tester.pump(const Duration(milliseconds: 301)); +} void main() { group('Modal Progress HUD', () { - Widget sut(isLoading) => MaterialApp( - home: LoadingOverlay( - isLoading: isLoading, - child: const Text(''), - ), - ); + Widget sut(bool isLoading) => MaterialApp( + home: LoadingOverlay(isLoading: isLoading, child: const Text('')), + ); testWidgets('should show progress indicator when loading', (tester) async { const inAsyncCall = true; @@ -20,8 +35,9 @@ void main() { expect(find.byType(CircularProgressIndicator), findsOneWidget); }); - testWidgets('should not show progress indicator when not loading', - (tester) async { + testWidgets('should not show progress indicator when not loading', ( + tester, + ) async { const inAsyncCall = false; await tester.pumpWidget(sut(inAsyncCall)); @@ -46,8 +62,9 @@ void main() { expect(find.byType(CircularProgressIndicator), findsOneWidget); }); - testWidgets('hides progress indicator when future completes', - (tester) async { + testWidgets('hides progress indicator when future completes', ( + tester, + ) async { final completer = Completer(); final widget = MaterialApp( home: LoadingOverlay.withFuture( @@ -57,14 +74,411 @@ void main() { ); await tester.pumpWidget(widget); + await finishFade(tester); expect(find.byType(CircularProgressIndicator), findsOneWidget); // Complete the future and allow reverse animation to finish completer.complete(); - await tester.pump(); // process completion microtask - await tester.pump(const Duration(milliseconds: 300)); + await finishFade(tester); + + expect(find.byType(CircularProgressIndicator), findsNothing); + }); + + for (final fail in [false, true]) { + testWidgets('ignores obsolete future ${fail ? 'errors' : 'completion'}', ( + tester, + ) async { + final first = Completer(); + final second = Completer(); + await tester.pumpWidget(futureOverlay(first.future)); + await finishFade(tester); + await tester.pumpWidget(futureOverlay(second.future)); + + if (fail) { + first.completeError(StateError('obsolete operation')); + } else { + first.complete(); + } + await finishFade(tester); + + expect(find.byType(CircularProgressIndicator), findsOneWidget); + second.complete(); + await finishFade(tester); + expect(find.byType(CircularProgressIndicator), findsNothing); + }); + + testWidgets('ignores ${fail ? 'errors' : 'completion'} after disposal', ( + tester, + ) async { + final operation = Completer(); + await tester.pumpWidget(futureOverlay(operation.future)); + await finishFade(tester); + await tester.pumpWidget(const SizedBox()); + if (fail) { + operation.completeError(StateError('disposed operation')); + } else { + operation.complete(); + } + await finishFade(tester); + expect(tester.takeException(), isNull); + }); + } + + testWidgets('handles errors without changing the caller future', ( + tester, + ) async { + final operation = Completer(); + final error = StateError('save failed'); + final stackTrace = StackTrace.current; + Object? receivedError; + StackTrace? receivedStackTrace; + operation.future.then( + (_) {}, + onError: (Object e, StackTrace s) { + receivedError = e; + receivedStackTrace = s; + }, + ); + await tester.pumpWidget(futureOverlay(operation.future)); + await finishFade(tester); + operation.completeError(error, stackTrace); + await finishFade(tester); + + expect(receivedError, same(error)); + expect(receivedStackTrace, same(stackTrace)); + expect(find.byType(CircularProgressIndicator), findsNothing); + expect(tester.takeException(), isNull); + }); + + testWidgets('hides on error without a separate error listener', ( + tester, + ) async { + final operation = Completer(); + await tester.pumpWidget(futureOverlay(operation.future)); + await finishFade(tester); + operation.completeError(StateError('save failed')); + await finishFade(tester); + expect(find.byType(CircularProgressIndicator), findsNothing); + expect(tester.takeException(), isNull); + }); + + testWidgets('does not restart a completed future on rebuild', ( + tester, + ) async { + final operation = Completer(); + await tester.pumpWidget(futureOverlay(operation.future)); + await finishFade(tester); + await tester.pumpWidget(futureOverlay(operation.future)); + operation.complete(); + await finishFade(tester); + await tester.pumpWidget(futureOverlay(operation.future)); + expect(find.byType(CircularProgressIndicator), findsNothing); + await tester.pump(); + expect(find.byType(CircularProgressIndicator), findsNothing); + await finishFade(tester); + expect(find.byType(CircularProgressIndicator), findsNothing); + }); + + testWidgets('shows for a new future after the previous future completed', ( + tester, + ) async { + final first = Completer(); + final second = Completer(); + await tester.pumpWidget(futureOverlay(first.future)); + first.complete(); + await finishFade(tester); + expect(find.byType(CircularProgressIndicator), findsNothing); + + await tester.pumpWidget(futureOverlay(second.future)); + await finishFade(tester); + expect(find.byType(CircularProgressIndicator), findsOneWidget); + second.complete(); + await finishFade(tester); + expect(find.byType(CircularProgressIndicator), findsNothing); + }); + + testWidgets('handles synchronous completion', (tester) async { + await tester.pumpWidget(futureOverlay(SynchronousFuture(null))); + await finishFade(tester); + expect(find.byType(CircularProgressIndicator), findsNothing); + expect(tester.takeException(), isNull); + }); + + testWidgets('handles synchronous completion when replacing a future', ( + tester, + ) async { + final operation = Completer(); + await tester.pumpWidget(futureOverlay(operation.future)); + await finishFade(tester); + + await tester.pumpWidget(futureOverlay(SynchronousFuture(null))); + await finishFade(tester); + expect(find.byType(CircularProgressIndicator), findsNothing); + + operation.complete(); + await finishFade(tester); + expect(find.byType(CircularProgressIndicator), findsNothing); + expect(tester.takeException(), isNull); + }); + testWidgets('shows for a new future during the previous fade-out', ( + tester, + ) async { + final first = Completer(); + final second = Completer(); + await tester.pumpWidget(futureOverlay(first.future)); + await finishFade(tester); + + first.complete(); + await tester.pump(); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 150)); + expect( + tester + .widget(find.byType(FadeTransition).last) + .opacity + .value, + closeTo(0.5, 0.01), + ); + + await tester.pumpWidget(futureOverlay(second.future)); + await finishFade(tester); + expect(find.byType(CircularProgressIndicator), findsOneWidget); + + second.complete(); + await finishFade(tester); + expect(find.byType(CircularProgressIndicator), findsNothing); + }); + + testWidgets('handles completion before the first fade finishes', ( + tester, + ) async { + final operation = Completer(); + await tester.pumpWidget(futureOverlay(operation.future)); + await tester.pump(const Duration(milliseconds: 150)); + operation.complete(); + await finishFade(tester); + expect(find.byType(CircularProgressIndicator), findsNothing); + }); + }); + + group('switching visibility controls', () { + for (final isLoading in [false, true]) { + for (final completed in [false, true]) { + testWidgets( + 'switches from ${completed ? 'completed' : 'pending'} future to isLoading=$isLoading', + (tester) async { + final operation = Completer(); + await tester.pumpWidget(futureOverlay(operation.future)); + await finishFade(tester); + if (completed) { + operation.complete(); + await finishFade(tester); + } + await tester.pumpWidget(manualOverlay(isLoading)); + await finishFade(tester); + expect( + find.byType(CircularProgressIndicator), + isLoading ? findsOneWidget : findsNothing, + ); + + if (!completed) { + operation.complete(); + await finishFade(tester); + expect( + find.byType(CircularProgressIndicator), + isLoading ? findsOneWidget : findsNothing, + ); + } + }, + ); + } + + testWidgets('switches from isLoading=$isLoading to a future', ( + tester, + ) async { + final operation = Completer(); + await tester.pumpWidget(manualOverlay(isLoading)); + await finishFade(tester); + await tester.pumpWidget(futureOverlay(operation.future)); + await finishFade(tester); + expect(find.byType(CircularProgressIndicator), findsOneWidget); + operation.complete(); + await finishFade(tester); + expect(find.byType(CircularProgressIndicator), findsNothing); + }); + } + }); + + group('existing overlay behaviour', () { + testWidgets('fades in and out over 300 milliseconds', (tester) async { + await tester.pumpWidget(manualOverlay(false)); + await tester.pumpWidget(manualOverlay(true)); + double opacity() => tester + .widget(find.byType(FadeTransition).last) + .opacity + .value; + expect(opacity(), 0); + await tester.pump(const Duration(milliseconds: 150)); + expect(opacity(), closeTo(0.5, 0.01)); + await tester.pump(const Duration(milliseconds: 150)); + expect(opacity(), 1); + + await tester.pumpWidget(manualOverlay(false)); + await tester.pump(const Duration(milliseconds: 150)); + expect(opacity(), closeTo(0.5, 0.01)); + await tester.pump(const Duration(milliseconds: 150)); + expect(opacity(), closeTo(0, 0.01)); + await tester.pump(const Duration(milliseconds: 1)); expect(find.byType(CircularProgressIndicator), findsNothing); }); + + testWidgets( + 'blocks child taps through fade-out and restores them afterwards', + (tester) async { + var taps = 0; + Widget app(bool loading) => MaterialApp( + home: LoadingOverlay( + isLoading: loading, + child: Align( + alignment: Alignment.topLeft, + child: GestureDetector( + onTap: () => taps++, + child: const SizedBox( + key: Key('tap-target'), + width: 100, + height: 100, + child: ColoredBox(color: Colors.red), + ), + ), + ), + ), + ); + await tester.pumpWidget(app(false)); + final position = tester.getCenter(find.byKey(const Key('tap-target'))); + await tester.tapAt(position); + expect(taps, 1); + await tester.pumpWidget(app(true)); + await tester.tapAt(position); + expect(taps, 1); + await finishFade(tester); + await tester.tapAt(position); + expect(taps, 1); + await tester.pumpWidget(app(false)); + await tester.pump(const Duration(milliseconds: 150)); + await tester.tapAt(position); + expect(taps, 1); + await tester.pump(const Duration(milliseconds: 151)); + await tester.tapAt(position); + expect(taps, 2); + }, + ); + + testWidgets('preserves child state across rapid loading changes', ( + tester, + ) async { + Widget app(bool loading) => MaterialApp( + home: LoadingOverlay( + isLoading: loading, + child: Form(child: const Text('form')), + ), + ); + await tester.pumpWidget(app(false)); + final childState = tester.state(find.byType(Form)); + await tester.pumpWidget(app(true)); + expect(tester.state(find.byType(Form)), same(childState)); + await tester.pump(const Duration(milliseconds: 100)); + await tester.pumpWidget(app(false)); + await tester.pump(const Duration(milliseconds: 50)); + await tester.pumpWidget(app(true)); + await finishFade(tester); + expect(find.byType(CircularProgressIndicator), findsOneWidget); + expect(tester.state(find.byType(Form)), same(childState)); + await tester.pumpWidget(app(false)); + await finishFade(tester); + expect(find.byType(CircularProgressIndicator), findsNothing); + expect(tester.state(find.byType(Form)), same(childState)); + }); + + for (final useFuture in [false, true]) { + testWidgets('honours custom colour and indicator (future=$useFuture)', ( + tester, + ) async { + const indicator = Text('custom progress'); + const color = Color(0x40800000); + final operation = Completer(); + await tester.pumpWidget( + MaterialApp( + home: useFuture + ? LoadingOverlay.withFuture( + future: operation.future, + color: color, + progressIndicator: indicator, + child: const Text('child'), + ) + : const LoadingOverlay( + isLoading: true, + color: color, + progressIndicator: indicator, + child: Text('child'), + ), + ), + ); + expect(find.text('custom progress'), findsOneWidget); + expect(find.byType(CircularProgressIndicator), findsNothing); + expect( + find.byWidgetPredicate( + (widget) => widget is ColoredBox && widget.color == color, + ), + findsOneWidget, + ); + }); + } + + testWidgets('preserves the default backdrop and white indicator', ( + tester, + ) async { + await tester.pumpWidget(manualOverlay(true)); + expect( + find.byWidgetPredicate( + (widget) => + widget is ColoredBox && widget.color == const Color(0x80000000), + ), + findsOneWidget, + ); + final indicator = tester.widget( + find.byType(CircularProgressIndicator), + ); + expect(indicator.valueColor!.value, Colors.white); + }); + + for (final brightness in [Brightness.light, Brightness.dark]) { + testWidgets('inherits the ${brightness.name} Material indicator theme', ( + tester, + ) async { + await tester.pumpWidget( + MaterialApp( + theme: ThemeData( + brightness: brightness, + progressIndicatorTheme: const ProgressIndicatorThemeData( + color: Colors.red, + strokeWidth: 7, + constraints: BoxConstraints.tightFor(width: 48, height: 48), + ), + ), + home: const LoadingOverlay(isLoading: true, child: Text('child')), + ), + ); + + final indicator = find.byType(CircularProgressIndicator); + expect(tester.getSize(indicator), const Size(48, 48)); + expect(Theme.of(tester.element(indicator)).brightness, brightness); + expect( + tester.widget(indicator).valueColor!.value, + Colors.white, + ); + expect(indicator, paints..arc(color: Colors.white, strokeWidth: 7)); + }); + } }); }