Skip to content

Commit

Permalink
Updated to null safety
Browse files Browse the repository at this point in the history
  • Loading branch information
LJaraCastillo committed Jan 24, 2022
1 parent 4d35759 commit 1296ced
Show file tree
Hide file tree
Showing 18 changed files with 90 additions and 86 deletions.
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@
.history
.svn/
/android/libs/flutter.jar

.dart_tool/
.flutter-plugins-dependencies
flutter_export_environment.sh
# IntelliJ related
*.iml
*.ipr
Expand Down
10 changes: 5 additions & 5 deletions android/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -2,30 +2,30 @@ group 'com.example.fluttersensors'
version '1.0-SNAPSHOT'

buildscript {
ext.kotlin_version = '1.3.61'
ext.kotlin_version = '1.6.10'
repositories {
google()
jcenter()
mavenCentral()
}

dependencies {
classpath 'com.android.tools.build:gradle:3.5.2'
classpath 'com.android.tools.build:gradle:4.0.2'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}

rootProject.allprojects {
repositories {
google()
jcenter()
mavenCentral()
}
}

apply plugin: 'com.android.library'
apply plugin: 'kotlin-android'

android {
compileSdkVersion 28
compileSdkVersion 31

sourceSets {
main.java.srcDirs += 'src/main/kotlin'
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,9 @@ class FlutterSensorsPlugin() : FlutterPlugin, MethodCallHandler {
private lateinit var messenger: BinaryMessenger
private lateinit var sensorManager: SensorManager

constructor(registrar: PluginRegistry.Registrar) : this() {
this.context = registrar.context()
this.messenger = registrar.messenger()
constructor(context: Context, binaryMessenger: BinaryMessenger) : this() {
this.context = context
this.messenger = binaryMessenger
this.sensorManager = context.getSystemService(Context.SENSOR_SERVICE) as SensorManager
}

Expand All @@ -31,10 +31,13 @@ class FlutterSensorsPlugin() : FlutterPlugin, MethodCallHandler {
companion object {
private const val CHANNEL_NAME = "flutter_sensors"

@Suppress("deprecation")
@JvmStatic
fun registerWith(registrar: PluginRegistry.Registrar) {
val methodChannel = MethodChannel(registrar.messenger(), CHANNEL_NAME)
val plugin = FlutterSensorsPlugin(registrar)
val context = registrar.context()
val binaryMessenger = registrar.messenger()
val plugin = FlutterSensorsPlugin(context, binaryMessenger)
methodChannel.setMethodCallHandler(plugin)
registrar.addViewDestroyListener {
plugin.onDestroy()
Expand Down Expand Up @@ -97,7 +100,8 @@ class FlutterSensorsPlugin() : FlutterPlugin, MethodCallHandler {
val interval: Int? = dataMap["interval"] as Int?
if (!eventChannels.containsKey(sensorId)) {
val eventChannel = EventChannel(messenger, "flutter_sensors/$sensorId")
val sensorManager = context.getSystemService(Context.SENSOR_SERVICE) as SensorManager
val sensorManager =
context.getSystemService(Context.SENSOR_SERVICE) as SensorManager
val sensorStreamHandler = SensorStreamHandler(sensorManager, sensorId, interval)
eventChannel.setStreamHandler(sensorStreamHandler)
eventChannels[sensorId] = eventChannel
Expand Down
8 changes: 2 additions & 6 deletions example/android/app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ apply plugin: 'kotlin-android'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"

android {
compileSdkVersion 28
compileSdkVersion 31

sourceSets {
main.java.srcDirs += 'src/main/kotlin'
Expand All @@ -40,10 +40,9 @@ android {
// TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
applicationId "com.example.fluttersensorsexample"
minSdkVersion 16
targetSdkVersion 28
targetSdkVersion 31
versionCode flutterVersionCode.toInteger()
versionName flutterVersionName
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}

buildTypes {
Expand All @@ -61,7 +60,4 @@ flutter {

dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test:runner:1.2.0'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
}
11 changes: 5 additions & 6 deletions example/android/app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -23,17 +23,16 @@
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|fontScale|screenLayout|density"
android:hardwareAccelerated="true"
android:windowSoftInputMode="adjustResize">
<!-- This keeps the window background of the activity showing
until Flutter renders its first frame. It can be removed if
there is no splash screen (such as the default splash screen
defined in @style/LaunchTheme). -->
<meta-data
android:name="io.flutter.app.android.SplashScreenUntilFirstFrame"
android:value="true" />
android:name="io.flutter.embedding.android.NormalTheme"
android:resource="@style/NormalTheme" />
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<meta-data
android:name="flutterEmbedding"
android:value="2" />
</application>
</manifest>
Original file line number Diff line number Diff line change
@@ -1,13 +1,5 @@
package com.example.fluttersensorsexample

import android.os.Bundle
import io.flutter.embedding.android.FlutterActivity

import io.flutter.app.FlutterActivity
import io.flutter.plugins.GeneratedPluginRegistrant

class MainActivity: FlutterActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
GeneratedPluginRegistrant.registerWith(this)
}
}
class MainActivity : FlutterActivity() {}
8 changes: 5 additions & 3 deletions example/android/app/src/main/res/values/styles.xml
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="LaunchTheme" parent="@android:style/Theme.Black.NoTitleBar">
<!-- Show a splash screen on the activity. Automatically removed when
Flutter draws its first frame -->
<style name="LaunchTheme" parent="@android:style/Theme.Light.NoTitleBar">
<item name="android:windowBackground">@drawable/launch_background</item>
<item name="android:windowFullscreen">true</item>
</style>
<style name="NormalTheme" parent="@android:style/Theme.Light.NoTitleBar">
<item name="android:windowBackground">?android:colorBackground</item>
</style>
</resources>
8 changes: 4 additions & 4 deletions example/android/build.gradle
Original file line number Diff line number Diff line change
@@ -1,20 +1,20 @@
buildscript {
ext.kotlin_version = '1.3.60'
ext.kotlin_version = '1.6.10'
repositories {
google()
jcenter()
mavenCentral()
}

dependencies {
classpath 'com.android.tools.build:gradle:3.5.2'
classpath 'com.android.tools.build:gradle:4.0.2'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}

allprojects {
repositories {
google()
jcenter()
mavenCentral()
}
}

Expand Down
3 changes: 1 addition & 2 deletions example/android/gradle.properties
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
org.gradle.jvmargs=-Xmx1536M
android.useAndroidX=true
android.enableJetifier=true
android.enableR8=true
android.enableJetifier=true
2 changes: 1 addition & 1 deletion example/android/gradle/wrapper/gradle-wrapper.properties
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,4 @@ distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-5.4.1-all.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-6.1.1-all.zip
24 changes: 10 additions & 14 deletions example/lib/main.dart
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ class _MyAppState extends State<MyApp> {
bool _gyroAvailable = false;
List<double> _accelData = List.filled(3, 0.0);
List<double> _gyroData = List.filled(3, 0.0);
StreamSubscription _accelSubscription;
StreamSubscription _gyroSubscription;
StreamSubscription? _accelSubscription;
StreamSubscription? _gyroSubscription;

@override
void initState() {
Expand Down Expand Up @@ -59,7 +59,7 @@ class _MyAppState extends State<MyApp> {

void _stopAccelerometer() {
if (_accelSubscription == null) return;
_accelSubscription.cancel();
_accelSubscription?.cancel();
_accelSubscription = null;
}

Expand All @@ -86,7 +86,7 @@ class _MyAppState extends State<MyApp> {

void _stopGyroscope() {
if (_gyroSubscription == null) return;
_gyroSubscription.cancel();
_gyroSubscription?.cancel();
_gyroSubscription = null;
}

Expand Down Expand Up @@ -132,19 +132,17 @@ class _MyAppState extends State<MyApp> {
MaterialButton(
child: Text("Start"),
color: Colors.green,
onPressed: _accelAvailable != null
? () => _startAccelerometer()
: null,
onPressed:
_accelAvailable ? () => _startAccelerometer() : null,
),
Padding(
padding: EdgeInsets.all(8.0),
),
MaterialButton(
child: Text("Stop"),
color: Colors.red,
onPressed: _accelAvailable != null
? () => _stopAccelerometer()
: null,
onPressed:
_accelAvailable ? () => _stopAccelerometer() : null,
),
],
),
Expand Down Expand Up @@ -179,17 +177,15 @@ class _MyAppState extends State<MyApp> {
MaterialButton(
child: Text("Start"),
color: Colors.green,
onPressed:
_gyroAvailable != null ? () => _startGyroscope() : null,
onPressed: _gyroAvailable ? () => _startGyroscope() : null,
),
Padding(
padding: EdgeInsets.all(8.0),
),
MaterialButton(
child: Text("Stop"),
color: Colors.red,
onPressed:
_gyroAvailable != null ? () => _stopGyroscope() : null,
onPressed: _gyroAvailable ? () => _stopGyroscope() : null,
),
],
),
Expand Down
4 changes: 2 additions & 2 deletions example/pubspec.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,15 @@ description: Demonstrates how to use the flutter_sensors plugin.
publish_to: 'none'

environment:
sdk: ">=2.0.0-dev.68.0 <3.0.0"
sdk: ">=2.14.0 <3.0.0"

dependencies:
flutter:
sdk: flutter

# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^0.1.2
cupertino_icons: any

dev_dependencies:
flutter_test:
Expand Down
2 changes: 1 addition & 1 deletion example/test/widget_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ void main() {
expect(
find.byWidgetPredicate(
(Widget widget) =>
widget is Text && widget.data.startsWith('Running on:'),
widget is Text && widget.data!.startsWith('Running on:'),
),
findsOneWidget,
);
Expand Down
4 changes: 2 additions & 2 deletions lib/flutter_sensors.dart
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ class SensorManager {
/// the sensor event channels are dynamically created and must be
/// registered before returning the stream for each channel.
Future<Stream<SensorEvent>> sensorUpdates(
{int sensorId, Duration interval}) =>
{required int sensorId, Duration? interval}) =>
_sensorChannel.sensorUpdates(sensorId: sensorId, interval: interval);

/// Checks if the [sensorId] is available in the system or supported by the
Expand All @@ -40,7 +40,7 @@ class SensorManager {
_sensorChannel.isSensorAvailable(sensorId);

/// Updates the interval between updates for an specific sensor.
Future updateSensorInterval({int sensorId, Duration interval}) =>
Future updateSensorInterval({required int sensorId, Duration? interval}) =>
_sensorChannel.updateSensorInterval(
sensorId: sensorId, interval: interval);
}
25 changes: 14 additions & 11 deletions lib/src/sensor_channel.dart
Original file line number Diff line number Diff line change
Expand Up @@ -15,16 +15,17 @@ class _SensorChannel {

/// Register a sensor update request.
Future<Stream<SensorEvent>> sensorUpdates(
{int sensorId, Duration interval}) async {
Stream<SensorEvent> sensorStream = _getSensorStream(sensorId);
{required int sensorId, Duration? interval}) async {
Stream<SensorEvent>? sensorStream = _getSensorStream(sensorId);
interval = interval ?? Sensors.SENSOR_DELAY_NORMAL;
if (sensorStream == null) {
final args = {"interval": _transformDurationToNumber(interval)};
final eventChannel = await _getEventChannel(sensorId, arguments: args);
final eventChannel =
await _getEventChannel(sensorId: sensorId, arguments: args);
sensorStream = eventChannel.receiveBroadcastStream().map((event) {
return SensorEvent.fromMap(event);
});
_sensorStreams.putIfAbsent(sensorId, () => sensorStream);
_sensorStreams.putIfAbsent(sensorId, () => sensorStream!);
} else {
await updateSensorInterval(sensorId: sensorId, interval: interval);
}
Expand All @@ -41,32 +42,34 @@ class _SensorChannel {
}

/// Updates the interval between updates for an specific sensor.
Future updateSensorInterval({int sensorId, Duration interval}) async {
Future updateSensorInterval(
{required int sensorId, Duration? interval}) async {
return _methodChannel.invokeMethod(
'update_sensor_interval',
{"sensorId": sensorId, "interval": _transformDurationToNumber(interval)},
);
}

/// Return the stream associated with the given sensor.
Stream<SensorEvent> _getSensorStream(int sensorId) {
Stream<SensorEvent>? _getSensorStream(int sensorId) {
return _sensorStreams[sensorId];
}

/// Return the stream associated with the given sensor.
Future<EventChannel> _getEventChannel(int sensorId, {Map arguments}) async {
EventChannel eventChannel = _eventChannels[sensorId];
Future<EventChannel> _getEventChannel(
{required int sensorId, Map arguments = const {}}) async {
EventChannel? eventChannel = _eventChannels[sensorId];
if (eventChannel == null) {
arguments["sensorId"] = sensorId;
await _methodChannel.invokeMethod("start_event_channel", arguments);
eventChannel = EventChannel("flutter_sensors/$sensorId");
_eventChannels.putIfAbsent(sensorId, () => eventChannel);
_eventChannels.putIfAbsent(sensorId, () => eventChannel!);
}
return eventChannel;
}

/// Transform the delay duration object to an int value for each platform.
num _transformDurationToNumber(Duration delay) {
return Platform.isAndroid ? delay.inMicroseconds : delay.inSeconds;
num? _transformDurationToNumber(Duration? delay) {
return Platform.isAndroid ? delay?.inMicroseconds : delay?.inSeconds;
}
}
Loading

0 comments on commit 1296ced

Please sign in to comment.