如何实现使用Firebase读取真实的时间传感器值的Flutter应用程序

dsekswqp  于 2023-10-22  发布在  Flutter
关注(0)|答案(1)|浏览(163)

这是我的代码,但这与snapsotMap的一些错误

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

class Dashboard extends StatefulWidget {
  const Dashboard({super.key});

  @override
  State<Dashboard> createState() => _DashboardState();
}

class _DashboardState extends State<Dashboard> {
  
  Future<void> readSensorValues() async {
    final DataSnapshot dataSnapshot =
        (await FirebaseDatabase.instance.ref().child('sensor').once()) as DataSnapshot;
    final Map<String, dynamic> data =
        Map<String, dynamic>.from(dataSnapshot.value);

    final double sensorEC = (data['EC'] as int).toDouble();
    final double sensorPH = (data['PH'] as int).toDouble();
    final double sensorRTD = (data['RTD'] as int).toDouble();
    final double humidity = (data['humidity']as int).toDouble();
    final double temperature = (data['temperature'] as int).toDouble();

    print('Sensor EC is $sensorEC');
    print('Sensor PH $sensorPH');
    print('Sensor RTD $sensorRTD'); 
    print('Sensor humidity $humidity');  
    print('Sensor temperature $temperature');
  }
@override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(

      ),
    );
  }
}

我想一些功能来读取数据传感器EC值,PH值,RTD,湿度,温度,然后将其转换成一个浮动的Flutter应用程序上的值。

rjjhvcjd

rjjhvcjd1#

您提供的代码基本上是正确的,但似乎您在将快照值强制转换为DataSnapshot时遇到了问题。Firebase的once()方法应该已经返回一个DataSnapshot,因此不需要显式转换为DataSnapshot。
下面是readSensorValues方法的一个稍微修改的版本:

Future<void> readSensorValues() async {
  DatabaseReference ref = FirebaseDatabase.instance.ref().child('sensor');
  DataSnapshot dataSnapshot = await ref.once();
  
  if(dataSnapshot.value != null) {
    Map<String, dynamic> data = Map<String, dynamic>.from(dataSnapshot.value);

    double sensorEC = (data['EC'] as num).toDouble();
    double sensorPH = (data['PH'] as num).toDouble();
    double sensorRTD = (data['RTD'] as num).toDouble();
    double humidity = (data['humidity'] as num).toDouble();
    double temperature = (data['temperature'] as num).toDouble();

    print('Sensor EC is $sensorEC');
    print('Sensor PH $sensorPH');
    print('Sensor RTD $sensorRTD'); 
    print('Sensor humidity $humidity');  
    print('Sensor temperature $temperature');
  } else {
    print('No data found in Firebase');
  }
}

一些变化和注意事项:
删除了不必要的转换为DataSnapshot。使用num类型而不是int,因为Firebase可能会返回int或double作为数值,然后我们显式转换为double。为dataSnapshot.值添加了空检查,以确保在Firebase中没有数据时应用不会崩溃。现在,您可以在构建方法或其他任何地方调用readSensorValues()函数,以从Firebase读取传感器值。

相关问题