英文:
Flutter The operator '[]' isn't defined for the type 'Object'. Try defining the operator '[]'
问题
你尝试连接你的应用程序到Firebase实时数据库,但遇到了以下错误:
'[]' 操作符未定义于 'Object' 类型。尝试定义 '[]' 操作符
出现在以下代码行:
snapshot.data!.snapshot.value?["Temperature:"]
snapshot.data!.snapshot.value?["Humidity:"]
更准确地说,出现在 ["Temperature:"] 和 ["Humidity:"] 中。
我的目标是更改Firebase中的temp和hum的值,并在应用程序中检测到更改。
如果您有任何修复方法,请告诉我。
以下是我的完整代码:
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
class IOTScreen extends StatefulWidget {
const IOTScreen({Key? key}) : super(key: key);
@override
_IOTScreenState createState() => _IOTScreenState();
}
class _IOTScreenState extends State<IOTScreen> {
bool value = false;
bool values = false;
final dbRef = FirebaseDatabase.instance.ref();
@override
void initState() {
super.initState();
initializeFirebase();
}
void initializeFirebase() async {
try {
await Firebase.initializeApp();
print('Firebase initialized successfully');
} catch (e) {
print('Failed to initialize Firebase: $e');
}
}
void onUpdate() {
setState(() {
value = !value;
});
}
void onUpdate2() {
setState(() {
values = !values;
});
}
void writeData() {
//dbRef.child("Data").set({"Humidity: ": 0, "Temperature: ": 0});
dbRef.child("LightStates").set({"switch": !value});
}
void writeData2() {
dbRef.child("FanStates").set({"switch": !values});
}
@override
Widget build(BuildContext context) {
SystemChrome.setPreferredOrientations(
[DeviceOrientation.portraitUp, DeviceOrientation.portraitDown]);
return Scaffold(
body: StreamBuilder(
stream: dbRef.child("Data").onValue,
builder: (context, snapshot) {
if (snapshot.hasData &&
!snapshot.hasError &&
snapshot.data?.snapshot.value != null) {
return Column(
children: [
Padding(
padding: const EdgeInsets.all(18),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Icon(Icons.clear_all, size: 30),
Text(
"Egg Incubator",
style: TextStyle(
fontSize: 30, fontWeight: FontWeight.bold),
),
Icon(Icons.settings, size: 30)
],
),
),
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(
snapshot.data!.snapshot.value?["Temperature:"],
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(
snapshot.data!.snapshot.value?["Humidity:"],
style: TextStyle(
fontSize: 20, fontWeight: FontWeight.bold),
),
)
],
),
SizedBox(
height: 60,
),
FloatingActionButton.extended(
onPressed: () {
writeData();
onUpdate();
},
label: value ? Text("Lamp ON") : Text("Lamp OFF"),
elevation: 20,
backgroundColor: value ? Colors.yellow : Colors.white60,
icon: value
? Icon(Icons.wb_incandescent)
: Icon(Icons.wb_incandescent_outlined)),
SizedBox(
height: 60,
),
FloatingActionButton.extended(
onPressed: () {
onUpdate2();
writeData2();
},
label: values ? Text("Fan OFF") : Text("Fan ON"),
elevation: 20,
backgroundColor: values ? Colors.white60 : Colors.blueAccent,
icon: values
? Icon(Icons.wind_power_rounded)
: Icon(Icons.wind_power_outlined),
)
],
);
} else
return Container();
},
),
);
}
}
请注意,代码中的中文注释已经保留在原文中,没有翻译。
英文:
i was trying to connect my app to firebase realtime database, but got the error
The operator '[]' isn't defined for the type 'Object'. Try defining the operator '[]'
in line
snapshot.data!.snapshot.value?["Temperature:"]
snapshot.data!.snapshot.value?["Humidity:"]
more precisely in ["Temperature:"] and ["Humidity:"].
my goal is to change the value of temp and hum in firebase and it detect the change in the app.
please let me know if you have any idea how to fix it.
here's my full code
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
class IOTScreen extends StatefulWidget {
const IOTScreen({Key? key}) : super(key: key);
@override
_IOTScreenState createState() => _IOTScreenState();
}
class _IOTScreenState extends State<IOTScreen> {
bool value = false;
bool values = false;
final dbRef = FirebaseDatabase.instance.ref();
@override
void initState() {
super.initState();
initializeFirebase();
}
void initializeFirebase() async {
try {
await Firebase.initializeApp();
print('Firebase initialized successfully');
} catch (e) {
print('Failed to initialize Firebase: $e');
}
}
void onUpdate() {
setState(() {
value = !value;
});
}
void onUpdate2() {
setState(() {
values = !values;
});
}
void writeData() {
//dbRef.child("Data").set({"Humidity: ": 0, "Temperature: ": 0});
dbRef.child("LightStates").set({"switch": !value});
}
void writeData2() {
dbRef.child("FanStates").set({"switch": !values});
}
@override
Widget build(BuildContext context) {
SystemChrome.setPreferredOrientations(
[DeviceOrientation.portraitUp, DeviceOrientation.portraitDown]);
return Scaffold(
body: StreamBuilder(
stream: dbRef.child("Data").onValue,
builder: (context, snapshot) {
if (snapshot.hasData &&
!snapshot.hasError &&
snapshot.data?.snapshot.value! != null) {
return Column(
children: [
Padding(
padding: const EdgeInsets.all(18),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Icon(Icons.clear_all, size: 30),
Text(
"Egg Incubator",
style: TextStyle(
fontSize: 30, fontWeight: FontWeight.bold),
),
Icon(Icons.settings, size: 30)
],
),
),
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(
snapshot.data!.snapshot.value?["Temperature:"],
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(
snapshot.data!.snapshot.value?.["Humidity:"],
style: TextStyle(
fontSize: 20, fontWeight: FontWeight.bold),
),
)
],
),
SizedBox(
height: 60,
),
FloatingActionButton.extended(
onPressed: () {
writeData();
onUpdate();
},
label: value ? Text("Lamp ON") : Text("Lamp OFF"),
elevation: 20,
backgroundColor: value ? Colors.yellow : Colors.white60,
icon: value
? Icon(Icons.wb_incandescent)
: Icon(Icons.wb_incandescent_outlined)),
SizedBox(
height: 60,
),
FloatingActionButton.extended(
onPressed: () {
onUpdate2();
writeData2();
},
label: values ? Text("Fan OFF") : Text("Fan ON"),
elevation: 20,
backgroundColor:
values ? Colors.white60 : Colors.blueAccent,
icon: values
? Icon(Icons.wind_power_rounded)
: Icon(Icons.wind_power_outlined),
)
],
);
} else
return Container();
},
),
);
}
}
答案1
得分: 2
(Assuming that it is a Map
) 它无法确定它是一个 Map
,所以你不能只使用 []
。你可以尝试写
(snapshot.data!.snapshot.value as Map?)?["Temperature:"]
英文:
(Assuming that it is a Map
) It can't determine that it is a Map
so you can't just use []
. You can try to write
(snapshot.data!.snapshot.value as Map?)?["Temperature:"]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论