I am trying to create a sonoff (https://sonoff.tech/) type of device, which basically switches on and off the relay by connecting to the server (In my case Firebase Realtime), For the Switch i am trying to implement a a Flutter Switch on the app where the switch reads the status of the boolean on the server and updates the bool in onchanged! My Server side is up and ready, even my test switched work successfully, only i am unable to implement the switch successfully.Firebase Sample
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:firebase_database/firebase_database.dart';
class SwitchPage extends StatefulWidget {
static const String id = 'switch_screen';
@override
_SwitchPageState createState() => _SwitchPageState();
}
class _SwitchPageState extends State<SwitchPage> {
final DBref = FirebaseDatabase.instance.reference();
bool isSwitched;
bool newVal;
void LedOn() async {
await DBref.child("DHT11")
.child("Device1")
.child("LED_STATUS")
.update({'DATA': 'TRUE'});
}
void LedOFF() async {
await DBref.child("DHT11")
.child("Device1")
.child("LED_STATUS")
.update({'DATA': 'FALSE'});
}
void getStatus() async {
String newValue = (await FirebaseDatabase.instance
.reference()
.child("DHT11/Device1/LED_STATUS/DATA")
.once())
.value;
print(isSwitched);
print(newValue);
setState(() {
if (newValue == 'TRUE') {
isSwitched = true;
} else {
isSwitched = false;
}
});
}
@override
void initState() {
getStatus();
super.initState();
}
@override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
appBar: AppBar(
title: Text('Device Center'),
),
backgroundColor: Colors.white,
body: Column(
children: <Widget>[
FlatButton(
onPressed: () async {
await getStatus();
},
child: Text('TEST STATUS')),
FlatButton(
onPressed: () {
LedOn();
print('ON');
},
child: Text('LED ON')),
FlatButton(
onPressed: () {
LedOFF();
print('OFF');
},
child: Text('LED OFF')),
Switch(
value: isSwitched,
onChanged: (value) {
setState(() {
isSwitched = value;
if (isSwitched == "TRUE") {
return LedOFF();
} else if (isSwitched == "FALSE") {
return LedOn();
}
});
},
),
],
)),
);
}
}