creativecreatorormaybenot
Committed by GitHub

Set up federated plugin (#42)

* Federated setup

* Add .github

* Revert "Merge branch 'master' into federated-plugin"

This reverts commit d78b1423272b1c9bc0549fdd87efb4c3fef0019a.

* Init platform interface

* Setup wakelock_web

* Setup wakelock

* Cleanup

* Add pigeons

* Implement Android

* Implement platform interface

* Test platform interface

* wakelock_platform_interface initial release

* Main README

* wakelock README

* wakelock tests

* Integration testing

* iOS implementation

* Finish wakelock

* Implement web

* Web tests

* comment

* Web dependency

* Add checks

* Fix checks

* Relative here

* reorder

* Skip pub get

* Desperation

* l

* Fix checks

* Add pana

* Pana relative path

* Add tests

* Version

* disable web checks

* Complete actions
Showing 129 changed files with 3133 additions and 777 deletions
# Contributing guide
## Steps
The following steps are based on a version of [flutter/plugin's contributing guide](https://github.com/flutter/plugins/blob/2ea66626c245a4373a6e07706ab2e7d471e25bd6/CONTRIBUTING.md).
### Creating a fork
- If you have not yet configured your machine with an SSH key that is known to GitHub, then follow [GitHub's directions](https://help.github.com/articles/generating-ssh-keys/) to generate an SSH key.
- Fork [this repository](https://github.com/creativecreatorormaybenot/wakelock) using the "Fork" button in the upper right corner of the repository's GitHub page.
- `git clone git@github.com:<github_user_name>/wakelock.git`
- `cd wakelock`
- `git remote add upstream git@github.com:creativecreatorormaybenot/wakelock.git`
This ensures that `git fetch upstream` is possible to fetch from this remote repository instead of from your own fork to get the latest changes.
### Create pull requests
- Fetch the latest repo state: `git fetch upstream`
- Create a feature branch: `git checkout upstream/master -b <name_of_your_branch>`
- Now, you can change the code necessary for your patch.
Make sure that you bump the version in [`pubspec.yaml`][pubspec]. You **must** bump the Pubspec
version when a new package version should be released and edit the `CHANGELOG.md` of the package
accordingly.
The version format needs to follow [Dart's semantic versioning][dart semver]. You need to take
[caret syntax][] into consideration when landing breaking changes.
- Commit your changes: `git commit -am "<commit_message>"`
- Push your changes: `git push origin <name_of_your_branch>`
After having followed these steps, you are ready to [create a pull request](https://help.github.com/en/articles/creating-a-pull-request-from-a-fork).
The GitHub interface makes this very easy by providing a button on your fork page that creates a pull request with changes from a recently pushed to branch.
Alternatively, you can also use `git pull-request` via [GitHub hub](https://hub.github.com/).
### Notes
- You should remember to exclude all files and directories your IDE might generate using the `.gitignore` files (if they do not already contain them for your IDE).
If you feel like you can make useful additions to any of the `.gitignore` files, you can include them in your pull request, potentially with an explanation.
- It is probably easier for you to run the integration tests for the plugin locally using `flutter drive --target=test_driver/app.dart` in the `example` directory
before opening a pull request (CI also runs the integration tests).
This way you can ensure that any changes you have made work properly. Furthermore, you might also want to add some tests if you implement new functionality.
- You should also run `dart format .` in the root directory and make sure that `flutter analyze` does not report any errors.
[dart semver]: https://dart.dev/tools/pub/versioning#semantic-versions
[caret syntax]: https://dart.dev/tools/pub/dependencies#caret-syntax
... ...
## Description
*A clear and concise description of what your PR accomplishes.*
... ...
... ... @@ -11,11 +11,14 @@ on:
- '**/pubspec.yaml'
- '**/test/**'
- '**/test_driver/**'
- '**/assets/**'
- '**/integration_test/**'
jobs:
analyze:
timeout-minutes: 7
runs-on: ${{ matrix.os }}
name: Format check & analysis (${{ matrix.channel }} on ${{ matrix.os }})
name: Analysis of ${{ matrix.package }} (${{ matrix.channel }}; ${{ matrix.os }})
strategy:
matrix:
os:
... ... @@ -24,6 +27,10 @@ jobs:
- 'stable'
- 'beta'
- 'dev'
package:
- 'wakelock'
- 'wakelock_platform_interface'
- 'wakelock_web'
fail-fast: false
steps:
... ... @@ -31,37 +38,36 @@ jobs:
- uses: subosito/flutter-action@v1.3.2
with:
channel: ${{ matrix.channel }}
- name: Setup projects (root & example)
run: |
flutter pub get
cd example
flutter create .
rm -rf test
flutter pub get
cd ..
- run: flutter pub get
working-directory: ${{ matrix.package }}
- name: Check format
run: flutter format . --set-exit-if-changed --fix
working-directory: ${{ matrix.package }}
run: dart format . --set-exit-if-changed
- run: flutter analyze
working-directory: ${{ matrix.package }}
test:
# Not using the conditional as jobs are not re-run when the draft status changes.
#if: github.event.pull_request.draft == false
timeout-minutes: 14
runs-on: macos-latest
name: Unit & integration tests (${{ matrix.channel }} on ${{ matrix.device }})
name: Testing of ${{ matrix.package }} (${{ matrix.channel }}; ${{ matrix.device }})
strategy:
matrix:
device:
- 'iPhone 11 Pro Max (13.7)'
- 'Android'
channel:
- 'stable'
- 'beta'
- 'dev'
package:
- 'wakelock'
- 'wakelock_platform_interface'
# Web tests do not work for now.
# - 'wakelock_web'
fail-fast: false
steps:
- name: Start iOS simulator
if: contains(matrix.device, 'iPhone')
if: matrix.package == 'wakelock'
run: |
xcrun instruments -s
UDID=$(
... ... @@ -76,25 +82,18 @@ jobs:
- uses: subosito/flutter-action@v1.3.2
with:
channel: ${{ matrix.channel }}
- name: Setup projects (root & example)
run: |
flutter pub get
cd example
flutter create .
rm -rf test
flutter pub get
cd ..
- name: Run unit tests
- run: flutter pub get
working-directory: ${{ matrix.package }}
- name: Run unit tests (tester)
if: matrix.package != 'wakelock_web'
run: flutter test
- name: Run integration tests on iOS
if: contains(matrix.device, 'iPhone')
working-directory: ${{ matrix.package }}
- name: Run unit tests (chrome)
if: matrix.package == 'wakelock_web'
run: flutter test --platform chrome
working-directory: ${{ matrix.package }}
- name: Integration tests on iOS
if: matrix.package == 'wakelock'
run: |
cd example
flutter drive --target=test_driver/app.dart
- name: Run integration tests on Android
if: contains(matrix.device, 'Android') && false # Need to run locally for now.
uses: reactivecircus/android-emulator-runner@v2.5.0
with:
api-level: 29
disable-animations: false
script: cd example && flutter drive --target=test_driver/app.dart
cd wakelock/example
flutter drive --driver=test_driver/integration_test.dart --target=integration_test/wakelock_test.dart
... ...
... ... @@ -11,15 +11,25 @@ on:
- '**/pubspec.yaml'
- '**/test/**'
- '**/test_driver/**'
- '**/assets/**'
- '**/integration_test/**'
jobs:
configure:
# Not using the conditional as jobs are not re-run when the draft status changes.
#if: github.event.pull_request.draft == false
timeout-minutes: 9
runs-on: ubuntu-latest
name: Configuration of ${{ matrix.package }}
strategy:
matrix:
package:
- 'wakelock'
- 'wakelock_platform_interface'
- 'wakelock_web'
fail-fast: false
steps:
- uses: actions/checkout@v2.3.3
- uses: axel-op/dart-package-analyzer@v3
with:
relativePath: ${{ matrix.package }}
githubToken: ${{ secrets.GITHUB_TOKEN }}
... ...
name: Publish
name: Publish packages and releases
on:
push:
branches:
- master
paths:
# Can only publish the package when the Pubspec changed, i.e. specifically the package
# version, however, we can ensure that this is the case in code review.
- '*/pubspec.yaml'
jobs:
checks:
runs-on: macos-latest
name: Check format, analyze, and test
pana:
timeout-minutes: 9
runs-on: ubuntu-latest
name: Configuration of ${{ matrix.package }}
strategy:
matrix:
package:
- 'wakelock'
- 'wakelock_platform_interface'
- 'wakelock_web'
fail-fast: false
steps:
- uses: actions/checkout@v2.3.3
- uses: subosito/flutter-action@v1.3.2
with:
channel: stable
- name: Setup projects (root & example)
run: |
flutter pub get
cd example
flutter create .
rm -rf test
flutter pub get
cd ..
- name: Check format
run: flutter format . --set-exit-if-changed --fix
- run: flutter analyze
- name: Run unit tests
run: flutter test
- name: Run integration tests on Android
if: false # Need to run locally for now.
uses: reactivecircus/android-emulator-runner@v2.5.0
- uses: axel-op/dart-package-analyzer@v3
with:
api-level: 29
disable-animations: false
script: cd example && flutter drive --target=test_driver/app.dart
relativePath: ${{ matrix.package }}
githubToken: ${{ secrets.GITHUB_TOKEN }}
publish:
needs: checks
needs: pana
timeout-minutes: 2
runs-on: ubuntu-latest
name: Publish plugin
name: Publishing of ${{ matrix.package }}
strategy:
matrix:
package:
- 'wakelock'
- 'wakelock_platform_interface'
- 'wakelock_web'
fail-fast: false
steps:
- uses: actions/checkout@v2.3.3
- uses: sakebook/actions-flutter-pub-publisher@v1.3.1
with:
relativePath: ${{ matrix.package }}
credential: ${{ secrets.PUB_CREDENTIALS }}
flutter_package: true
skip_test: true
tag-release:
needs: publish
timeout-minutes: 1
runs-on: ubuntu-latest
name: Tagging of ${{ matrix.package }}
strategy:
matrix:
package:
- wakelock
- wakelock_web
- wakelock_platform_interface
steps:
- uses: actions/checkout@v2
with:
fetch-depth: 2
- name: Check package Pubspec
id: pubspec
run: |
set +e
git diff-tree --no-commit-id --name-only -r ${{ github.sha }} | grep '${{ matrix.package }}/pubspec.yaml' &> /dev/null
echo ::set-output name=changed::$?
set -e
- name: Extract package version
if: steps.pubspec.outputs.changed == 0
run: |
cd ${{ matrix.package }}
echo ::set-env name=VERSION::"$(awk '{if ($1 ~ /^version:/) print $2}' pubspec.yaml)"
- name: Create Release
if: steps.pubspec.outputs.changed == 0
id: create_release
uses: actions/create-release@v1.1.4
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
tag_name: ${{ matrix.package }}-v${{ env.VERSION }}
release_name: ${{ matrix.package }} v${{ env.VERSION }}
draft: false
prerelease: false
\ No newline at end of file
... ...
.DS_Store
.dart_tool
.packages
.pub
build
# Cleanliness
pubspec.lock
**.iml
.idea
.metadata
* @creativecreatorormaybenot
# Steps
The following steps are based on a version of [flutter/plugin's contributing guide](https://github.com/flutter/plugins/blob/2ea66626c245a4373a6e07706ab2e7d471e25bd6/CONTRIBUTING.md).
## Creating a fork
* If you have not yet configured your machine with an SSH key that is known to GitHub, then follow [GitHub's directions](https://help.github.com/articles/generating-ssh-keys/) to generate an SSH key.
* Fork [this repository](https://github.com/creativecreatorormaybenot/wakelock) using the "Fork" button in the upper right corner of the repository's GitHub page.
* `git clone git@github.com:<github_user_name>/wakelock.git`
* `cd wakelock`
* `git remote add upstream git@github.com:creativecreatorormaybenot/wakelock.git`
This ensures that `git fetch upstream` is possible to fetch from this remote repository instead of from your own fork to get the latest changes.
## Creating a patch
* `git fetch upstream`
* `git checkout upstream/master -b <name_of_your_branch>`
* Now, you can change the code necessary for your patch.
Make sure that you bump the version in [`pubspec.yaml`](https://github.com/creativecreatorormaybenot/wakelock/blob/master/pubspec.yaml)
and add an entry to [`CHANGELOG.md`](https://github.com/creativecreatorormaybenot/wakelock/blob/master/CHANGELOG.md).
The version format is `r.M.m+p`. You will want to increment one of these values and which one you increment depends on the impact of your patch:
`p` for simple patches, `m` for minor versions, `M` for major versions, and `r` for released. Do not forget to reset the values to the right of the value you incremented to 0. You should omit `+0`.
* `git commit -am "<commit_message>"`
* `git push origin <name_of_your_branch>`
After having followed these steps, you are ready to [create a pull request](https://help.github.com/en/articles/creating-a-pull-request-from-a-fork).
The GitHub interface makes this very easy by providing a button on your fork page that creates a pull request with changes from a recently pushed to branch.
Alternatively, you can also use `git pull-request` via [GitHub hub](https://hub.github.com/).
# Notes
* You should remember to exclude all files and directories your IDE might generate using the `.gitignore` files (if they do not already contain them for your IDE).
If you feel like you can make useful additions to any of the `.gitignore` files, you can include them in your pull request, potentially with an explanation.
* It is probably easier for you to run the integration tests for the plugin locally using `flutter drive --target=test_driver/app.dart` in the `example` directory
before opening a pull request (CI also runs the integration tests).
This way you can ensure that any changes you have made work properly. Furthermore, you might also want to add some tests if you implement new functionality.
* You should also run `flutter format lib example --fix` in the root directory and make sure that `flutter analyze` does not report any errors.
# Wakelock [![](https://github.com/creativecreatorormaybenot/wakelock/workflows/Publish/badge.svg)](https://github.com/creativecreatorormaybenot/wakelock/actions) [![](https://img.shields.io/github/stars/creativecreatorormaybenot/wakelock.svg)](https://github.com/creativecreatorormaybenot/wakelock) [![](https://img.shields.io/pub/v/wakelock.svg)](https://pub.dev/packages/wakelock)
# Wakelock [![Publish workflow](https://github.com/creativecreatorormaybenot/wakelock/workflows/Publish/badge.svg)](https://github.com/creativecreatorormaybenot/wakelock/actions) [![GitHub stars](https://img.shields.io/github/stars/creativecreatorormaybenot/wakelock.svg)](https://github.com/creativecreatorormaybenot/wakelock) [![Pub version](https://img.shields.io/pub/v/wakelock.svg)](https://pub.dev/packages/wakelock)
This Flutter plugin allows you to enable and toggle the screen wakelock on Android and iOS, which prevents the screen from turning off automatically.
Essentially, this allows you to keep the device awake, i.e. prevent the device from sleeping.
Wakelock is Flutter plugin that allows you to keep the device screen awake, i.e. prevent the screen from sleeping on Android, iOS, and web.
## Usage
## Getting started
To use this plugin, follow the [installing guide](https://pub.dev/packages/wakelock#-installing-tab-).
To learn more about the plugin and getting started, you can view [the main package (`wakelock`) README](https://github.com/creativecreatorormaybenot/wakelock/blob/master/wakelock/README.md).
### Implementation
### Plugin structure
Everything in this plugin is controlled via the [`Wakelock` class](https://pub.dev/documentation/wakelock/latest/wakelock/Wakelock-class.html).
If you want to enable the wakelock, i.e. keep the device awake, you can simply call [`Wakelock.enable`](https://pub.dev/documentation/wakelock/latest/wakelock/Wakelock/enable.html)
and to disable it again, you can use [`Wakelock.disable`](https://pub.dev/documentation/wakelock/latest/wakelock/Wakelock/disable.html):
The `wakelock` plugin uses the [federated plugins approach](https://flutter.dev/docs/development/packages-and-plugins/developing-packages#federated-plugins).
For this plugin, it means that the basic API is defined using [`pigeon`](https://pub.dev/packages/pigeon). The pigeon files can be found in the [`pigeons` directory](https://github.com/creativecreatorormaybenot/wakelock/tree/master/wakelock/pigeons)
in the main package. The API is defined in Dart in the [`wakelock_platform_interface` package](https://github.com/creativecreatorormaybenot/wakelock/tree/master/wakelock_platform_interface).
Furthermore, the Android and iOS implementations can be found in the main package, while the web implementation is in the [`wakelock_web` package](https://github.com/creativecreatorormaybenot/wakelock/tree/master/wakelock_platform_interface).
```dart
import 'package:wakelock/wakelock.dart';
// ...
The packages in this repo are the following:
// The following line will enable the Android and iOS wakelock.
Wakelock.enable();
| Package | Implementations |
| ------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------- |
| [`wakelock`](https://github.com/creativecreatorormaybenot/wakelock/tree/master/wakelock) | Main plugin package + Android & iOS implementations |
| [`wakelock_platform_interface`](https://github.com/creativecreatorormaybenot/wakelock/tree/master/wakelock_platform_interface) | Basic API definition & message handling |
| [`wakelock_web`](https://github.com/creativecreatorormaybenot/wakelock/tree/master/wakelock_web) | Web implementation |
// The next line disables the wakelock again.
Wakelock.disable();
```
## Contributing
For more advanced usage, you can pass a `bool` to [`Wakelock.toggle`](https://pub.dev/documentation/wakelock/latest/wakelock/Wakelock/toggle.html) to enable or disable the wakelock
and also retrieve the current wakelock status using [`Wakelock.isEnabled`](https://pub.dev/documentation/wakelock/latest/wakelock/Wakelock/isEnabled.html):
If you want to contribute to this plugin, follow the [contributing guide](https://github.com/creativecreatorormaybenot/wakelock/blob/master/.github/CONTRIBUTING.md).
```dart
import 'package:wakelock/wakelock.dart';
// ...
## Origin
// The following lines of code toggle the wakelock based on a bool value.
bool on = true;
// The following statement enables the wakelock.
Wakelock.toggle(on: on);
on = false;
// The following statement disables the wakelock.
Wakelock.toggle(on: on);
// If you want to retrieve the current wakelock status,
// you will have to be in an async scope
// to await the Future returned by isEnabled.
bool isEnabled = await Wakelock.isEnabled;
```
If you want to wait for the wakelock toggle on Android or iOS to complete (which takes an insignificant amount of time),
you can also `await` any of `Wakelock.enable`, `Wakelock.disable`, and `Wakelock.toggle`.
## Notes
This plugin is originally based on [`screen`](https://pub.dev/packages/screen).
Originally, this plugin was based on [`screen`](https://pub.dev/packages/screen).
Specifically, the wakelock functionality was extracted into this plugin due to lack of maintenance by the author of the `screen` plugin.
If you want to contribute to this plugin, follow the [contributing guide](https://github.com/creativecreatorormaybenot/wakelock/blob/master/CONTRIBUTING.md).
Today, the `wakelock` plugin has been completely refreshed (using latest Flutter standards and platform integration) with added web support.
... ...
include: package:pedantic/analysis_options.1.9.2.yaml
linter:
rules:
- public_member_api_docs
\ No newline at end of file
... ...
*.iml
.gradle
local.properties
.DS_Store
build
captures
.idea
package creativecreatorormaybenot.wakelock
import androidx.annotation.NonNull
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.embedding.engine.plugins.activity.ActivityAware
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result
import io.flutter.plugin.common.PluginRegistry.Registrar
public class WakelockPlugin : FlutterPlugin, MethodCallHandler, ActivityAware {
private lateinit var channel: MethodChannel
override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
channel = MethodChannel(flutterPluginBinding.binaryMessenger, "wakelock")
channel.setMethodCallHandler(this)
wakelock = Wakelock()
}
private var registrar: Registrar? = null
// This static function is optional and equivalent to onAttachedToEngine. It supports the old
// pre-Flutter-1.12 Android projects. You are encouraged to continue supporting
// plugin registration via this function while apps migrate to use the new Android APIs
// post-flutter-1.12 via https://flutter.dev/go/android-project-migration.
//
// It is encouraged to share logic between onAttachedToEngine and registerWith to keep
// them functionally equivalent. Only one of onAttachedToEngine or registerWith will be called
// depending on the user's project. onAttachedToEngine or registerWith must both be defined
// in the same class.
companion object {
@JvmStatic
fun registerWith(registrar: Registrar) {
val channel = MethodChannel(registrar.messenger(), "wakelock")
val plugin = WakelockPlugin()
plugin.registrar = registrar
plugin.wakelock = Wakelock()
channel.setMethodCallHandler(plugin)
}
}
private var wakelock: Wakelock? = null
override fun onMethodCall(@NonNull call: MethodCall, @NonNull result: Result) {
if (registrar != null) wakelock!!.activity = registrar!!.activity()
when (call.method) {
"toggle" -> {
wakelock!!.toggle(call.argument<Boolean>("enable")!!, result)
}
"isEnabled" -> {
wakelock!!.isEnabled(result)
}
else -> {
result.notImplemented()
}
}
if (registrar != null) wakelock!!.activity = null
}
override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) {
channel.setMethodCallHandler(null)
wakelock = null
registrar = null
}
override fun onAttachedToActivity(binding: ActivityPluginBinding) {
wakelock?.activity = binding.activity
}
override fun onDetachedFromActivity() {
wakelock?.activity = null
}
override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) {
onAttachedToActivity(binding)
}
override fun onDetachedFromActivityForConfigChanges() {
onDetachedFromActivity()
}
}
# Example
This is a basic example demonstrating the functionality of the wakelock plugin, including enabling & disabling the wakelock and also retrieving the current wakelock status using a `FutureBuilder`.
If you want to run this example app, you need to run `flutter create .` in the `example` directory (`cd example` from the plugin directory) first. This is also necessary when running the Flutter Driver tests.
See [`example/lib/main.dart`](https://github.com/creativecreatorormaybenot/wakelock/blob/master/example/lib/main.dart).
## Integration testing
For integration testing, this plugin uses [`example/test_driver`](https://github.com/creativecreatorormaybenot/wakelock/tree/master/example/test_driver). The project has a setup for continuous integration, which will run the integration tests to confirm that the plugin is working correctly.
The status for the latest commit is [![build status](https://travis-ci.com/creativecreatorormaybenot/wakelock.svg?branch=master)](https://travis-ci.com/creativecreatorormaybenot/wakelock).
If you want to run the integration tests yourself, you can run `flutter drive --target=test_driver/app.dart` from the `example` directory.
import 'dart:async';
import 'package:flutter_driver/driver_extension.dart';
import 'package:test/test.dart';
import 'package:wakelock/wakelock.dart';
import 'package:wakelock_example/main.dart' as example;
void main() {
final completer = Completer<String>();
enableFlutterDriverExtension(handler: (message) => completer.future);
// The example app tests need this.
example.main();
var result = 'success';
final _expect = (dynamic value, Matcher matcher) {
if (!matcher.matches(value, null)) {
result = 'failure';
}
expect(value, matcher);
};
group('wakelock bare platform testing', () {
tearDownAll(() => completer.complete(result));
test('toggle on', () async {
await Wakelock.toggle(on: true);
_expect(await Wakelock.isEnabled, isTrue);
});
test('toggle off', () async {
await Wakelock.toggle(on: false);
_expect(await Wakelock.isEnabled, isFalse);
});
});
}
import 'package:flutter_driver/flutter_driver.dart';
import 'package:test/test.dart';
void main() async {
FlutterDriver driver;
String bareTestingResult;
setUpAll(() async {
driver = await FlutterDriver.connect();
bareTestingResult =
await driver.requestData('', timeout: const Duration(minutes: 1));
});
tearDownAll(() => driver?.close());
group('example app', () {
test('wakelock is disabled at start', () async {
await driver._expectEnabled(isFalse);
});
test('enable wakelock', () async {
// Use the button in the example app instead of a direct plugin call.
await driver.tap(find.text('enable wakelock'));
await driver._expectEnabled(isTrue);
});
test('disable wakelock', () async {
// Use the button in the example app instead of a direct plugin call.
await driver.tap(find.text('disable wakelock'));
await driver._expectEnabled(isFalse);
});
});
test('wakelock bare platform testing', () async {
expect(bareTestingResult, equals('success'));
});
}
extension on FlutterDriver {
Future<bool> _finds(SerializableFinder finder) async {
try {
await waitFor(finder, timeout: const Duration(milliseconds: 420));
return true;
} catch (_) {
return false;
}
}
Future<void> _expectEnabled(Matcher matcher) async {
// Check the widget in the example app.
final result = await _finds(find.text(
'wakelock is currently ${matcher == isTrue ? 'enabled' : 'disabled'}'));
expect(result, isTrue);
}
}
#import "WakelockPlugin.h"
@implementation WakelockPlugin
+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar>*)registrar {
FlutterMethodChannel* channel = [FlutterMethodChannel
methodChannelWithName:@"wakelock"
binaryMessenger:[registrar messenger]];
WakelockPlugin* instance = [[WakelockPlugin alloc] init];
[registrar addMethodCallDelegate:instance channel:channel];
}
- (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result {
if ([@"toggle" isEqualToString:call.method]) {
NSNumber *enable = call.arguments[@"enable"];
NSNumber *enabled = [NSNumber numberWithBool:[[UIApplication sharedApplication] isIdleTimerDisabled]];
if([enable isEqualToNumber:enabled]) {
result(nil);
} else {
[[UIApplication sharedApplication] setIdleTimerDisabled:enable.boolValue];
result(nil);
}
} else if ([@"isEnabled" isEqualToString:call.method]) {
result([NSNumber numberWithBool:[[UIApplication sharedApplication] isIdleTimerDisabled]]);
} else {
result(FlutterMethodNotImplemented);
}
}
@end
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
/// To enable the wakelock, you can use [Wakelock.enable] and to disable it,
/// you can call [Wakelock.disable].
/// You do not need to worry about making redundant calls, e.g. calling [Wakelock.enable]
/// when the wakelock is already enabled as the plugin handles this for you, i.e. it checks
/// the status to determine if the wakelock is already enabled or disabled.
/// If you want the flexibility to pass a [bool] to control whether the wakelock should be
/// enabled or disabled, you can use [Wakelock.toggle].
///
/// The [Wakelock.isEnabled] property allows you to retrieve the current wakelock
/// status from Android or iOS.
class Wakelock {
static const MethodChannel _channel = MethodChannel('wakelock');
/// This can simply be called using `Wakelock.enable()` and does not return anything.
/// You can await the [Future] to wait for the operation to complete.
static Future<void> enable() =>
_channel.invokeMethod('toggle', {'enable': true});
/// This can simply be called using `Wakelock.disable()` and does not return anything.
/// You can await the [Future] to wait for the operation to complete.
static Future<void> disable() =>
_channel.invokeMethod('toggle', {'enable': false});
/// You can simply use this function to toggle the wakelock using a [bool] value.
///
/// ```dart
/// // This line keeps the screen on.
/// Wakelock.toggle(on: true);
///
/// bool turnOnWakelock = false;
/// // The following line disables the wakelock.
/// Wakelock.toggle(on: turnOnWakelock);
/// ```
///
/// You can await the [Future] to wait for the operation to complete.
static Future<void> toggle({@required bool on}) {
assert(on != null,
'The [on] parameter cannot be null when toggling the wakelock.');
return _channel.invokeMethod('toggle', {'enable': on});
}
/// If you want to retrieve the current wakelock status, you will have to call [Wakelock.isEnabled]
/// and await its result: `bool isEnabled = await Wakelock.isEnabled()`
static Future<bool> get isEnabled => _channel.invokeMethod('isEnabled');
}
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:wakelock/wakelock.dart';
void main() {
const MethodChannel channel = MethodChannel('wakelock');
TestWidgetsFlutterBinding.ensureInitialized();
setUp(() {
var enabled = false;
channel.setMockMethodCallHandler((MethodCall methodCall) async {
switch (methodCall.method) {
case 'toggle':
enabled = methodCall.arguments['enable'];
break;
case 'enable':
enabled = true;
break;
case 'disable':
enabled = false;
break;
case 'isEnabled':
return enabled;
default:
throw ArgumentError.value(methodCall.method);
}
return null;
});
});
tearDown(() {
channel.setMockMethodCallHandler(null);
});
test('isEnabled', () async {
expect(await Wakelock.isEnabled, isFalse);
});
group('toggle', () {
test('on', () async {
await Wakelock.toggle(on: true);
expect(await Wakelock.isEnabled, isTrue);
});
test('off', () async {
await Wakelock.toggle(on: false);
expect(await Wakelock.isEnabled, isFalse);
});
test('non-null assertion', () async {
expect(() async => await Wakelock.toggle(on: null), throwsAssertionError);
});
});
test('enable', () async {
await Wakelock.enable();
expect(await Wakelock.isEnabled, isTrue);
});
test('disable', () async {
await Wakelock.disable();
expect(await Wakelock.isEnabled, isFalse);
});
}
# Miscellaneous
*.class
*.log
*.pyc
*.swp
.DS_Store
.atom/
.buildlog/
.history
.svn/
.metadata
# IntelliJ related
*.iml
*.ipr
*.iws
.idea/
# The .vscode folder contains launch configuration and tasks you configure in
# VS Code which you may wish to be included in version control, so this line
# is commented out by default.
#.vscode/
# Flutter/Dart/Pub related
**/doc/api/
.dart_tool/
.flutter-plugins
.flutter-plugins-dependencies
.packages
.pub-cache/
.pub/
build/
pubspec.lock
# Android related
**/android/**/gradle-wrapper.jar
**/android/.gradle
**/android/captures/
**/android/gradlew
**/android/gradlew.bat
**/android/local.properties
**/android/**/GeneratedPluginRegistrant.java
# iOS/XCode related
**/ios/**/*.mode1v3
**/ios/**/*.mode2v3
**/ios/**/*.moved-aside
**/ios/**/*.pbxuser
**/ios/**/*.perspectivev3
**/ios/**/*sync/
**/ios/**/.sconsign.dblite
**/ios/**/.tags*
**/ios/**/.vagrant/
**/ios/**/DerivedData/
**/ios/**/Icon?
**/ios/**/Pods/
**/ios/**/.symlinks/
**/ios/**/profile
**/ios/**/xcuserdata
**/ios/.generated/
**/ios/Flutter/App.framework
**/ios/Flutter/Flutter.framework
**/ios/Flutter/Flutter.podspec
**/ios/Flutter/Generated.xcconfig
**/ios/Flutter/app.flx
**/ios/Flutter/app.zip
**/ios/Flutter/flutter_assets/
**/ios/Flutter/flutter_export_environment.sh
**/ios/ServiceDefinitions.json
**/ios/Runner/GeneratedPluginRegistrant.*
# Exceptions to above rules.
!**/ios/**/default.mode1v3
!**/ios/**/default.mode2v3
!**/ios/**/default.pbxuser
!**/ios/**/default.perspectivev3
... ...
## 0.2.0
* Added web support.
* Overhauled the plugin with the latest Flutter standards.
* Implemented federated plugin approach, adding `wakelock_platform_interface` and `wakelock_web`
dependencies.
* Removed support for the Android v1 APIs.
* *Deprecated* `Wakelock.isEnabled` in favor of `Wakelock.enabled`. The fact that it is a getter
should be enough and remove the need for the "is" context.
* *Deprecated* the `on` parameter in `Wakelock.toggle` in favor of the `enable` parameter, which
should be a more descriptive name.
## 0.1.4+2
* Fixed Gradle builds missing NonNull annotation.
... ...
# wakelock [![Pub version](https://img.shields.io/pub/v/wakelock.svg)](https://pub.dev/packages/wakelock) [![GitHub stars](https://img.shields.io/github/stars/creativecreatorormaybenot/wakelock.svg)](https://github.com/creativecreatorormaybenot/wakelock)
Plugin that allows you to keep the device screen awake, i.e. prevent the screen from sleeping on
Android, iOS, and web.
---
The plugin allows you to enable and toggle the screen wakelock on Android, iOS, and web, which
prevents the screen from turning off automatically.
Essentially, this allows you to keep the device awake, i.e. prevent the device from sleeping.
## Usage
To use this plugin, follow the [installing guide](https://pub.dev/packages/wakelock/install).
### Implementation
Everything in this plugin is controlled via the [`Wakelock` class](https://pub.dev/documentation/wakelock/latest/wakelock/Wakelock-class.html).
If you want to enable the wakelock, i.e. keep the device awake, you can simply call [`Wakelock.enable`](https://pub.dev/documentation/wakelock/latest/wakelock/Wakelock/enable.html)
and to disable it again, you can use [`Wakelock.disable`](https://pub.dev/documentation/wakelock/latest/wakelock/Wakelock/disable.html):
```dart
import 'package:wakelock/wakelock.dart';
// ...
// The following line will enable the Android and iOS wakelock.
Wakelock.enable();
// The next line disables the wakelock again.
Wakelock.disable();
```
For more advanced usage, you can pass a `bool` to [`Wakelock.toggle`](https://pub.dev/documentation/wakelock/latest/wakelock/Wakelock/toggle.html)
to enable or disable the wakelock and also retrieve the current wakelock status using
[`Wakelock.isEnabled`](https://pub.dev/documentation/wakelock/latest/wakelock/Wakelock/isEnabled.html):
```dart
import 'package:wakelock/wakelock.dart';
// ...
// The following lines of code toggle the wakelock based on a bool value.
bool enable = true;
// The following statement enables the wakelock.
Wakelock.toggle(enable: enable);
enable = false;
// The following statement disables the wakelock.
Wakelock.toggle(enable: enable);
// If you want to retrieve the current wakelock status,
// you will have to be in an async scope
// to await the Future returned by `enabled`.
bool wakelockEnabled = await Wakelock.enabled;
```
If you want to wait for the wakelock toggle to complete (which takes an insignificant amount of
time), you can also `await` any of `Wakelock.enable`, `Wakelock.disable`, and `Wakelock.toggle`.
## Learn more
If you want to learn more about how this plugin works, how to contribute, etc., you can read through
the [main README on GitHub](https://github.com/creativecreatorormaybenot/wakelock).
... ...
*.iml
.gradle
/local.properties
/.idea/workspace.xml
/.idea/libraries
.DS_Store
/build
/captures
... ...
group 'creativecreatorormaybenot.wakelock'
group 'creativemaybeno.wakelock'
version '1.0-SNAPSHOT'
buildscript {
... ... @@ -25,7 +25,7 @@ apply plugin: 'com.android.library'
apply plugin: 'kotlin-android'
android {
compileSdkVersion 28
compileSdkVersion 29
sourceSets {
main.java.srcDirs += 'src/main/kotlin'
... ... @@ -40,5 +40,4 @@ android {
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation "androidx.annotation:annotation:1.1.0"
}
... ...
org.gradle.jvmargs=-Xmx1536M
android.useAndroidX=true
android.enableJetifier=true
... ...
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="creativecreatorormaybenot.wakelock">
package="creativemaybeno.wakelock">
</manifest>
... ...
// Autogenerated from Pigeon (v0.1.7), do not edit directly.
// See also: https://pub.dev/packages/pigeon
package creativemaybeno.wakelock
import io.flutter.plugin.common.BasicMessageChannel
import io.flutter.plugin.common.BinaryMessenger
import io.flutter.plugin.common.StandardMessageCodec
import java.util.*
/** Generated class from Pigeon. */
object Messages {
private fun wrapError(exception: Exception): HashMap<*, *> {
val errorMap = HashMap<String, Any?>()
errorMap["message"] = exception.toString()
errorMap["code"] = null
errorMap["details"] = null
return errorMap
}
/** Generated class from Pigeon that represents data sent in messages. */
class ToggleMessage {
private var enable: Boolean? = null
fun getEnable(): Boolean? {
return enable
}
fun setEnable(setterArg: Boolean?) {
enable = setterArg
}
fun toMap(): HashMap<*, *> {
val toMapResult = HashMap<String, Any?>()
toMapResult["enable"] = enable
return toMapResult
}
companion object {
fun fromMap(map: HashMap<*, *>?): ToggleMessage {
val fromMapResult = ToggleMessage()
val enable = map!!["enable"]
fromMapResult.enable = enable as Boolean?
return fromMapResult
}
}
}
/** Generated class from Pigeon that represents data sent in messages. */
class IsEnabledMessage {
private var enabled: Boolean? = null
fun getEnabled(): Boolean? {
return enabled
}
fun setEnabled(setterArg: Boolean?) {
enabled = setterArg
}
fun toMap(): HashMap<*, *> {
val toMapResult = HashMap<String, Any?>()
toMapResult["enabled"] = enabled
return toMapResult
}
companion object {
fun fromMap(map: HashMap<*, *>): IsEnabledMessage {
val fromMapResult = IsEnabledMessage()
val enabled = map["enabled"]
fromMapResult.enabled = enabled as Boolean?
return fromMapResult
}
}
}
/** Generated interface from Pigeon that represents a handler of messages from Flutter. */
interface WakelockApi {
fun toggle(arg: ToggleMessage?)
val isEnabled: IsEnabledMessage
companion object {
/** Sets up an instance of `WakelockApi` to handle messages through the `binaryMessenger` */
fun setup(binaryMessenger: BinaryMessenger?, api: WakelockApi?) {
run {
val channel = BasicMessageChannel(binaryMessenger!!, "dev.flutter.pigeon.WakelockApi.toggle", StandardMessageCodec())
if (api != null) {
channel.setMessageHandler { message: Any?, reply: BasicMessageChannel.Reply<Any> ->
val wrapped = HashMap<String, HashMap<*, *>?>()
try {
val input = ToggleMessage.fromMap(message as HashMap<*, *>?)
api.toggle(input)
wrapped["result"] = null
} catch (exception: Exception) {
wrapped["error"] = wrapError(exception)
}
reply.reply(wrapped)
}
} else {
channel.setMessageHandler(null)
}
}
run {
val channel = BasicMessageChannel(binaryMessenger!!, "dev.flutter.pigeon.WakelockApi.isEnabled", StandardMessageCodec())
if (api != null) {
channel.setMessageHandler { message: Any?, reply: BasicMessageChannel.Reply<Any> ->
val wrapped = HashMap<String, HashMap<*, *>>()
try {
val output = api.isEnabled
wrapped["result"] = output.toMap()
} catch (exception: Exception) {
wrapped["error"] = wrapError(exception)
}
reply.reply(wrapped)
}
} else {
channel.setMessageHandler(null)
}
}
}
}
}
}
... ...
package creativecreatorormaybenot.wakelock
package creativemaybeno.wakelock
import android.app.Activity
import android.view.WindowManager
import io.flutter.plugin.common.MethodChannel
import creativemaybeno.wakelock.Messages.IsEnabledMessage
import creativemaybeno.wakelock.Messages.ToggleMessage
internal class Wakelock {
var activity: Activity? = null
... ... @@ -11,32 +12,30 @@ internal class Wakelock {
get() = activity!!.window.attributes.flags and
WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON != 0
fun toggle(enable: Boolean, result: MethodChannel.Result) {
fun toggle(message: ToggleMessage) {
if (activity == null) {
result.noActivity()
return
throw NoActivityException()
}
val activity = this.activity!!
val enabled = this.enabled
if (enable) {
if (message.getEnable()!!) {
if (!enabled) activity.window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
} else if (enabled) {
activity.window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
}
result.success(null)
}
fun isEnabled(result: MethodChannel.Result) {
fun isEnabled(): IsEnabledMessage {
if (activity == null) {
result.noActivity()
return
throw NoActivityException()
}
result.success(enabled)
val msg = IsEnabledMessage()
msg.setEnabled(enabled)
return msg
}
}
fun MethodChannel.Result.noActivity() = error("no_activity", "wakelock requires a foreground activity", null)
class NoActivityException() : Exception("wakelock requires a foreground activity")
... ...
package creativemaybeno.wakelock
import androidx.annotation.NonNull
import creativemaybeno.wakelock.Messages.IsEnabledMessage
import creativemaybeno.wakelock.Messages.ToggleMessage
import creativemaybeno.wakelock.Messages.WakelockApi
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.embedding.engine.plugins.activity.ActivityAware
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding
/** WakelockPlugin */
class WakelockPlugin : FlutterPlugin, WakelockApi, ActivityAware {
private var wakelock: Wakelock? = null
override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
WakelockApi.setup(flutterPluginBinding.binaryMessenger, this)
wakelock = Wakelock()
}
override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) {
WakelockApi.setup(binding.binaryMessenger, null)
wakelock = null
}
override fun onAttachedToActivity(binding: ActivityPluginBinding) {
wakelock?.activity = binding.activity
}
override fun onDetachedFromActivity() {
wakelock?.activity = null
}
override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) {
onAttachedToActivity(binding)
}
override fun onDetachedFromActivityForConfigChanges() {
onDetachedFromActivity()
}
override fun toggle(arg: ToggleMessage?) {
wakelock!!.toggle(arg!!)
}
override val isEnabled: IsEnabledMessage
get() {
return wakelock!!.isEnabled()
}
}
... ...
... ... @@ -22,6 +22,7 @@
# Flutter/Dart/Pub related
**/doc/api/
**/ios/Flutter/.last_build_id
.dart_tool/
.flutter-plugins
.flutter-plugins-dependencies
... ... @@ -38,14 +39,3 @@ app.*.symbols
# Obfuscation related
app.*.map.json
# Exceptions to above rules.
!/packages/flutter_tools/test/data/dart_dependencies_test/**/.packages
# Cleanliness
pubspec.lock
.metadata
test
ios
android
web
... ...
# wakelock_example
Example app demonstrating how to use the wakelock plugin. It also includes integration tests for
testing the plugin in an integrated example.
## Integration tests
You can run the integration tests using the following command:
```
flutter drive --driver=test_driver/integration_test.dart --target=integration_test/wakelock_test.dart
```
... ...
gradle-wrapper.jar
/.gradle
/captures/
/gradlew
/gradlew.bat
/local.properties
GeneratedPluginRegistrant.java
# Remember to never publicly share your keystore.
# See https://flutter.dev/docs/deployment/android#reference-the-keystore-from-the-app
key.properties
... ...
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 29
sourceSets {
main.java.srcDirs += 'src/main/kotlin'
}
lintOptions {
disable 'InvalidPackage'
}
defaultConfig {
// TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
applicationId "creativemaybeno.wakelock_example"
minSdkVersion 16
targetSdkVersion 29
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"
}
... ...
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="creativemaybeno.wakelock_example">
<!-- Flutter needs it to communicate with the running application
to allow setting breakpoints, to provide hot reload, etc.
-->
<uses-permission android:name="android.permission.INTERNET"/>
</manifest>
... ...
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="creativemaybeno.wakelock_example">
<!-- io.flutter.app.FlutterApplication is an android.app.Application that
calls FlutterMain.startInitialization(this); in its onCreate method.
In most cases you can leave this as-is, but you if you want to provide
additional functionality it is fine to subclass or reimplement
FlutterApplication and put your custom class here. -->
<application
android:name="io.flutter.app.FlutterApplication"
android:label="wakelock_example"
android:icon="@mipmap/ic_launcher">
<activity
android:name=".MainActivity"
android:launchMode="singleTop"
android:theme="@style/LaunchTheme"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
android:hardwareAccelerated="true"
android:windowSoftInputMode="adjustResize">
<!-- Specifies an Android theme to apply to this Activity as soon as
the Android process has started. This theme is visible to the user
while the Flutter UI initializes. After that, this theme continues
to determine the Window background behind the Flutter UI. -->
<meta-data
android:name="io.flutter.embedding.android.NormalTheme"
android:resource="@style/NormalTheme"
/>
<!-- Displays an Android View that continues showing the launch screen
Drawable until Flutter paints its first frame, then this splash
screen fades out. A splash screen is useful to avoid any visual
gap between the end of Android's launch screen and the painting of
Flutter's first frame. -->
<meta-data
android:name="io.flutter.embedding.android.SplashScreenDrawable"
android:resource="@drawable/launch_background"
/>
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<!-- Don't delete the meta-data below.
This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
<meta-data
android:name="flutterEmbedding"
android:value="2" />
</application>
</manifest>
... ...
package creativemaybeno.wakelock_example
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
... ...
<?xml version="1.0" encoding="utf-8"?>
<!-- Modify this file to customize your launch splash screen -->
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@android:color/white" />
<!-- You can insert your own image assets here -->
<!-- <item>
<bitmap
android:gravity="center"
android:src="@mipmap/launch_image" />
</item> -->
</layer-list>
... ...
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- Theme applied to the Android Window while the process is starting -->
<style name="LaunchTheme" parent="@android:style/Theme.Black.NoTitleBar">
<!-- Show a splash screen on the activity. Automatically removed when
Flutter draws its first frame -->
<item name="android:windowBackground">@drawable/launch_background</item>
</style>
<!-- Theme applied to the Android Window as soon as the process has started.
This theme determines the color of the Android Window while your
Flutter UI initializes, as well as behind your Flutter UI while its
running.
This Theme is only used starting with V2 of Flutter's Android embedding. -->
<style name="NormalTheme" parent="@android:style/Theme.Black.NoTitleBar">
<item name="android:windowBackground">@android:color/white</item>
</style>
</resources>
... ...
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="creativemaybeno.wakelock_example">
<!-- Flutter needs it to communicate with the running application
to allow setting breakpoints, to provide hot reload, etc.
-->
<uses-permission android:name="android.permission.INTERNET"/>
</manifest>
... ...
buildscript {
ext.kotlin_version = '1.3.50'
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.5.0'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
allprojects {
repositories {
google()
jcenter()
}
}
rootProject.buildDir = '../build'
subprojects {
project.buildDir = "${rootProject.buildDir}/${project.name}"
}
subprojects {
project.evaluationDependsOn(':app')
}
task clean(type: Delete) {
delete rootProject.buildDir
}
... ...
org.gradle.jvmargs=-Xmx1536M
android.enableR8=true
android.useAndroidX=true
android.enableJetifier=true
android.enableR8=true
... ...
#Fri Jun 23 08:50:38 CEST 2017
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-5.6.2-all.zip
... ...
include ':app'
def localPropertiesFile = new File(rootProject.projectDir, "local.properties")
def properties = new Properties()
assert localPropertiesFile.exists()
localPropertiesFile.withReader("UTF-8") { reader -> properties.load(reader) }
def flutterSdkPath = properties.getProperty("flutter.sdk")
assert flutterSdkPath != null, "flutter.sdk not set in local.properties"
apply from: "$flutterSdkPath/packages/flutter_tools/gradle/app_plugin_loader.gradle"
... ...
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
import 'package:wakelock/wakelock.dart';
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
testWidgets('enabling and disabling wakelock', (WidgetTester tester) async {
final wakelockEnabled = await Wakelock.enabled;
// The wakelock should initially be disabled.
expect(wakelockEnabled, isFalse);
await Wakelock.enable();
expect(await Wakelock.enabled, isTrue);
await Wakelock.disable();
expect(await Wakelock.enabled, isFalse);
});
testWidgets('toggling wakelock', (WidgetTester tester) async {
await Wakelock.toggle(enable: true);
expect(await Wakelock.enabled, isTrue);
await Wakelock.toggle(enable: false);
expect(await Wakelock.enabled, isFalse);
});
}
... ...
*.mode1v3
*.mode2v3
*.moved-aside
*.pbxuser
*.perspectivev3
**/*sync/
.sconsign.dblite
.tags*
**/.vagrant/
**/DerivedData/
Icon?
**/Pods/
**/.symlinks/
profile
xcuserdata
**/.generated/
Flutter/App.framework
Flutter/Flutter.framework
Flutter/Flutter.podspec
Flutter/Generated.xcconfig
Flutter/app.flx
Flutter/app.zip
Flutter/flutter_assets/
Flutter/flutter_export_environment.sh
ServiceDefinitions.json
Runner/GeneratedPluginRegistrant.*
# Exceptions to above rules.
!default.mode1v3
!default.mode2v3
!default.pbxuser
!default.perspectivev3
... ...
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>$(DEVELOPMENT_LANGUAGE)</string>
<key>CFBundleExecutable</key>
<string>App</string>
<key>CFBundleIdentifier</key>
<string>io.flutter.flutter.app</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>App</string>
<key>CFBundlePackageType</key>
<string>FMWK</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>1.0</string>
<key>MinimumOSVersion</key>
<string>9.0</string>
</dict>
</plist>
... ...
#include "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"
#include "Generated.xcconfig"
... ...
#include "Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"
#include "Generated.xcconfig"
... ...
# Uncomment this line to define a global platform for your project
# platform :ios, '9.0'
# CocoaPods analytics sends network stats synchronously affecting flutter build latency.
ENV['COCOAPODS_DISABLE_STATS'] = 'true'
project 'Runner', {
'Debug' => :debug,
'Profile' => :release,
'Release' => :release,
}
def flutter_root
generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'Generated.xcconfig'), __FILE__)
unless File.exist?(generated_xcode_build_settings_path)
raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure flutter pub get is executed first"
end
File.foreach(generated_xcode_build_settings_path) do |line|
matches = line.match(/FLUTTER_ROOT\=(.*)/)
return matches[1].strip if matches
end
raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Generated.xcconfig, then run flutter pub get"
end
require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root)
flutter_ios_podfile_setup
target 'Runner' do
flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__))
end
post_install do |installer|
installer.pods_project.targets.each do |target|
flutter_additional_ios_build_settings(target)
end
end
... ...
PODS:
- Flutter (1.0.0)
- integration_test (0.0.1):
- Flutter
- wakelock (0.0.1):
- Flutter
DEPENDENCIES:
- Flutter (from `Flutter`)
- integration_test (from `.symlinks/plugins/integration_test/ios`)
- wakelock (from `.symlinks/plugins/wakelock/ios`)
EXTERNAL SOURCES:
Flutter:
:path: Flutter
integration_test:
:path: ".symlinks/plugins/integration_test/ios"
wakelock:
:path: ".symlinks/plugins/wakelock/ios"
SPEC CHECKSUMS:
Flutter: 0e3d915762c693b495b44d77113d4970485de6ec
integration_test: 5ed24a436eb7ec17b6a13046e9bf7ca4a404e59e
wakelock: bfc7955c418d0db797614075aabbc58a39ab5107
PODFILE CHECKSUM: 8e679eca47255a8ca8067c4c67aab20e64cb974d
COCOAPODS: 1.9.3
... ...
// !$*UTF8*$!
{
archiveVersion = 1;
classes = {
};
objectVersion = 46;
objects = {
/* Begin PBXBuildFile section */
1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */ = {isa = PBXBuildFile; fileRef = 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */; };
3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */ = {isa = PBXBuildFile; fileRef = 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */; };
978B8F6F1D3862AE00F588F7 /* AppDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = 7AFFD8EE1D35381100E5BB4D /* AppDelegate.m */; };
97C146F31CF9000F007C117D /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = 97C146F21CF9000F007C117D /* main.m */; };
97C146FC1CF9000F007C117D /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FA1CF9000F007C117D /* Main.storyboard */; };
97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FD1CF9000F007C117D /* Assets.xcassets */; };
97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */; };
A6847046D3B647529A66EE97 /* libPods-Runner.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 320D1841761F9CD1E849A1F0 /* libPods-Runner.a */; };
/* End PBXBuildFile section */
/* Begin PBXCopyFilesBuildPhase section */
9705A1C41CF9048500538489 /* Embed Frameworks */ = {
isa = PBXCopyFilesBuildPhase;
buildActionMask = 2147483647;
dstPath = "";
dstSubfolderSpec = 10;
files = (
);
name = "Embed Frameworks";
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXCopyFilesBuildPhase section */
/* Begin PBXFileReference section */
1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GeneratedPluginRegistrant.h; sourceTree = "<group>"; };
1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GeneratedPluginRegistrant.m; sourceTree = "<group>"; };
2111AD0340E57F623E74EE98 /* Pods-Runner.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.release.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"; sourceTree = "<group>"; };
320D1841761F9CD1E849A1F0 /* libPods-Runner.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = "libPods-Runner.a"; sourceTree = BUILT_PRODUCTS_DIR; };
3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = AppFrameworkInfo.plist; path = Flutter/AppFrameworkInfo.plist; sourceTree = "<group>"; };
6937DE1C1E231CE26C21EB6B /* Pods-Runner.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.profile.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.profile.xcconfig"; sourceTree = "<group>"; };
7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = Release.xcconfig; path = Flutter/Release.xcconfig; sourceTree = "<group>"; };
7AFFD8ED1D35381100E5BB4D /* AppDelegate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AppDelegate.h; sourceTree = "<group>"; };
7AFFD8EE1D35381100E5BB4D /* AppDelegate.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AppDelegate.m; sourceTree = "<group>"; };
9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Debug.xcconfig; path = Flutter/Debug.xcconfig; sourceTree = "<group>"; };
9740EEB31CF90195004384FC /* Generated.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Generated.xcconfig; path = Flutter/Generated.xcconfig; sourceTree = "<group>"; };
97C146EE1CF9000F007C117D /* Runner.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Runner.app; sourceTree = BUILT_PRODUCTS_DIR; };
97C146F21CF9000F007C117D /* main.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = main.m; sourceTree = "<group>"; };
97C146FB1CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = "<group>"; };
97C146FD1CF9000F007C117D /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
97C147001CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = "<group>"; };
97C147021CF9000F007C117D /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
F6CC63182AFEEC23EAC5C95F /* Pods-Runner.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.debug.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
97C146EB1CF9000F007C117D /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
A6847046D3B647529A66EE97 /* libPods-Runner.a in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
356EF92E5865B0B43E707F28 /* Frameworks */ = {
isa = PBXGroup;
children = (
320D1841761F9CD1E849A1F0 /* libPods-Runner.a */,
);
name = Frameworks;
sourceTree = "<group>";
};
7865595A245EC8291D1003FA /* Pods */ = {
isa = PBXGroup;
children = (
F6CC63182AFEEC23EAC5C95F /* Pods-Runner.debug.xcconfig */,
2111AD0340E57F623E74EE98 /* Pods-Runner.release.xcconfig */,
6937DE1C1E231CE26C21EB6B /* Pods-Runner.profile.xcconfig */,
);
name = Pods;
path = Pods;
sourceTree = "<group>";
};
9740EEB11CF90186004384FC /* Flutter */ = {
isa = PBXGroup;
children = (
3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */,
9740EEB21CF90195004384FC /* Debug.xcconfig */,
7AFA3C8E1D35360C0083082E /* Release.xcconfig */,
9740EEB31CF90195004384FC /* Generated.xcconfig */,
);
name = Flutter;
sourceTree = "<group>";
};
97C146E51CF9000F007C117D = {
isa = PBXGroup;
children = (
9740EEB11CF90186004384FC /* Flutter */,
97C146F01CF9000F007C117D /* Runner */,
97C146EF1CF9000F007C117D /* Products */,
7865595A245EC8291D1003FA /* Pods */,
356EF92E5865B0B43E707F28 /* Frameworks */,
);
sourceTree = "<group>";
};
97C146EF1CF9000F007C117D /* Products */ = {
isa = PBXGroup;
children = (
97C146EE1CF9000F007C117D /* Runner.app */,
);
name = Products;
sourceTree = "<group>";
};
97C146F01CF9000F007C117D /* Runner */ = {
isa = PBXGroup;
children = (
7AFFD8ED1D35381100E5BB4D /* AppDelegate.h */,
7AFFD8EE1D35381100E5BB4D /* AppDelegate.m */,
97C146FA1CF9000F007C117D /* Main.storyboard */,
97C146FD1CF9000F007C117D /* Assets.xcassets */,
97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */,
97C147021CF9000F007C117D /* Info.plist */,
97C146F11CF9000F007C117D /* Supporting Files */,
1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */,
1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */,
);
path = Runner;
sourceTree = "<group>";
};
97C146F11CF9000F007C117D /* Supporting Files */ = {
isa = PBXGroup;
children = (
97C146F21CF9000F007C117D /* main.m */,
);
name = "Supporting Files";
sourceTree = "<group>";
};
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
97C146ED1CF9000F007C117D /* Runner */ = {
isa = PBXNativeTarget;
buildConfigurationList = 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */;
buildPhases = (
112EA101BE908B08DE569906 /* [CP] Check Pods Manifest.lock */,
9740EEB61CF901F6004384FC /* Run Script */,
97C146EA1CF9000F007C117D /* Sources */,
97C146EB1CF9000F007C117D /* Frameworks */,
97C146EC1CF9000F007C117D /* Resources */,
9705A1C41CF9048500538489 /* Embed Frameworks */,
3B06AD1E1E4923F5004D2608 /* Thin Binary */,
FAD6D21B222DFE9FB43C310E /* [CP] Embed Pods Frameworks */,
);
buildRules = (
);
dependencies = (
);
name = Runner;
productName = Runner;
productReference = 97C146EE1CF9000F007C117D /* Runner.app */;
productType = "com.apple.product-type.application";
};
/* End PBXNativeTarget section */
/* Begin PBXProject section */
97C146E61CF9000F007C117D /* Project object */ = {
isa = PBXProject;
attributes = {
LastUpgradeCheck = 1020;
ORGANIZATIONNAME = "";
TargetAttributes = {
97C146ED1CF9000F007C117D = {
CreatedOnToolsVersion = 7.3.1;
};
};
};
buildConfigurationList = 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */;
compatibilityVersion = "Xcode 9.3";
developmentRegion = en;
hasScannedForEncodings = 0;
knownRegions = (
en,
Base,
);
mainGroup = 97C146E51CF9000F007C117D;
productRefGroup = 97C146EF1CF9000F007C117D /* Products */;
projectDirPath = "";
projectRoot = "";
targets = (
97C146ED1CF9000F007C117D /* Runner */,
);
};
/* End PBXProject section */
/* Begin PBXResourcesBuildPhase section */
97C146EC1CF9000F007C117D /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */,
3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */,
97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */,
97C146FC1CF9000F007C117D /* Main.storyboard in Resources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXResourcesBuildPhase section */
/* Begin PBXShellScriptBuildPhase section */
112EA101BE908B08DE569906 /* [CP] Check Pods Manifest.lock */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputFileListPaths = (
);
inputPaths = (
"${PODS_PODFILE_DIR_PATH}/Podfile.lock",
"${PODS_ROOT}/Manifest.lock",
);
name = "[CP] Check Pods Manifest.lock";
outputFileListPaths = (
);
outputPaths = (
"$(DERIVED_FILE_DIR)/Pods-Runner-checkManifestLockResult.txt",
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n";
showEnvVarsInLog = 0;
};
3B06AD1E1E4923F5004D2608 /* Thin Binary */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputPaths = (
);
name = "Thin Binary";
outputPaths = (
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" embed_and_thin";
};
9740EEB61CF901F6004384FC /* Run Script */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputPaths = (
);
name = "Run Script";
outputPaths = (
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" build";
};
FAD6D21B222DFE9FB43C310E /* [CP] Embed Pods Frameworks */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputPaths = (
"${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks.sh",
"${PODS_ROOT}/../Flutter/Flutter.framework",
);
name = "[CP] Embed Pods Frameworks";
outputPaths = (
"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/Flutter.framework",
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks.sh\"\n";
showEnvVarsInLog = 0;
};
/* End PBXShellScriptBuildPhase section */
/* Begin PBXSourcesBuildPhase section */
97C146EA1CF9000F007C117D /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
978B8F6F1D3862AE00F588F7 /* AppDelegate.m in Sources */,
97C146F31CF9000F007C117D /* main.m in Sources */,
1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXSourcesBuildPhase section */
/* Begin PBXVariantGroup section */
97C146FA1CF9000F007C117D /* Main.storyboard */ = {
isa = PBXVariantGroup;
children = (
97C146FB1CF9000F007C117D /* Base */,
);
name = Main.storyboard;
sourceTree = "<group>";
};
97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */ = {
isa = PBXVariantGroup;
children = (
97C147001CF9000F007C117D /* Base */,
);
name = LaunchScreen.storyboard;
sourceTree = "<group>";
};
/* End PBXVariantGroup section */
/* Begin XCBuildConfiguration section */
249021D3217E4FDB00AE95B9 /* Profile */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CLANG_ANALYZER_NONNULL = YES;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x";
CLANG_CXX_LIBRARY = "libc++";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
COPY_PHASE_STRIP = NO;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
ENABLE_NS_ASSERTIONS = NO;
ENABLE_STRICT_OBJC_MSGSEND = YES;
GCC_C_LANGUAGE_STANDARD = gnu99;
GCC_NO_COMMON_BLOCKS = YES;
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 9.0;
MTL_ENABLE_DEBUG_INFO = NO;
SDKROOT = iphoneos;
SUPPORTED_PLATFORMS = iphoneos;
TARGETED_DEVICE_FAMILY = "1,2";
VALIDATE_PRODUCT = YES;
};
name = Profile;
};
249021D4217E4FDB00AE95B9 /* Profile */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)";
ENABLE_BITCODE = NO;
FRAMEWORK_SEARCH_PATHS = (
"$(inherited)",
"$(PROJECT_DIR)/Flutter",
);
INFOPLIST_FILE = Runner/Info.plist;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
LIBRARY_SEARCH_PATHS = (
"$(inherited)",
"$(PROJECT_DIR)/Flutter",
);
PRODUCT_BUNDLE_IDENTIFIER = creativemaybeno.wakelockExample;
PRODUCT_NAME = "$(TARGET_NAME)";
VERSIONING_SYSTEM = "apple-generic";
};
name = Profile;
};
97C147031CF9000F007C117D /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CLANG_ANALYZER_NONNULL = YES;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x";
CLANG_CXX_LIBRARY = "libc++";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
COPY_PHASE_STRIP = NO;
DEBUG_INFORMATION_FORMAT = dwarf;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_TESTABILITY = YES;
GCC_C_LANGUAGE_STANDARD = gnu99;
GCC_DYNAMIC_NO_PIC = NO;
GCC_NO_COMMON_BLOCKS = YES;
GCC_OPTIMIZATION_LEVEL = 0;
GCC_PREPROCESSOR_DEFINITIONS = (
"DEBUG=1",
"$(inherited)",
);
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 9.0;
MTL_ENABLE_DEBUG_INFO = YES;
ONLY_ACTIVE_ARCH = YES;
SDKROOT = iphoneos;
TARGETED_DEVICE_FAMILY = "1,2";
};
name = Debug;
};
97C147041CF9000F007C117D /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CLANG_ANALYZER_NONNULL = YES;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x";
CLANG_CXX_LIBRARY = "libc++";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
COPY_PHASE_STRIP = NO;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
ENABLE_NS_ASSERTIONS = NO;
ENABLE_STRICT_OBJC_MSGSEND = YES;
GCC_C_LANGUAGE_STANDARD = gnu99;
GCC_NO_COMMON_BLOCKS = YES;
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 9.0;
MTL_ENABLE_DEBUG_INFO = NO;
SDKROOT = iphoneos;
SUPPORTED_PLATFORMS = iphoneos;
TARGETED_DEVICE_FAMILY = "1,2";
VALIDATE_PRODUCT = YES;
};
name = Release;
};
97C147061CF9000F007C117D /* Debug */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)";
ENABLE_BITCODE = NO;
FRAMEWORK_SEARCH_PATHS = (
"$(inherited)",
"$(PROJECT_DIR)/Flutter",
);
INFOPLIST_FILE = Runner/Info.plist;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
LIBRARY_SEARCH_PATHS = (
"$(inherited)",
"$(PROJECT_DIR)/Flutter",
);
PRODUCT_BUNDLE_IDENTIFIER = creativemaybeno.wakelockExample;
PRODUCT_NAME = "$(TARGET_NAME)";
VERSIONING_SYSTEM = "apple-generic";
};
name = Debug;
};
97C147071CF9000F007C117D /* Release */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)";
ENABLE_BITCODE = NO;
FRAMEWORK_SEARCH_PATHS = (
"$(inherited)",
"$(PROJECT_DIR)/Flutter",
);
INFOPLIST_FILE = Runner/Info.plist;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
LIBRARY_SEARCH_PATHS = (
"$(inherited)",
"$(PROJECT_DIR)/Flutter",
);
PRODUCT_BUNDLE_IDENTIFIER = creativemaybeno.wakelockExample;
PRODUCT_NAME = "$(TARGET_NAME)";
VERSIONING_SYSTEM = "apple-generic";
};
name = Release;
};
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */ = {
isa = XCConfigurationList;
buildConfigurations = (
97C147031CF9000F007C117D /* Debug */,
97C147041CF9000F007C117D /* Release */,
249021D3217E4FDB00AE95B9 /* Profile */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */ = {
isa = XCConfigurationList;
buildConfigurations = (
97C147061CF9000F007C117D /* Debug */,
97C147071CF9000F007C117D /* Release */,
249021D4217E4FDB00AE95B9 /* Profile */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
/* End XCConfigurationList section */
};
rootObject = 97C146E61CF9000F007C117D /* Project object */;
}
... ...
<?xml version="1.0" encoding="UTF-8"?>
<Workspace
version = "1.0">
<FileRef
location = "group:Runner.xcodeproj">
</FileRef>
</Workspace>
... ...
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>IDEDidComputeMac32BitWarning</key>
<true/>
</dict>
</plist>
... ...
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>PreviewsEnabled</key>
<false/>
</dict>
</plist>
... ...
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1020"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "97C146ED1CF9000F007C117D"
BuildableName = "Runner.app"
BlueprintName = "Runner"
ReferencedContainer = "container:Runner.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
</Testables>
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "97C146ED1CF9000F007C117D"
BuildableName = "Runner.app"
BlueprintName = "Runner"
ReferencedContainer = "container:Runner.xcodeproj">
</BuildableReference>
</MacroExpansion>
<AdditionalOptions>
</AdditionalOptions>
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "97C146ED1CF9000F007C117D"
BuildableName = "Runner.app"
BlueprintName = "Runner"
ReferencedContainer = "container:Runner.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
<AdditionalOptions>
</AdditionalOptions>
</LaunchAction>
<ProfileAction
buildConfiguration = "Profile"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "97C146ED1CF9000F007C117D"
BuildableName = "Runner.app"
BlueprintName = "Runner"
ReferencedContainer = "container:Runner.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
... ...
<?xml version="1.0" encoding="UTF-8"?>
<Workspace
version = "1.0">
<FileRef
location = "group:Runner.xcodeproj">
</FileRef>
<FileRef
location = "group:Pods/Pods.xcodeproj">
</FileRef>
</Workspace>
... ...
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>IDEDidComputeMac32BitWarning</key>
<true/>
</dict>
</plist>
... ...
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>PreviewsEnabled</key>
<false/>
</dict>
</plist>
... ...
#import <Flutter/Flutter.h>
#import <UIKit/UIKit.h>
@interface AppDelegate : FlutterAppDelegate
@end
... ...
#import "AppDelegate.h"
#import "GeneratedPluginRegistrant.h"
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[GeneratedPluginRegistrant registerWithRegistry:self];
// Override point for customization after application launch.
return [super application:application didFinishLaunchingWithOptions:launchOptions];
}
@end
... ...
{
"images" : [
{
"size" : "20x20",
"idiom" : "iphone",
"filename" : "Icon-App-20x20@2x.png",
"scale" : "2x"
},
{
"size" : "20x20",
"idiom" : "iphone",
"filename" : "Icon-App-20x20@3x.png",
"scale" : "3x"
},
{
"size" : "29x29",
"idiom" : "iphone",
"filename" : "Icon-App-29x29@1x.png",
"scale" : "1x"
},
{
"size" : "29x29",
"idiom" : "iphone",
"filename" : "Icon-App-29x29@2x.png",
"scale" : "2x"
},
{
"size" : "29x29",
"idiom" : "iphone",
"filename" : "Icon-App-29x29@3x.png",
"scale" : "3x"
},
{
"size" : "40x40",
"idiom" : "iphone",
"filename" : "Icon-App-40x40@2x.png",
"scale" : "2x"
},
{
"size" : "40x40",
"idiom" : "iphone",
"filename" : "Icon-App-40x40@3x.png",
"scale" : "3x"
},
{
"size" : "60x60",
"idiom" : "iphone",
"filename" : "Icon-App-60x60@2x.png",
"scale" : "2x"
},
{
"size" : "60x60",
"idiom" : "iphone",
"filename" : "Icon-App-60x60@3x.png",
"scale" : "3x"
},
{
"size" : "20x20",
"idiom" : "ipad",
"filename" : "Icon-App-20x20@1x.png",
"scale" : "1x"
},
{
"size" : "20x20",
"idiom" : "ipad",
"filename" : "Icon-App-20x20@2x.png",
"scale" : "2x"
},
{
"size" : "29x29",
"idiom" : "ipad",
"filename" : "Icon-App-29x29@1x.png",
"scale" : "1x"
},
{
"size" : "29x29",
"idiom" : "ipad",
"filename" : "Icon-App-29x29@2x.png",
"scale" : "2x"
},
{
"size" : "40x40",
"idiom" : "ipad",
"filename" : "Icon-App-40x40@1x.png",
"scale" : "1x"
},
{
"size" : "40x40",
"idiom" : "ipad",
"filename" : "Icon-App-40x40@2x.png",
"scale" : "2x"
},
{
"size" : "76x76",
"idiom" : "ipad",
"filename" : "Icon-App-76x76@1x.png",
"scale" : "1x"
},
{
"size" : "76x76",
"idiom" : "ipad",
"filename" : "Icon-App-76x76@2x.png",
"scale" : "2x"
},
{
"size" : "83.5x83.5",
"idiom" : "ipad",
"filename" : "Icon-App-83.5x83.5@2x.png",
"scale" : "2x"
},
{
"size" : "1024x1024",
"idiom" : "ios-marketing",
"filename" : "Icon-App-1024x1024@1x.png",
"scale" : "1x"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
}
... ...
{
"images" : [
{
"idiom" : "universal",
"filename" : "LaunchImage.png",
"scale" : "1x"
},
{
"idiom" : "universal",
"filename" : "LaunchImage@2x.png",
"scale" : "2x"
},
{
"idiom" : "universal",
"filename" : "LaunchImage@3x.png",
"scale" : "3x"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
}
... ...
# Launch Screen Assets
You can customize the launch screen with your own desired assets by replacing the image files in this directory.
You can also do it by opening your Flutter project's Xcode project with `open ios/Runner.xcworkspace`, selecting `Runner/Assets.xcassets` in the Project Navigator and dropping in the desired images.
\ No newline at end of file
... ...
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="12121" systemVersion="16G29" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" launchScreen="YES" colorMatched="YES" initialViewController="01J-lp-oVM">
<dependencies>
<deployment identifier="iOS"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="12089"/>
</dependencies>
<scenes>
<!--View Controller-->
<scene sceneID="EHf-IW-A2E">
<objects>
<viewController id="01J-lp-oVM" sceneMemberID="viewController">
<layoutGuides>
<viewControllerLayoutGuide type="top" id="Ydg-fD-yQy"/>
<viewControllerLayoutGuide type="bottom" id="xbc-2k-c8Z"/>
</layoutGuides>
<view key="view" contentMode="scaleToFill" id="Ze5-6b-2t3">
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<subviews>
<imageView opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" image="LaunchImage" translatesAutoresizingMaskIntoConstraints="NO" id="YRO-k0-Ey4">
</imageView>
</subviews>
<color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<constraints>
<constraint firstItem="YRO-k0-Ey4" firstAttribute="centerX" secondItem="Ze5-6b-2t3" secondAttribute="centerX" id="1a2-6s-vTC"/>
<constraint firstItem="YRO-k0-Ey4" firstAttribute="centerY" secondItem="Ze5-6b-2t3" secondAttribute="centerY" id="4X2-HB-R7a"/>
</constraints>
</view>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="iYj-Kq-Ea1" userLabel="First Responder" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="53" y="375"/>
</scene>
</scenes>
<resources>
<image name="LaunchImage" width="168" height="185"/>
</resources>
</document>
... ...
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="10117" systemVersion="15F34" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" initialViewController="BYZ-38-t0r">
<dependencies>
<deployment identifier="iOS"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="10085"/>
</dependencies>
<scenes>
<!--Flutter View Controller-->
<scene sceneID="tne-QT-ifu">
<objects>
<viewController id="BYZ-38-t0r" customClass="FlutterViewController" sceneMemberID="viewController">
<layoutGuides>
<viewControllerLayoutGuide type="top" id="y3c-jy-aDJ"/>
<viewControllerLayoutGuide type="bottom" id="wfy-db-euE"/>
</layoutGuides>
<view key="view" contentMode="scaleToFill" id="8bC-Xf-vdC">
<rect key="frame" x="0.0" y="0.0" width="600" height="600"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="calibratedWhite"/>
</view>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="dkx-z0-nzr" sceneMemberID="firstResponder"/>
</objects>
</scene>
</scenes>
</document>
... ...
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>$(DEVELOPMENT_LANGUAGE)</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>wakelock_example</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>$(FLUTTER_BUILD_NAME)</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>$(FLUTTER_BUILD_NUMBER)</string>
<key>LSRequiresIPhoneOS</key>
<true/>
<key>UILaunchStoryboardName</key>
<string>LaunchScreen</string>
<key>UIMainStoryboardFile</key>
<string>Main</string>
<key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>UISupportedInterfaceOrientations~ipad</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationPortraitUpsideDown</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>UIViewControllerBasedStatusBarAppearance</key>
<false/>
</dict>
</plist>
... ...
#import <Flutter/Flutter.h>
#import <UIKit/UIKit.h>
#import "AppDelegate.h"
int main(int argc, char* argv[]) {
@autoreleasepool {
return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
}
}
... ...
... ... @@ -2,30 +2,37 @@ import 'package:flutter/material.dart';
import 'package:wakelock/wakelock.dart';
void main() {
runApp(ExampleApp());
runApp(WakelockExampleApp());
}
/// The wakelock implementation is located inside the [FlatButton.onPressed] functions and a [FutureBuilder].
/// The [FlatButton]'s and the [FutureBuilder] sit inside the [Column] that is a child of the [Scaffold] in [_ExampleAppState].
class ExampleApp extends StatefulWidget {
const ExampleApp({Key key}) : super(key: key);
/// Example app widget demonstrating how to use the wakelock plugin.
///
/// The example implementation is located inside [OutlineButton.onPressed]
/// callback functions and a [FutureBuilder].
class WakelockExampleApp extends StatefulWidget {
@override
_ExampleAppState createState() => _ExampleAppState();
_WakelockExampleAppState createState() => _WakelockExampleAppState();
}
class _ExampleAppState extends State<ExampleApp> {
class _WakelockExampleAppState extends State<WakelockExampleApp> {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Wakelock example app'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
FlatButton(
const Spacer(
flex: 3,
),
OutlineButton(
onPressed: () {
// The following code will enable the wakelock on Android or iOS using the wakelock plugin.
// The following code will enable the wakelock on the device
// using the wakelock plugin.
setState(() {
Wakelock.enable();
// You could also use Wakelock.toggle(on: true);
... ... @@ -33,9 +40,11 @@ class _ExampleAppState extends State<ExampleApp> {
},
child: const Text('enable wakelock'),
),
FlatButton(
const Spacer(),
OutlineButton(
onPressed: () {
// The following code will disable the wakelock on Android or iOS using the wakelock plugin.
// The following code will disable the wakelock on the device
// using the wakelock plugin.
setState(() {
Wakelock.disable();
// You could also use Wakelock.toggle(on: false);
... ... @@ -43,16 +52,27 @@ class _ExampleAppState extends State<ExampleApp> {
},
child: const Text('disable wakelock'),
),
const Spacer(
flex: 2,
),
FutureBuilder(
future: Wakelock.isEnabled,
future: Wakelock.enabled,
builder: (context, AsyncSnapshot<bool> snapshot) {
// The use of FutureBuilder is necessary here to await the bool value from isEnabled.
if (!snapshot.hasData)
return Container(); // The Future is retrieved so fast that you will not be able to see any loading indicator.
return Text(
'wakelock is currently ${snapshot.data ? 'enabled' : 'disabled'}');
// The use of FutureBuilder is necessary here to await the
// bool value from the `enabled` getter.
if (!snapshot.hasData) {
// The Future is retrieved so fast that you will not be able
// to see any loading indicator.
return Container();
}
return Text('The wakelock is currently '
'${snapshot.data ? 'enabled' : 'disabled'}.');
},
),
const Spacer(
flex: 3,
),
],
),
),
... ...
name: wakelock_example
description: Demonstrates how to use the wakelock plugin and is used for integration testing.
description: >-2
Example app demonstrating how to use the wakelock plugin. It also includes integration tests for
testing the plugin in an integrated example.
publish_to: 'none'
environment:
... ... @@ -9,15 +11,20 @@ dependencies:
flutter:
sdk: flutter
dev_dependencies:
pedantic: 1.9.0
wakelock:
# When depending on this package from a real application you should use:
# wakelock: ^x.y.z
# See https://dart.dev/tools/pub/dependencies#version-constraints
# The example app is bundled with the plugin so we use a path dependency on
# the parent directory to use the current plugin's version.
path: ../
dev_dependencies:
flutter_test:
sdk: flutter
flutter_driver:
sdk: flutter
test: # This is equivalent to any.
integration_test: ^0.9.1
test: any
dependency_overrides:
pedantic: 1.9.0
pedantic: ^1.9.2
... ...
import 'package:integration_test/integration_test_driver.dart';
Future<void> main() => integrationDriver();
... ...
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta content="IE=Edge" http-equiv="X-UA-Compatible">
<meta name="description" content="Example app demonstrating how to use the wakelock plugin.">
<!-- iOS meta tags -->
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<meta name="apple-mobile-web-app-title" content="wakelock example">
<title>wakelock example</title>
<link rel="manifest" href="manifest.json">
</head>
<body>
<!-- This script installs service_worker.js to provide PWA functionality to
application. For more information, see:
https://developers.google.com/web/fundamentals/primers/service-workers -->
<script>
if ('serviceWorker' in navigator) {
window.addEventListener('load', function () {
navigator.serviceWorker.register('flutter_service_worker.js');
});
}
</script>
<script src="main.dart.js" type="application/javascript"></script>
</body>
</html>
... ...
{
"name": "wakelock example",
"short_name": "wakelock",
"start_url": ".",
"display": "standalone",
"background_color": "#0175C2",
"theme_color": "#0175C2",
"description": "Example app demonstrating how to use the wakelock plugin.",
"orientation": "portrait-primary",
"prefer_related_applications": false
}
... ...
#import "WakelockPlugin.h"
#import "messages.h"
@interface WakelockPlugin () <FLTWakelockApi>
@end
@implementation WakelockPlugin
+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar>*)registrar {
WakelockPlugin* instance = [[WakelockPlugin alloc] init];
FLTWakelockApiSetup(registrar.messenger, instance);
}
- (void)toggle:(FLTToggleMessage*)input error:(FlutterError**)error {
NSNumber *enable = input.enable;
NSNumber *enabled = [NSNumber numberWithBool:[[UIApplication sharedApplication] isIdleTimerDisabled]];
if (![enable isEqualToNumber:enabled]) {
[[UIApplication sharedApplication] setIdleTimerDisabled:enable.boolValue];
}
}
- (FLTIsEnabledMessage*)isEnabled:(FlutterError* __autoreleasing *)error {
NSNumber *enabled = [NSNumber numberWithBool:[[UIApplication sharedApplication] isIdleTimerDisabled]];
FLTIsEnabledMessage* result = [[FLTIsEnabledMessage alloc] init];
result.enabled = enabled;
return result;
}
@end
... ...
// Autogenerated from Pigeon (v0.1.7), do not edit directly.
// See also: https://pub.dev/packages/pigeon
#import <Foundation/Foundation.h>
@protocol FlutterBinaryMessenger;
@class FlutterError;
@class FlutterStandardTypedData;
NS_ASSUME_NONNULL_BEGIN
@class FLTToggleMessage;
@class FLTIsEnabledMessage;
@interface FLTToggleMessage : NSObject
@property(nonatomic, strong, nullable) NSNumber * enable;
@end
@interface FLTIsEnabledMessage : NSObject
@property(nonatomic, strong, nullable) NSNumber * enabled;
@end
@protocol FLTWakelockApi
-(void)toggle:(FLTToggleMessage*)input error:(FlutterError *_Nullable *_Nonnull)error;
-(nullable FLTIsEnabledMessage *)isEnabled:(FlutterError *_Nullable *_Nonnull)error;
@end
extern void FLTWakelockApiSetup(id<FlutterBinaryMessenger> binaryMessenger, id<FLTWakelockApi> _Nullable api);
NS_ASSUME_NONNULL_END
... ...
// Autogenerated from Pigeon (v0.1.7), do not edit directly.
// See also: https://pub.dev/packages/pigeon
#import "messages.h"
#import <Flutter/Flutter.h>
#if !__has_feature(objc_arc)
#error File requires ARC to be enabled.
#endif
static NSDictionary* wrapResult(NSDictionary *result, FlutterError *error) {
NSDictionary *errorDict = (NSDictionary *)[NSNull null];
if (error) {
errorDict = [NSDictionary dictionaryWithObjectsAndKeys:
(error.code ? error.code : [NSNull null]), @"code",
(error.message ? error.message : [NSNull null]), @"message",
(error.details ? error.details : [NSNull null]), @"details",
nil];
}
return [NSDictionary dictionaryWithObjectsAndKeys:
(result ? result : [NSNull null]), @"result",
errorDict, @"error",
nil];
}
@interface FLTToggleMessage ()
+(FLTToggleMessage*)fromMap:(NSDictionary*)dict;
-(NSDictionary*)toMap;
@end
@interface FLTIsEnabledMessage ()
+(FLTIsEnabledMessage*)fromMap:(NSDictionary*)dict;
-(NSDictionary*)toMap;
@end
@implementation FLTToggleMessage
+(FLTToggleMessage*)fromMap:(NSDictionary*)dict {
FLTToggleMessage* result = [[FLTToggleMessage alloc] init];
result.enable = dict[@"enable"];
if ((NSNull *)result.enable == [NSNull null]) {
result.enable = nil;
}
return result;
}
-(NSDictionary*)toMap {
return [NSDictionary dictionaryWithObjectsAndKeys:(self.enable ? self.enable : [NSNull null]), @"enable", nil];
}
@end
@implementation FLTIsEnabledMessage
+(FLTIsEnabledMessage*)fromMap:(NSDictionary*)dict {
FLTIsEnabledMessage* result = [[FLTIsEnabledMessage alloc] init];
result.enabled = dict[@"enabled"];
if ((NSNull *)result.enabled == [NSNull null]) {
result.enabled = nil;
}
return result;
}
-(NSDictionary*)toMap {
return [NSDictionary dictionaryWithObjectsAndKeys:(self.enabled ? self.enabled : [NSNull null]), @"enabled", nil];
}
@end
void FLTWakelockApiSetup(id<FlutterBinaryMessenger> binaryMessenger, id<FLTWakelockApi> api) {
{
FlutterBasicMessageChannel *channel =
[FlutterBasicMessageChannel
messageChannelWithName:@"dev.flutter.pigeon.WakelockApi.toggle"
binaryMessenger:binaryMessenger];
if (api) {
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
FlutterError *error;
FLTToggleMessage *input = [FLTToggleMessage fromMap:message];
[api toggle:input error:&error];
callback(wrapResult(nil, error));
}];
}
else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel =
[FlutterBasicMessageChannel
messageChannelWithName:@"dev.flutter.pigeon.WakelockApi.isEnabled"
binaryMessenger:binaryMessenger];
if (api) {
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
FlutterError *error;
FLTIsEnabledMessage *output = [api isEnabled:&error];
callback(wrapResult([output toMap], error));
}];
}
else {
[channel setMessageHandler:nil];
}
}
}
... ...
... ... @@ -5,19 +5,19 @@
Pod::Spec.new do |s|
s.name = 'wakelock'
s.version = '0.0.1'
s.summary = 'A new Flutter plugin.'
s.summary = 'Plugin that allows you to keep the device screen awake, i.e. prevent the screen from sleeping on Android, iOS, and web.'
s.description = <<-DESC
A new Flutter plugin.
Plugin that allows you to keep the device screen awake, i.e. prevent the screen from sleeping on Android, iOS, and web.
DESC
s.homepage = 'http://example.com'
s.license = { :file => '../LICENSE' }
s.author = { 'Your Company' => 'email@example.com' }
s.source = { :path => '.' }
s.source_files = 'Classes/**/*'
s.public_header_files = 'Classes/**/*.h'
s.dependency 'Flutter'
s.platform = :ios, '8.0'
# Flutter.framework does not contain a i386 slice. Only x86_64 simulators are supported.
s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES', 'VALID_ARCHS[sdk=iphonesimulator*]' => 'x86_64' }
s.ios.deployment_target = '8.0'
# Flutter.framework does not contain a i386 slice.
s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES', 'EXCLUDED_ARCHS[sdk=iphonesimulator*]' => 'i386' }
end
... ...
import 'package:meta/meta.dart';
import 'package:wakelock_platform_interface/wakelock_platform_interface.dart';
final _wakelockPlatformInstance = WakelockPlatformInterface.instance;
/// Class providing all wakelock functionality using static members.
///
/// To enable the wakelock, you can use [Wakelock.enable] and to disable it,
/// you can call [Wakelock.disable].
/// You do not need to worry about making redundant calls, e.g. calling
/// [Wakelock.enable] when the wakelock is already enabled as the plugin handles
/// this for you, i.e. it checks the status to determine if the wakelock is
/// already enabled or disabled.
/// If you want the flexibility to pass a [bool] to control whether the wakelock
/// should be enabled or disabled, you can use [Wakelock.toggle].
///
/// The [Wakelock.enabled] getter allows you to retrieve the current wakelock
/// status of the device..
class Wakelock {
/// Enables the wakelock.
///
/// This can simply be called using `Wakelock.enable()` and does not return
/// anything.
/// You can await the [Future] to wait for the operation to complete.
///
/// See also:
/// * [toggle], which allows to enable or disable using a [bool] parameter.
static Future<void> enable() => toggle(enable: true);
/// Disables the wakelock.
///
/// This can simply be called using `Wakelock.disable()` and does not return
/// anything.
/// You can await the [Future] to wait for the operation to complete.
///
/// See also:
/// * [toggle], which allows to enable or disable using a [bool] parameter.
static Future<void> disable() => toggle(enable: false);
/// Toggles the wakelock on or off.
///
/// You can simply use this function to toggle the wakelock using a [bool]
/// value (for the [enable] parameter).
///
/// ```dart
/// // This line keeps the screen on.
/// Wakelock.toggle(enable: true);
///
/// bool enableWakelock = false;
/// // The following line disables the wakelock.
/// Wakelock.toggle(enable: enableWakelock);
/// ```
///
/// You can await the [Future] to wait for the operation to complete.
static Future<void> toggle({
@required bool enable,
@Deprecated('Use the `enable` parameter instead.') bool on,
}) {
// The checks allow only `on` to be used in the case of old code and
// they encourage to use only `enable` instead (combined with the
// deprecation warning).
assert(enable != null || on != null,
'The `enable` parameter must not be null when toggling the wakelock.');
assert(
on == null || enable == null,
'The `on` parameter has been deprecated; '
'specify only the `enable` parameter instead.');
return _wakelockPlatformInstance.toggle(enable: enable ?? on);
}
/// Returns whether the wakelock is currently enabled or not.
///
/// If you want to retrieve the current wakelock status, you will have to call
/// [Wakelock.enabled] and await its result:
///
/// ```dart
/// bool wakelockEnabled = await Wakelock.enabled;
/// ```
static Future<bool> get enabled => _wakelockPlatformInstance.enabled;
/// Returns the current wakelock status.
@Deprecated('Use the `enabled` getter instead.')
static Future<bool> get isEnabled => enabled;
}
... ...
import 'package:pigeon/pigeon.dart';
/// Message for toggling the wakelock on the platform side.
class ToggleMessage {
bool enable;
}
/// Message for reporting the wakelock state from the platform side.
class IsEnabledMessage {
bool enabled;
}
@HostApi(dartHostTestHandler: 'TestWakelockApi')
abstract class WakelockApi {
void toggle(ToggleMessage msg);
IsEnabledMessage isEnabled();
}
void configurePigeon(PigeonOptions options) {
options
..dartOut = '../wakelock_platform_interface/lib/messages.dart'
..objcHeaderOut = 'ios/Classes/messages.h'
..objcSourceOut = 'ios/Classes/messages.m'
..objcOptions.prefix = 'FLT'
..javaOut = 'android/src/main/java/creativemaybeno/wakelock/Messages.java'
..javaOptions.package = 'creativemaybeno.wakelock';
}
... ...
name: wakelock
description: This plugin allows you to keep Android and iOS devices awake, i.e. prevent the screen from sleeping by toggling the wakelock of the device on or off.
version: 0.1.4+2
homepage: https://github.com/creativecreatorormaybenot/wakelock
description: >-2
Plugin that allows you to keep the device screen awake, i.e. prevent the screen from sleeping on
Android, iOS, and web.
version: 0.2.0
homepage: https://github.com/creativecreatorormaybenot/wakelock/tree/master/wakelock
environment:
sdk: ">=2.7.0 <3.0.0"
flutter: ">=1.12.0 <2.0.0"
sdk: ">=2.8.0 <3.0.0"
flutter: ">=1.20.0 <2.0.0"
dependencies:
flutter:
sdk: flutter
wakelock_web:
path: wakelock_web/
dev_dependencies:
pedantic: 1.9.0
meta: ^1.2.0
wakelock_platform_interface: ^0.1.0
wakelock_web: ^0.1.0
dev_dependencies:
flutter_test:
sdk: flutter
dependency_overrides:
pedantic: 1.9.0
pedantic: ^1.9.2
pigeon: 0.1.7
flutter:
plugin:
platforms:
android:
package: creativecreatorormaybenot.wakelock
package: creativemaybeno.wakelock
pluginClass: WakelockPlugin
ios:
pluginClass: WakelockPlugin
web:
default_package: wakelock_web
assets:
- assets/NoSleep.js
... ...
import 'package:flutter_test/flutter_test.dart';
import 'package:wakelock/wakelock.dart';
import 'package:wakelock_platform_interface/messages.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
group('$Wakelock', () {
FakeWakelockApi fakeWakelock;
setUpAll(() {
fakeWakelock = FakeWakelockApi();
});
test('toggle enable non-null assertion', () {
expect(() => Wakelock.toggle(enable: null), throwsAssertionError);
});
test('enable', () async {
await Wakelock.enable();
expect(fakeWakelock.calls.last, 'toggle');
expect(fakeWakelock.toggleMessage.enable, isTrue);
});
test('disable', () async {
await Wakelock.disable();
expect(fakeWakelock.calls.last, 'toggle');
expect(fakeWakelock.toggleMessage.enable, isFalse);
});
test('toggle', () async {
await Wakelock.toggle(enable: false);
expect(fakeWakelock.calls.last, 'toggle');
expect(fakeWakelock.toggleMessage.enable, isFalse);
await Wakelock.toggle(enable: true);
expect(fakeWakelock.calls.last, 'toggle');
expect(fakeWakelock.toggleMessage.enable, isTrue);
});
test('enabled', () async {
expect(Wakelock.enabled, completion(isTrue));
expect(fakeWakelock.calls.last, 'isEnabled');
});
});
}
class FakeWakelockApi extends TestWakelockApi {
FakeWakelockApi() {
TestWakelockApi.setup(this);
}
final calls = <String>[];
ToggleMessage toggleMessage;
@override
IsEnabledMessage isEnabled() {
calls.add('isEnabled');
return IsEnabledMessage()..enabled = true;
}
@override
void toggle(ToggleMessage message) {
calls.add('toggle');
toggleMessage = message;
;
}
}
... ...
# Miscellaneous
*.class
*.log
*.pyc
*.swp
.DS_Store
.atom/
.buildlog/
.history
.svn/
.metadata
# IntelliJ related
*.iml
*.ipr
*.iws
.idea/
# The .vscode folder contains launch configuration and tasks you configure in
# VS Code which you may wish to be included in version control, so this line
# is commented out by default.
#.vscode/
# Flutter/Dart/Pub related
**/doc/api/
.dart_tool/
.flutter-plugins
.flutter-plugins-dependencies
.packages
.pub-cache/
.pub/
build/
pubspec.lock
# Android related
**/android/**/gradle-wrapper.jar
**/android/.gradle
**/android/captures/
**/android/gradlew
**/android/gradlew.bat
**/android/local.properties
**/android/**/GeneratedPluginRegistrant.java
# iOS/XCode related
**/ios/**/*.mode1v3
**/ios/**/*.mode2v3
**/ios/**/*.moved-aside
**/ios/**/*.pbxuser
**/ios/**/*.perspectivev3
**/ios/**/*sync/
**/ios/**/.sconsign.dblite
**/ios/**/.tags*
**/ios/**/.vagrant/
**/ios/**/DerivedData/
**/ios/**/Icon?
**/ios/**/Pods/
**/ios/**/.symlinks/
**/ios/**/profile
**/ios/**/xcuserdata
**/ios/.generated/
**/ios/Flutter/App.framework
**/ios/Flutter/Flutter.framework
**/ios/Flutter/Flutter.podspec
**/ios/Flutter/Generated.xcconfig
**/ios/Flutter/app.flx
**/ios/Flutter/app.zip
**/ios/Flutter/flutter_assets/
**/ios/Flutter/flutter_export_environment.sh
**/ios/ServiceDefinitions.json
**/ios/Runner/GeneratedPluginRegistrant.*
# Exceptions to above rules.
!**/ios/**/default.mode1v3
!**/ios/**/default.mode2v3
!**/ios/**/default.pbxuser
!**/ios/**/default.perspectivev3
... ...
## 0.1.0
* Initial release.
... ...
BSD 3-Clause License
Copyright (c) 2020, creativecreatorormaybenot
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
... ...
# wakelock_platform_interface [![Pub version](https://img.shields.io/pub/v/wakelock_platform_interface.svg)](https://pub.dev/packages/wakelock_platform_interface) [![GitHub stars](https://img.shields.io/github/stars/creativecreatorormaybenot/wakelock.svg)](https://github.com/creativecreatorormaybenot/wakelock)
A common platform interface for the [wakelock plugin][wakelock GitHub] used by the different
platform implementations.
The practices for the implementation have been adapted from the [video_player_platform_interface]
package.
[wakelock GitHub]: https://github.com/creativecreatorormaybenot/wakelock
[video_player_platform_interface]: https://github.com/flutter/plugins/tree/master/packages/video_player/video_player_platform_interface
... ...
// Autogenerated from Pigeon (v0.1.7), do not edit directly.
// See also: https://pub.dev/packages/pigeon
// ignore_for_file: public_member_api_docs, non_constant_identifier_names, avoid_as, unused_import
// @dart = 2.8
import 'dart:async';
import 'package:flutter/services.dart';
import 'dart:typed_data' show Uint8List, Int32List, Int64List, Float64List;
class ToggleMessage {
bool enable;
// ignore: unused_element
Map<dynamic, dynamic> _toMap() {
final Map<dynamic, dynamic> pigeonMap = <dynamic, dynamic>{};
pigeonMap['enable'] = enable;
return pigeonMap;
}
// ignore: unused_element
static ToggleMessage _fromMap(Map<dynamic, dynamic> pigeonMap) {
if (pigeonMap == null) {
return null;
}
final ToggleMessage result = ToggleMessage();
result.enable = pigeonMap['enable'];
return result;
}
}
class IsEnabledMessage {
bool enabled;
// ignore: unused_element
Map<dynamic, dynamic> _toMap() {
final Map<dynamic, dynamic> pigeonMap = <dynamic, dynamic>{};
pigeonMap['enabled'] = enabled;
return pigeonMap;
}
// ignore: unused_element
static IsEnabledMessage _fromMap(Map<dynamic, dynamic> pigeonMap) {
if (pigeonMap == null) {
return null;
}
final IsEnabledMessage result = IsEnabledMessage();
result.enabled = pigeonMap['enabled'];
return result;
}
}
class WakelockApi {
Future<void> toggle(ToggleMessage arg) async {
final Map<dynamic, dynamic> requestMap = arg._toMap();
const BasicMessageChannel<dynamic> channel = BasicMessageChannel<dynamic>(
'dev.flutter.pigeon.WakelockApi.toggle', StandardMessageCodec());
final Map<dynamic, dynamic> replyMap = await channel.send(requestMap);
if (replyMap == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
details: null);
} else if (replyMap['error'] != null) {
final Map<dynamic, dynamic> error = replyMap['error'];
throw PlatformException(
code: error['code'],
message: error['message'],
details: error['details']);
} else {
// noop
}
}
Future<IsEnabledMessage> isEnabled() async {
const BasicMessageChannel<dynamic> channel = BasicMessageChannel<dynamic>(
'dev.flutter.pigeon.WakelockApi.isEnabled', StandardMessageCodec());
final Map<dynamic, dynamic> replyMap = await channel.send(null);
if (replyMap == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
details: null);
} else if (replyMap['error'] != null) {
final Map<dynamic, dynamic> error = replyMap['error'];
throw PlatformException(
code: error['code'],
message: error['message'],
details: error['details']);
} else {
return IsEnabledMessage._fromMap(replyMap['result']);
}
}
}
abstract class TestWakelockApi {
void toggle(ToggleMessage arg);
IsEnabledMessage isEnabled();
static void setup(TestWakelockApi api) {
{
const BasicMessageChannel<dynamic> channel = BasicMessageChannel<dynamic>(
'dev.flutter.pigeon.WakelockApi.toggle', StandardMessageCodec());
channel.setMockMessageHandler((dynamic message) async {
final Map<dynamic, dynamic> mapMessage =
message as Map<dynamic, dynamic>;
final ToggleMessage input = ToggleMessage._fromMap(mapMessage);
api.toggle(input);
return <dynamic, dynamic>{};
});
}
{
const BasicMessageChannel<dynamic> channel = BasicMessageChannel<dynamic>(
'dev.flutter.pigeon.WakelockApi.isEnabled', StandardMessageCodec());
channel.setMockMessageHandler((dynamic message) async {
final IsEnabledMessage output = api.isEnabled();
return <dynamic, dynamic>{'result': output._toMap()};
});
}
}
}
... ...
import 'package:wakelock_platform_interface/messages.dart';
import 'package:wakelock_platform_interface/wakelock_platform_interface.dart';
/// Method channel implementation of the [WakelockPlatformInterface].
class MethodChannelWakelock extends WakelockPlatformInterface {
final _api = WakelockApi();
@override
Future<bool> get enabled async {
final message = await _api.isEnabled();
return message.enabled;
}
@override
Future<void> toggle({bool enable}) async {
assert(enable != null);
final message = ToggleMessage();
message.enable = enable;
await _api.toggle(message);
}
}
... ...
import 'package:meta/meta.dart';
import 'package:wakelock_platform_interface/method_channel_wakelock.dart';
/// The interface that implementations of wakelock must implement.
///
/// Platform implementations should extend this class rather than implement it
/// because `implements` does not consider newly added methods to be breaking
/// changes. Extending this class (using `extends`) ensures that the subclass
/// will get the default implementation.
abstract class WakelockPlatformInterface {
static WakelockPlatformInterface _instance = MethodChannelWakelock();
/// The default instance of the [WakelockPlatformInterface] to use.
///
/// Platform-specific plugins should override this with their own
/// platform-specific class that extends [WakelockPlatformInterface] when they
/// register themselves.
///
/// Defaults to [MethodChannelWakelock].
static WakelockPlatformInterface get instance => _instance;
/// Sets the default instance of the [WakelockPlatformInterface].
///
/// This will be removed after https://github.com/flutter/flutter/issues/43368
/// has been resolved.
static set instance(WakelockPlatformInterface instance) {
if (!instance.isMock) {
try {
instance._verifyProvidesDefaultImplementations();
} on NoSuchMethodError catch (_) {
throw AssertionError(
'Platform interfaces must not be implemented with `implements`');
}
}
_instance = instance;
}
/// Only mock implementations should set this to true.
///
/// Mockito mocks are implementing this class with `implements`, which is
/// forbidden for anything other than mocks (see class docs). This property
/// provides a backdoor for mockito mocks to skip the verification that the
/// class is not implemented with `implements`.
@visibleForTesting
bool get isMock => false;
/// Toggles the wakelock based on the given [enable] value.
Future<void> toggle({@required bool enable}) {
throw UnimplementedError('toggle() has not been implemented.');
}
/// Returns whether the wakelock is enabled or not.
Future<bool> get enabled {
throw UnimplementedError('isEnabled has not been implemented.');
}
// This method makes sure that VideoPlayer isn't implemented with `implements`.
//
// See class doc for more details on why implementing this class is forbidden.
//
// This private method is called by the instance setter, which fails if the
// class is implemented with `implements`.
void _verifyProvidesDefaultImplementations() {}
}
... ...
name: wakelock_platform_interface
description: >-2
A common platform interface for the wakelock plugin used by the different platform
implementations.
version: 0.1.0
homepage: >-2
https://github.com/creativecreatorormaybenot/wakelock/tree/master/wakelock_platform_interface
environment:
sdk: ">=2.8.0 <3.0.0"
flutter: ">=1.17.0 <2.0.0"
dependencies:
flutter:
sdk: flutter
meta: ^1.2.0
dev_dependencies:
flutter_test:
sdk: flutter
mockito: ^4.1.2
pedantic: ^1.9.2
... ...
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/mockito.dart';
import 'package:wakelock_platform_interface/messages.dart';
import 'package:wakelock_platform_interface/method_channel_wakelock.dart';
import 'package:wakelock_platform_interface/wakelock_platform_interface.dart';
class _ApiLogger implements TestWakelockApi {
final List<String> log = [];
ToggleMessage toggleMessage;
@override
IsEnabledMessage isEnabled() {
log.add('isEnabled');
return IsEnabledMessage()..enabled = true;
}
@override
void toggle(ToggleMessage message) {
log.add('toggle');
toggleMessage = message;
}
}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
group('$WakelockPlatformInterface', () {
test('$MethodChannelWakelock() is the default instance', () {
expect(WakelockPlatformInterface.instance,
isInstanceOf<MethodChannelWakelock>());
});
test('Cannot be implemented with `implements`', () {
expect(() {
WakelockPlatformInterface.instance =
ImplementsWakelockPlatformInterface();
}, throwsA(isInstanceOf<AssertionError>()));
});
test('Can be mocked with `implements`', () {
final mock = ImplementsWakelockPlatformInterface();
when(mock.isMock).thenReturn(true);
WakelockPlatformInterface.instance = mock;
});
test('Can be extended', () {
WakelockPlatformInterface.instance = ExtendsVideoPlayerPlatform();
});
});
group('$MethodChannelWakelock', () {
final wakelock = MethodChannelWakelock();
_ApiLogger logger;
setUp(() {
logger = _ApiLogger();
TestWakelockApi.setup(logger);
});
test('toggle', () async {
await wakelock.toggle(enable: true);
expect(logger.log.last, 'toggle');
expect(logger.toggleMessage.enable, isTrue);
await wakelock.toggle(enable: false);
expect(logger.log.last, 'toggle');
expect(logger.log, hasLength(2));
expect(logger.toggleMessage.enable, isFalse);
});
test('enabled', () async {
final enabled = await wakelock.enabled;
expect(logger.log.last, 'isEnabled');
expect(enabled, isTrue);
});
});
}
class ImplementsWakelockPlatformInterface extends Mock
implements WakelockPlatformInterface {}
class ExtendsVideoPlayerPlatform extends WakelockPlatformInterface {}
... ...
... ... @@ -8,6 +8,7 @@
.buildlog/
.history
.svn/
.metadata
# IntelliJ related
*.iml
... ... @@ -28,24 +29,48 @@
.packages
.pub-cache/
.pub/
/build/
# Web related
lib/generated_plugin_registrant.dart
build/
pubspec.lock
# Symbolication related
app.*.symbols
# Android related
**/android/**/gradle-wrapper.jar
**/android/.gradle
**/android/captures/
**/android/gradlew
**/android/gradlew.bat
**/android/local.properties
**/android/**/GeneratedPluginRegistrant.java
# Obfuscation related
app.*.map.json
# iOS/XCode related
**/ios/**/*.mode1v3
**/ios/**/*.mode2v3
**/ios/**/*.moved-aside
**/ios/**/*.pbxuser
**/ios/**/*.perspectivev3
**/ios/**/*sync/
**/ios/**/.sconsign.dblite
**/ios/**/.tags*
**/ios/**/.vagrant/
**/ios/**/DerivedData/
**/ios/**/Icon?
**/ios/**/Pods/
**/ios/**/.symlinks/
**/ios/**/profile
**/ios/**/xcuserdata
**/ios/.generated/
**/ios/Flutter/App.framework
**/ios/Flutter/Flutter.framework
**/ios/Flutter/Flutter.podspec
**/ios/Flutter/Generated.xcconfig
**/ios/Flutter/app.flx
**/ios/Flutter/app.zip
**/ios/Flutter/flutter_assets/
**/ios/Flutter/flutter_export_environment.sh
**/ios/ServiceDefinitions.json
**/ios/Runner/GeneratedPluginRegistrant.*
# Exceptions to above rules.
!/packages/flutter_tools/test/data/dart_dependencies_test/**/.packages
# Cleanliness
pubspec.lock
.metadata
test
ios
android
web
!**/ios/**/default.mode1v3
!**/ios/**/default.mode2v3
!**/ios/**/default.pbxuser
!**/ios/**/default.perspectivev3
... ...
../CHANGELOG.md
\ No newline at end of file
## 0.1.0
* Initial release.
... ...
../LICENSE
\ No newline at end of file
BSD 3-Clause License
Copyright (c) 2020, creativecreatorormaybenot
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
... ...
../README.md
\ No newline at end of file
# wakelock_web [![Pub version](https://img.shields.io/pub/v/wakelock_platform_interface.svg)](https://pub.dev/packages/wakelock_web) [![GitHub stars](https://img.shields.io/github/stars/creativecreatorormaybenot/wakelock.svg)](https://github.com/creativecreatorormaybenot/wakelock)
Web platform implementation of the `wakelock_platform_interface` for the
[wakelock plugin][wakelock GitHub].
## Getting started
If you want to use the wakelock plugin on web, see the [main `wakelock` plugin package](https://pub.dev/packages/wakelock).
## Implementation
The web implementation is based on [`NoSleep.js`](https://github.com/richtr/NoSleep.js/), i.e.
the `assets` include a version that was modified to work with the wakelock plugin.
This supports the [Screen Wake Lock API](https://developer.mozilla.org/en-US/docs/Web/API/Screen_Wake_Lock_API)
if available.
[wakelock GitHub]: https://github.com/creativecreatorormaybenot/wakelock
... ...
var webm =
'data:video/webm;base64,GkXfo0AgQoaBAUL3gQFC8oEEQvOBCEKCQAR3ZWJtQoeBAkKFgQIYU4BnQI0VSalmQCgq17FAAw9CQE2AQAZ3aGFtbXlXQUAGd2hhbW15RIlACECPQAAAAAAAFlSua0AxrkAu14EBY8WBAZyBACK1nEADdW5khkAFVl9WUDglhohAA1ZQOIOBAeBABrCBCLqBCB9DtnVAIueBAKNAHIEAAIAwAQCdASoIAAgAAUAmJaQAA3AA/vz0AAA=';
'data:video/webm;base64,GkXfo0AgQoaBAUL3gQFC8oEEQvOBCEKCQAR3ZWJtQoeBAkKFgQIYU4BnQI0VSalmQCgq17FAAw9CQE2AQAZ3aGFtbXlXQUAGd2hhbW15RIlACECPQAAAAAAAFlSua0AxrkAu14EBY8WBAZyBACK1nEADdW5khkAFVl9WUDglhohAA1ZQOIOBAeBABrCBCLqBCB9DtnVAIueBAKNAHIEAAIAwAQCdASoIAAgAAUAmJaQAA3AA/vz0AAA='
var mp4 =
'data:video/mp4;base64,AAAAIGZ0eXBtcDQyAAACAGlzb21pc28yYXZjMW1wNDEAAAAIZnJlZQAACKBtZGF0AAAC8wYF///v3EXpvebZSLeWLNgg2SPu73gyNjQgLSBjb3JlIDE0MiByMjQ3OSBkZDc5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AAidzdGJsAAAAZ3N0c2QAAAAAAAAAAQAAAFdtcDRhAAAAAAAAAAEAAAAAAAAAAAACABAAAAAArEQAAAAAADNlc2RzAAAAAAOAgIAiAAIABICAgBRAFQAAAAADDUAAAAAABYCAgAISEAaAgIABAgAAABhzdHRzAAAAAAAAAAEAAABYAAAEAAAAABxzdHNjAAAAAAAAAAEAAAABAAAAAQAAAAEAAAAUc3RzegAAAAAAAAAGAAAAWAAAAXBzdGNvAAAAAAAAAFgAAAOBAAADhwAAA5oAAAOtAAADswAAA8oAAAPfAAAD5QAAA/gAAAQLAAAEEQAABCgAAAQ9AAAEUAAABFYAAARpAAAEgAAABIYAAASbAAAErgAABLQAAATHAAAE3gAABPMAAAT5AAAFDAAABR8AAAUlAAAFPAAABVEAAAVXAAAFagAABX0AAAWDAAAFmgAABa8AAAXCAAAFyAAABdsAAAXyAAAF+AAABg0AAAYgAAAGJgAABjkAAAZQAAAGZQAABmsAAAZ+AAAGkQAABpcAAAauAAAGwwAABskAAAbcAAAG7wAABwYAAAcMAAAHIQAABzQAAAc6AAAHTQAAB2QAAAdqAAAHfwAAB5IAAAeYAAAHqwAAB8IAAAfXAAAH3QAAB/AAAAgDAAAICQAACCAAAAg1AAAIOwAACE4AAAhhAAAIeAAACH4AAAiRAAAIpAAACKoAAAiwAAAItgAACLwAAAjCAAAAFnVkdGEAAAAObmFtZVN0ZXJlbwAAAHB1ZHRhAAAAaG1ldGEAAAAAAAAAIWhkbHIAAAAAAAAAAG1kaXJhcHBsAAAAAAAAAAAAAAAAO2lsc3QAAAAzqXRvbwAAACtkYXRhAAAAAQAAAABIYW5kQnJha2UgMC4xMC4yIDIwMTUwNjExMDA='
var _createClass = (function () {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ('value' in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
var descriptor = props[i]
descriptor.enumerable = descriptor.enumerable || false
descriptor.configurable = true
if ('value' in descriptor) descriptor.writable = true
Object.defineProperty(target, descriptor.key, descriptor)
}
}
return function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);
if (staticProps) defineProperties(Constructor, staticProps);
return Constructor;
};
})();
if (protoProps) defineProperties(Constructor.prototype, protoProps)
if (staticProps) defineProperties(Constructor, staticProps)
return Constructor
}
})()
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError('Cannot call a class as a function');
throw new TypeError('Cannot call a class as a function')
}
}
... ... @@ -40,54 +40,57 @@ var oldIOS =
.replace('_', '.')
.replace('_', '')
) < 10 &&
!window.MSStream;
!window.MSStream
// Detect native Wake Lock API support
var nativeWakeLock = 'wakeLock' in navigator;
var nativeWakeLock = 'wakeLock' in navigator
var NoSleep = (function () {
var _releasedNative = true
var _nativeRequestInProgress = false
function NoSleep() {
var _this = this;
var _this = this
_classCallCheck(this, NoSleep);
_classCallCheck(this, NoSleep)
if (nativeWakeLock) {
this._wakeLock = null;
this._wakeLock = null
var handleVisibilityChange = function handleVisibilityChange() {
if (
_this._wakeLock !== null &&
document.visibilityState === 'visible'
) {
_this.enable();
_this.enable()
}
};
document.addEventListener('visibilitychange', handleVisibilityChange);
document.addEventListener('fullscreenchange', handleVisibilityChange);
}
document.addEventListener('visibilitychange', handleVisibilityChange)
document.addEventListener('fullscreenchange', handleVisibilityChange)
} else if (oldIOS) {
this.noSleepTimer = null;
this.noSleepTimer = null
} else {
// Set up no sleep video element
this.noSleepVideo = document.createElement('video');
this.noSleepVideo = document.createElement('video')
this.noSleepVideo.setAttribute('title', 'No Sleep');
this.noSleepVideo.setAttribute('playsinline', '');
this.noSleepVideo.setAttribute('title', 'No Sleep')
this.noSleepVideo.setAttribute('playsinline', '')
this._addSourceToVideo(this.noSleepVideo, 'webm', webm);
this._addSourceToVideo(this.noSleepVideo, 'mp4', mp4);
this._addSourceToVideo(this.noSleepVideo, 'webm', webm)
this._addSourceToVideo(this.noSleepVideo, 'mp4', mp4)
this.noSleepVideo.addEventListener('loadedmetadata', function () {
if (_this.noSleepVideo.duration <= 1) {
// webm source
_this.noSleepVideo.setAttribute('loop', '');
_this.noSleepVideo.setAttribute('loop', '')
} else {
// mp4 source
_this.noSleepVideo.addEventListener('timeupdate', function () {
if (_this.noSleepVideo.currentTime > 0.5) {
_this.noSleepVideo.currentTime = Math.random();
_this.noSleepVideo.currentTime = Math.random()
}
});
})
}
});
})
}
}
... ... @@ -95,46 +98,48 @@ var NoSleep = (function () {
{
key: '_addSourceToVideo',
value: function _addSourceToVideo(element, type, dataURI) {
var source = document.createElement('source');
source.src = dataURI;
source.type = 'video/' + type;
element.appendChild(source);
var source = document.createElement('source')
source.src = dataURI
source.type = 'video/' + type
element.appendChild(source)
},
},
{
key: 'enable',
value: function enable() {
var _this2 = this;
var _this2 = this
if (nativeWakeLock) {
_nativeRequestInProgress = true
navigator.wakeLock
.request('screen')
.then(function (wakeLock) {
_this2._wakeLock = wakeLock;
console.log('Wake Lock active.');
_releasedNative = false
_nativeRequestInProgress = false
_this2._wakeLock = wakeLock
_this2._wakeLock.addEventListener('release', function () {
// ToDo: Potentially emit an event for the page to observe since
// Wake Lock releases happen when page visibility changes.
// (https://web.dev/wakelock/#wake-lock-lifecycle)
console.log('Wake Lock released.');
});
_releasedNative = true
_this2._wakeLock = null
})
})
.catch(function (err) {
console.error(err.name + ', ' + err.message);
});
_nativeRequestInProgress = false
console.error(err.name + ', ' + err.message)
})
} else if (oldIOS) {
this.disable();
this.disable()
console.warn(
'\n NoSleep enabled for older iOS devices. This can interrupt\n active or long-running network requests from completing successfully.\n See https://github.com/richtr/NoSleep.js/issues/15 for more details.\n '
);
)
this.noSleepTimer = window.setInterval(function () {
if (!document.hidden) {
window.location.href = window.location.href.split('#')[0];
window.setTimeout(window.stop, 0);
window.location.href = window.location.href.split('#')[0]
window.setTimeout(window.stop, 0)
}
}, 15000);
}, 15000)
} else {
this.noSleepVideo.play();
this.noSleepVideo.play()
}
},
},
... ... @@ -142,37 +147,84 @@ var NoSleep = (function () {
key: 'disable',
value: function disable() {
if (nativeWakeLock) {
if(this._wakeLock != null) {
this._wakeLock.release();
if (this._wakeLock != null) {
_releasedNative = true
this._wakeLock.release()
}
this._wakeLock = null;
this._wakeLock = null
} else if (oldIOS) {
if (this.noSleepTimer) {
console.warn(
'\n NoSleep now disabled for older iOS devices.\n '
);
window.clearInterval(this.noSleepTimer);
this.noSleepTimer = null;
)
window.clearInterval(this.noSleepTimer)
this.noSleepTimer = null
}
} else {
this.noSleepVideo.pause();
this.noSleepVideo.pause()
}
},
},
{
key: 'isEnabled',
value: function isEnabled() {
if (oldIOS) {
return this.noSleepTimer != null;
key: 'enabled',
value: async function enabled() {
if (nativeWakeLock) {
if (_nativeRequestInProgress == true) {
// Wait until the request is done.
while (true) {
// Wait for 42 milliseconds.
await new Promise((resolve, reject) => setTimeout(resolve, 42))
if (_nativeRequestInProgress == false) {
break
}
}
}
// todo: use WakeLockSentinel.released when that is available (https://developer.mozilla.org/en-US/docs/Web/API/WakeLockSentinel/released)
if (_releasedNative != false) {
return false
}
return true
} else if (oldIOS) {
return this.noSleepTimer != null
} else {
return !this.noSleepVideo.paused;
if (this.noSleepVideo == undefined) {
return false
}
return !this.noSleepVideo.paused
}
},
},
]);
])
return NoSleep
})()
var noSleep = new NoSleep()
return NoSleep;
})();
var Wakelock = {
enabled: async function () {
try {
return noSleep.enabled()
} catch (e) {
return false
}
},
toggle: async function (enable) {
if (enable) {
noSleep.enable()
} else {
noSleep.disable()
}
},
}
var Wakelock = new NoSleep();
if (nativeWakeLock != true) {
// The first non-native call sometimes throws an error, however,
// the error does not leak the try-catch above. Therefore, this
// is an easy fix that realiably works.
Wakelock.enabled()
}
... ...
typedef Func1<A, R> = R Function(A a);
... ...
@JS('Wakelock')
library wakelock.js;
import 'package:js/js.dart';
import 'package:wakelock_web/src/promise.dart';
/// Toggles the JS wakelock.
external toggle(bool enable);
/// Returns a JS promise of whether the wakelock is enabled or not.
external PromiseJsImpl<bool> enabled();
... ...
@JS()
library firebase.es6_interop;
import 'package:js/js.dart';
import 'package:wakelock_web/src/func.dart';
/// JavaScript promise typing.
@JS('Promise')
class PromiseJsImpl<T> {
/// Promise constructor for JS code.
external PromiseJsImpl(Function resolver);
/// Attaches callbacks to a JS promise.
external PromiseJsImpl then([Func1 onResolve, Func1 onReject]);
}
... ...
@JS('Wakelock')
library wakelock.js;
import 'package:js/js.dart';
external enable();
external disable();
external bool isEnabled();
import 'dart:async';
import 'dart:js';
import 'package:flutter/services.dart';
import 'package:flutter_web_plugins/flutter_web_plugins.dart';
import 'package:import_js_library/import_js_library.dart';
import 'wakelock_js.dart' as wakelock;
/// A web implementation of the Wakelock plugin.
class WakelockWebPlugin {
final _isNativeWakelockSupported =
context['navigator'].hasProperty('wakeLock');
var _enabled = false;
import 'package:js/js.dart';
import 'package:wakelock_platform_interface/wakelock_platform_interface.dart';
import 'package:wakelock_web/src/js_wakelock.dart' as Wakelock;
/// The web implementation of the [WakelockPlatformInterface].
///
/// This class implements the `wakelock` plugin functionality for web.
class WakelockWeb extends WakelockPlatformInterface {
/// Registers [WakelockWeb] as the default instance of the
/// [WakelockPlatformInterface].
static void registerWith(Registrar registrar) {
final MethodChannel channel = MethodChannel(
'wakelock',
const StandardMethodCodec(),
registrar.messenger,
);
// Import a version of `NoSleep.js` that was adjusted for the wakelock
// plugin.
importJsLibrary(
url: 'assets/no_sleep.js', flutterPluginName: 'wakelock_web');
/// Import JS library
importJsLibrary(url: './assets/NoSleep.js', flutterPluginName: 'wakelock');
final pluginInstance = WakelockWebPlugin();
channel.setMethodCallHandler(pluginInstance.handleMethodCall);
}
/// Handles method calls over the MethodChannel of this plugin.
/// Note: Check the "federated" architecture for a new way of doing this:
/// https://flutter.dev/go/federated-plugins
Future<dynamic> handleMethodCall(MethodCall call) async {
switch (call.method) {
case 'toggle':
final bool enable = call.arguments['enable'];
return Future.value(_toggle(enable));
break;
case 'isEnabled':
return Future.value(_isEnabled());
break;
default:
throw PlatformException(
code: 'Unimplemented',
details: 'wakelock_web for web doesn\'t implement \'${call.method}\'',
);
}
WakelockPlatformInterface.instance = WakelockWeb();
}
_toggle(bool enable) {
if (enable) {
wakelock.enable();
} else {
wakelock.disable();
}
@override
Future<void> toggle({bool enable}) async {
assert(enable != null);
_enabled = enable;
Wakelock.toggle(enable);
}
bool _isEnabled() {
/// If the native WebLock API is supported
/// since these APIs are async in nature
/// Give immediate boolean value based on `_enabled`
if (_isNativeWakelockSupported) {
return _enabled;
}
@override
Future<bool> get enabled async {
final completer = Completer<bool>();
Wakelock.enabled().then(
// onResolve
allowInterop((value) {
assert(value is bool);
completer.complete(value);
}),
// onReject
allowInterop((error) {
completer.completeError(error);
}),
);
return wakelock.isEnabled();
return completer.future;
}
}
... ...
name: wakelock_web
description: This plugin allows you to keep the browser devices awake, i.e. prevent the screen from sleeping by toggling the wakelock of the device on or off.
version: 0.1.4+2
homepage: https://github.com/creativecreatorormaybenot/wakelock
description: Web platform implementation of the wakelock_platform_interface for the wakelock plugin.
version: 0.1.0
homepage: https://github.com/creativecreatorormaybenot/wakelock/tree/master/wakelock_web
environment:
sdk: ">=2.7.0 <3.0.0"
sdk: ">=2.8.0 <3.0.0"
flutter: ">=1.20.0 <2.0.0"
dependencies:
... ... @@ -12,51 +12,27 @@ dependencies:
sdk: flutter
flutter_web_plugins:
sdk: flutter
import_js_library: ^1.0.1
js: ^0.6.2
wakelock_platform_interface: ^0.1.0
dev_dependencies:
flutter_test:
sdk: flutter
# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec
pedantic: ^1.9.2
wakelock:
path: ../wakelock
# The following section is specific to Flutter.
flutter:
# This section identifies this Flutter project as a plugin project.
# The 'pluginClass' and Android 'package' identifiers should not ordinarily
# be modified. They are used by the tooling to maintain consistency when
# adding or updating assets for this project.
plugin:
platforms:
web:
pluginClass: WakelockWebPlugin
pluginClass: WakelockWeb
fileName: wakelock_web.dart
#
# For details regarding assets in packages, see
# https://flutter.dev/assets-and-images/#from-packages
#
# An image asset can refer to one or more resolution-specific "variants", see
# https://flutter.dev/assets-and-images/#resolution-aware.
# To add custom fonts to your plugin 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.dev/custom-fonts/#from-packages
assets:
- assets/no_sleep.js
... ...
import 'package:flutter_test/flutter_test.dart';
import 'package:wakelock/wakelock.dart';
import 'package:wakelock_platform_interface/wakelock_platform_interface.dart';
import 'package:wakelock_web/wakelock_web.dart';
@TestOn('browser')
void main() {
group('$WakelockWeb', () {
setUpAll(() async {
// todo: the web tests do not work as the JS library import does not work.
WakelockPlatformInterface.instance = WakelockWeb();
});
test('$WakelockWeb set as default instance', () {
expect(WakelockPlatformInterface.instance, isA<WakelockWeb>());
});
test('initially disabled', () async {
expect(Wakelock.enabled, completion(isFalse));
});
test('enable', () async {
await Wakelock.enable();
expect(Wakelock.enabled, completion(isTrue));
});
test('disable', () async {
await Wakelock.disable();
expect(Wakelock.enabled, completion(isFalse));
});
test('toggle', () async {
await Wakelock.toggle(enable: true);
expect(Wakelock.enabled, completion(isTrue));
await Wakelock.toggle(enable: false);
expect(Wakelock.enabled, completion(isFalse));
});
});
}
... ...