首页 > 解决方案 > 通过从 Flutter 中的 firebase 实时数据库中获取布尔值来更新按钮的状态

问题描述

我试图通过从 firebase 实时数据库中获取值来控制我的开关。它在更改时侦听布尔值,但我不明白如何在实时数据库中的值更改时使用该值来切换按钮。这基本上是一个应用程序,您可以在其中通过应用程序和应用程序通过硬件控制开关,实时数据库 Firebase 作为它们之间的桥梁。

这是我的main.dart文件:

import 'package:firebaseiot/screens/iotscreen.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  const MyApp({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      routes: <String, WidgetBuilder>{
        'iotscreen/': (BuildContext context) => IotScreen()
      },
      title: "Firebase IOT",
      debugShowCheckedModeBanner: false,
      theme:
          ThemeData(
            brightness: Brightness.dark,
            backgroundColor: Colors.black
            ),
      themeMode: ThemeMode.system,
      home: IotScreen(),
    );
  }
}

这是我的iotscreen.dart文件:

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

class IotScreen extends StatefulWidget {
  @override
  _IotScreenState createState() => _IotScreenState();
}

class _IotScreenState extends State<IotScreen> {
  @override
  final DatabaseReference = FirebaseDatabase.instance.reference();
  bool state = false;
  bool newValue;

  onUpdate() {
    setState(() {
      state = !state;
    });
  }

  void getStatus() async {
    String newValue = (await DatabaseReference.child("LightState/switch").once()).value;
    print(newValue);
    print(state);
    setState(() {
      if (newValue == 'TRUE' || newValue == 'true') {
        state = true;
      } else if(newValue == 'FALSE' || newValue == 'false') {
        state = false;
      }
    });
  }

  Widget build(BuildContext context) {
    SystemChrome.setPreferredOrientations(
        [DeviceOrientation.portraitUp, DeviceOrientation.portraitDown]);
    return Scaffold(
      body: StreamBuilder(
          //stream: DatabaseReference.child("LightState").onValue,
          builder: (context, snapshot) {
            if (snapshot.hasData &&
                !snapshot.hasError &&
                snapshot.data.snapshot.value != null) {
              return Column(
                children: [
                  Padding(
                    padding: EdgeInsets.all(20),
                    child: SafeArea(
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Icon(
                            Icons.clear_all,
                            color: Colors.black,
                          ),
                          Text(
                            "MY ROOM",
                            style: TextStyle(
                                fontSize: 20, fontWeight: FontWeight.bold),
                          ),
                          Icon(Icons.settings)
                        ],
                      ),
                    ),
                  ),
                  SizedBox(height: 20),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Column(
                        children: [
                          Padding(
                            padding: const EdgeInsets.all(8.0),
                            child: Text(
                              "Temperature",
                              style: TextStyle(
                                  fontSize: 20, fontWeight: FontWeight.bold),
                            ),
                          ),
                          Padding(
                            padding: const EdgeInsets.all(8.0),
                            child: Text(
                              "30", // test data
                              style: TextStyle(
                                  fontSize: 20, fontWeight: FontWeight.bold),
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),
                  SizedBox(height: 20),
                  Column(
                    children: [
                      Padding(
                        padding: const EdgeInsets.all(8.0),
                        child: Text(
                          "Humidity",
                          style: TextStyle(
                              fontSize: 20, fontWeight: FontWeight.bold),
                        ),
                      ),
                      Padding(
                        padding: const EdgeInsets.all(8.0),
                        child: Text(
                          "80", // test data
                          style: TextStyle(
                              fontSize: 20, fontWeight: FontWeight.bold),
                        ),
                      ),
                    ],
                  ),
                  SizedBox(height: 80),
                  FloatingActionButton.extended(
                    onPressed: () async {
                      onUpdate();
                      onWrite();
                      await getStatus();
                      print(state);
                    },
                    label: state ? Text("ON") : Text("OFF"),
                    elevation: 20,
                    backgroundColor: state ? Colors.yellow : Colors.white,
                    icon: state
                        ? Icon(Icons.visibility)
                        : Icon(Icons.visibility_off),
                  )
                ],
              );
            } else
              return Container();
          },
          stream: DatabaseReference.child("LightState").onValue),
    );
  }

  Future<void> onWrite() async {
    DatabaseReference.child("LightState").set({"switch": !state});
  }
}

这是我的 .json 文件:

{
  "LightState" : {
    "switch" : true
  }
}

当实时数据库中的值从“假”变为“真”时,请帮助我使用监听的值来切换按钮。我使用这个颤振库'firebase_database: ^7.1.1'https://pub.dev/packages/firebase_database

标签: androidfirebaseflutterfirebase-realtime-databaseswitch-statement

解决方案


推荐阅读