Flutter环境传感器插件environment_sensors的使用

发布于 1周前 作者 songsunli 来自 Flutter

Flutter环境传感器插件environment_sensors的使用

Environment Sensors

Flutter plugin for accessing ambient temperature, relative humidity, ambient light, and barometric pressure sensors of a device.

Install

Add environment_sensors as a dependency in pubspec.yaml. For help on adding as a dependency, view the documentation.

dependencies:
  environment_sensors: ^latest_version

Replace ^latest_version with the latest version of the package. You can find the latest version on the pub.dev page for environment_sensors.

After adding the dependency, run flutter pub get to install it.

Usage

Check for availability of sensors

Before using the sensors, you should check if they are available on the device:

final environmentSensors = EnvironmentSensors();   

var tempAvailable = await environmentSensors.getSensorAvailable(SensorType.AmbientTemperature);
var humidityAvailable = await environmentSensors.getSensorAvailable(SensorType.Humidity);
var lightAvailable = await environmentSensors.getSensorAvailable(SensorType.Light);
var pressureAvailable = await environmentSensors.getSensorAvailable(SensorType.Pressure);

Get sensor stream

You can listen to changes in sensor data by subscribing to the streams provided by the plugin:

final environmentSensors = EnvironmentSensors();

environmentSensors.pressure.listen((pressure) {
  //Pressure in Millibars
  print(pressure.toString());
});

Complete Example Demo

Below is a complete example demo that integrates all the functionalities mentioned above into a simple Flutter application.

import 'package:flutter/material.dart';
import 'dart:async';

import 'package:environment_sensors/environment_sensors.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  bool _tempAvailable = false;
  bool _humidityAvailable = false;
  bool _lightAvailable = false;
  bool _pressureAvailable = false;
  final environmentSensors = EnvironmentSensors();

  @override
  void initState() {
    super.initState();
    // Subscribe to the pressure stream
    environmentSensors.pressure.listen((pressure) {
      print(pressure.toString());
    });
    initPlatformState();
  }

  // Initialize the state of the platform sensors.
  Future<void> initPlatformState() async {
    bool tempAvailable;
    bool humidityAvailable;
    bool lightAvailable;
    bool pressureAvailable;

    tempAvailable = await environmentSensors.getSensorAvailable(SensorType.AmbientTemperature);
    humidityAvailable = await environmentSensors.getSensorAvailable(SensorType.Humidity);
    lightAvailable = await environmentSensors.getSensorAvailable(SensorType.Light);
    pressureAvailable = await environmentSensors.getSensorAvailable(SensorType.Pressure);

    setState(() {
      _tempAvailable = tempAvailable;
      _humidityAvailable = humidityAvailable;
      _lightAvailable = lightAvailable;
      _pressureAvailable = pressureAvailable;
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Environment Sensors'),
        ),
        body: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            (_humidityAvailable)
                ? StreamBuilder<double>(
                    stream: environmentSensors.humidity,
                    builder: (context, snapshot) {
                      if (!snapshot.hasData) return CircularProgressIndicator();
                      return Text(
                          'The Current Humidity is: ${snapshot.data?.toStringAsFixed(2)}%');
                    })
                : Text('No relative humidity sensor found'),
            (_tempAvailable)
                ? StreamBuilder<double>(
                    stream: environmentSensors.temperature,
                    builder: (context, snapshot) {
                      if (!snapshot.hasData) return CircularProgressIndicator();
                      return Text(
                          'The Current Temperature is: ${snapshot.data?.toStringAsFixed(2)}°C');
                    })
                : Text('No temperature sensor found'),
            (_lightAvailable)
                ? StreamBuilder<double>(
                    stream: environmentSensors.light,
                    builder: (context, snapshot) {
                      if (!snapshot.hasData) return CircularProgressIndicator();
                      return Text(
                          'The Current Light is: ${snapshot.data?.toStringAsFixed(2)} lux');
                    })
                : Text('No light sensor found'),
            (_pressureAvailable)
                ? StreamBuilder<double>(
                    stream: environmentSensors.pressure,
                    builder: (context, snapshot) {
                      if (!snapshot.hasData) return CircularProgressIndicator();
                      return Text(
                          'The Current Pressure is: ${snapshot.data?.toStringAsFixed(2)} hPa');
                    })
                : Text('No pressure sensor found'),
          ],
        ),
      ),
    );
  }
}

This demo creates a simple Flutter app that checks for the availability of different environment sensors and displays their current readings in real-time. If a sensor is not available, it will display a message indicating so.


更多关于Flutter环境传感器插件environment_sensors的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter环境传感器插件environment_sensors的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是如何在Flutter项目中使用environment_sensors插件来获取环境传感器数据的示例代码。这个插件允许你访问设备上的环境传感器,比如光线传感器、加速度计、磁力计等。

首先,你需要在pubspec.yaml文件中添加environment_sensors依赖:

dependencies:
  flutter:
    sdk: flutter
  environment_sensors: ^x.y.z  # 请替换为最新版本号

然后运行flutter pub get来获取依赖。

接下来,你可以在你的Flutter应用中导入并使用这个插件。以下是一个简单的示例,展示如何获取光线传感器和加速度计的数据:

import 'package:flutter/material.dart';
import 'package:environment_sensors/environment_sensors.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String _lightLevel = 'No data';
  String _acceleration = 'No data';

  @override
  void initState() {
    super.initState();
    _listenToLightSensor();
    _listenToAccelerometer();
  }

  void _listenToLightSensor() async {
    try {
      final lightSensor = LightSensor();
      lightSensor.onData.listen((LightSensorEvent event) {
        setState(() {
          _lightLevel = 'Light Level: ${event.lux.toStringAsFixed(2)} lux';
        });
      });

      // Optional: Start the sensor manually if needed
      // await lightSensor.activate();

    } catch (e) {
      print('Error accessing light sensor: $e');
    }
  }

  void _listenToAccelerometer() async {
    try {
      final accelerometer = Accelerometer();
      accelerometer.onData.listen((AccelerometerEvent event) {
        setState(() {
          _acceleration = 'Acceleration: X=${event.x.toStringAsFixed(2)}, Y=${event.y.toStringAsFixed(2)}, Z=${event.z.toStringAsFixed(2)} m/s²';
        });
      });

      // Optional: Start the sensor manually if needed
      // await accelerometer.activate();

    } catch (e) {
      print('Error accessing accelerometer: $e');
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Environment Sensors Example'),
        ),
        body: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Text(_lightLevel, style: TextStyle(fontSize: 20)),
              SizedBox(height: 20),
              Text(_acceleration, style: TextStyle(fontSize: 20)),
            ],
          ),
        ),
      ),
    );
  }
}

在这个示例中:

  1. 我们首先导入了environment_sensors包。
  2. MyApp_MyAppState类中,我们声明了两个字符串变量_lightLevel_acceleration来存储光线传感器和加速度计的数据。
  3. initState方法中,我们分别调用_listenToLightSensor_listenToAccelerometer方法来开始监听传感器数据。
  4. _listenToLightSensor方法尝试获取光线传感器实例,并监听其onData流来更新_lightLevel变量。
  5. _listenToAccelerometer方法尝试获取加速度计实例,并监听其onData流来更新_acceleration变量。
  6. build方法中,我们使用Text组件来显示获取到的传感器数据。

请注意,由于设备权限和硬件支持的不同,某些传感器可能不可用或需要额外的权限配置。在实际应用中,你应该处理这些潜在的异常情况,并为用户提供适当的反馈。

回到顶部