“Flutter The operator ‘[]’ isn’t defined for the type ‘Object’. Try defining the operator ‘[]'”

huangapple go评论262阅读模式
英文:

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?[&quot;Temperature:&quot;]
snapshot.data!.snapshot.value?[&quot;Humidity:&quot;]

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 &#39;package:firebase_core/firebase_core.dart&#39;;
import &#39;package:firebase_database/firebase_database.dart&#39;;
import &#39;package:flutter/material.dart&#39;;
import &#39;package:flutter/services.dart&#39;;
class IOTScreen extends StatefulWidget {
const IOTScreen({Key? key}) : super(key: key);
@override
_IOTScreenState createState() =&gt; _IOTScreenState();
}
class _IOTScreenState extends State&lt;IOTScreen&gt; {
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(&#39;Firebase initialized successfully&#39;);
} catch (e) {
print(&#39;Failed to initialize Firebase: $e&#39;);
}
}
void onUpdate() {
setState(() {
value = !value;
});
}
void onUpdate2() {
setState(() {
values = !values;
});
}
void writeData() {
//dbRef.child(&quot;Data&quot;).set({&quot;Humidity: &quot;: 0, &quot;Temperature: &quot;: 0});
dbRef.child(&quot;LightStates&quot;).set({&quot;switch&quot;: !value});
}
void writeData2() {
dbRef.child(&quot;FanStates&quot;).set({&quot;switch&quot;: !values});
}
@override
Widget build(BuildContext context) {
SystemChrome.setPreferredOrientations(
[DeviceOrientation.portraitUp, DeviceOrientation.portraitDown]);
return Scaffold(
body: StreamBuilder(
stream: dbRef.child(&quot;Data&quot;).onValue,
builder: (context, snapshot) {
if (snapshot.hasData &amp;&amp;
!snapshot.hasError &amp;&amp;
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(
&quot;Egg Incubator&quot;,
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(
&quot;Temperature&quot;,
style: TextStyle(
fontSize: 20, fontWeight: FontWeight.bold),
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
snapshot.data!.snapshot.value?[&quot;Temperature:&quot;],
style: TextStyle(
fontSize: 20, fontWeight: FontWeight.bold),
),
)
],
)
],
),
SizedBox(height: 20),
Column(
children: [
Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
&quot;Humidity&quot;,
style: TextStyle(
fontSize: 20, fontWeight: FontWeight.bold),
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
snapshot.data!.snapshot.value?.[&quot;Humidity:&quot;],
style: TextStyle(
fontSize: 20, fontWeight: FontWeight.bold),
),
)
],
),
SizedBox(
height: 60,
),
FloatingActionButton.extended(
onPressed: () {
writeData();
onUpdate();
},
label: value ? Text(&quot;Lamp ON&quot;) : Text(&quot;Lamp OFF&quot;),
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(&quot;Fan OFF&quot;) : Text(&quot;Fan ON&quot;),
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?)?[&quot;Temperature:&quot;]

huangapple
  • 本文由 发表于 2023年6月26日 17:15:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/76555263.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定