我的 StreamBuilder 包含两个对我来说无法解决的错误
My StreamBuilder contains two for me unsolvable errors
我正在尝试构建一个待办事项应用程序。 (学习扑动)
这是代码中出现两个错误的部分:
class ToDo1 extends StatefulWidget {
@override
_ToDo1State createState() => _ToDo1State();
}
class _ToDo1State extends State<ToDo1> {
var User;
late DatabaseService database;
Future<void> connectToFirebase() async{
await Firebase.initializeApp();
final FirebaseAuth auth = FirebaseAuth.instance;
UserCredential result = await FirebaseAuth.instance.signInAnonymously();
User = result.user;
database = DatabaseService(User.uid);
if (!(await database.checkIfUserExists())) {
database.setTodo('To-Do anlegen', false);
}
}
void toggleDone(String key, bool value) {
database.setTodo(key, !value);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Center(
child: Text(
'Stufe 1',
style: TextStyle(
fontStyle: FontStyle.italic,
decoration: TextDecoration.underline),
)),
backgroundColor: Color.fromRGBO(35, 112, 192, 1),
),
body: FutureBuilder(
future: connectToFirebase(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(child: CircularProgressIndicator());
} else {
return StreamBuilder<DocumentSnapshot> (
stream: database.getTodos(),
builder: (context, AsyncSnapshot<DocumentSnapshot> snapshot) {
if(!snapshot.hasData) {
return CircularProgressIndicator();
} else {
Map<String, dynamic> items = snapshot.data.data;
return ListView.separated(
separatorBuilder: (BuildContext context, int index) {
return SizedBox(
height: 10,
);
},
padding: EdgeInsets.all(10),
itemCount: items.length,
itemBuilder: (BuildContext, i) {
String key = items.keys.elementAt(i);
return ToDoItem(
key,
items[key]!,
() => toggleDone(key, items[key]),
);
});
}
}
);
}
},
)
);
}
}
这是红色下划线:
Stream: database.getTodos()
还有这个:
snapshot.data.data
这是与 Firebase 交互的 class:
class DatabaseService {
final String userID;
DatabaseService(this.userID);
final CollectionReference userTodos =
FirebaseFirestore.instance.collection('userTodos');
Future setTodo(String item, bool value) async {
return await userTodos.doc(userID).set(
{item:value}, SetOptions(merge: true));
}
Future deleteTodo(String key) async {
return await userTodos.doc(userID).update(
{key: FieldValue.delete(),}
);
}
Future checkIfUserExists() async {
if((await userTodos.doc(userID).get()).exists) {
return true;
}
else {
return false;
}
}
Stream getTodos() {
return userTodos.doc(userID).snapshots();
}
}
最后,这是错误:
Error: Property 'data' cannot be accessed on 'DocumentSnapshot<Object?>?' because it is potentially null.
- 'DocumentSnapshot' is from 'package:cloud_firestore/cloud_firestore.dart' ('/C:/flutter/.pub->cache/hosted/pub.dartlang.org/cloud_firestore-2.5.1/lib/cloud_firestore.dart').
- 'Object' is from 'dart:core'.
Try accessing using ?. instead.
Map<String, dynamic> items = snapshot.data.data;
lib/Pages/Home_Page.dart:347:62: Error: A value of type 'Object? Function()' can't be assigned to a variable of type 'Map<String, dynamic>'.
- 'Object' is from 'dart:core'.
- 'Map' is from 'dart:core'.
Map<String, dynamic> items = snapshot.data.data;
^
lib/Pages/Home_Page.dart:342:32: Error: The argument type 'Stream<dynamic>' can't be assigned to the parameter type 'Stream<DocumentSnapshot<Object?>>?'.
- 'Stream' is from 'dart:async'.
- 'DocumentSnapshot' is from 'package:cloud_firestore/cloud_firestore.dart' ('/C:/flutter/.pub->cache/hosted/pub.dartlang.org/cloud_firestore-2.5.1/lib/cloud_firestore.dart').
- 'Object' is from 'dart:core'.
stream: database.getTodos(),
^
FAILURE: Build failed with an exception.
* Where:
Script 'C:\flutter\packages\flutter_tools\gradle\flutter.gradle' line: 1035
* What went wrong:
Execution failed for task ':app:compileFlutterBuildDebug'.
Process 'command 'C:\flutter\bin\flutter.bat'' finished with non-zero exit value 1
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
* Get more help at https://help.gradle.org
BUILD FAILED in 14s
Exception: Gradle task assembleDebug failed with exit code 1
希望我已经提供了所有必要的数据,以便可以解决这两个问题。
如果没有,请写信给我,我会尽力将您需要的 material 发送给您。
Stream: database.getTodos()
的第一个问题是您的 getTodos()
方法需要 return 类型,例如 Stream<DocumentSnapshot<Object?>>? getTodos()
.
snapshot.data.data
的第二个问题是 snapshot.data
可以是 null
,您无法访问最终可能是 null
的内容。但是,由于您已经在 !snapshot.hasData
中检查了它,这似乎是误报,因此您可以通过分配值 snapshot.data!.data
来消除它的可空性,!
告诉编译器在此点 snapshot.data
不能有 null
值。
我正在尝试构建一个待办事项应用程序。 (学习扑动) 这是代码中出现两个错误的部分:
class ToDo1 extends StatefulWidget {
@override
_ToDo1State createState() => _ToDo1State();
}
class _ToDo1State extends State<ToDo1> {
var User;
late DatabaseService database;
Future<void> connectToFirebase() async{
await Firebase.initializeApp();
final FirebaseAuth auth = FirebaseAuth.instance;
UserCredential result = await FirebaseAuth.instance.signInAnonymously();
User = result.user;
database = DatabaseService(User.uid);
if (!(await database.checkIfUserExists())) {
database.setTodo('To-Do anlegen', false);
}
}
void toggleDone(String key, bool value) {
database.setTodo(key, !value);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Center(
child: Text(
'Stufe 1',
style: TextStyle(
fontStyle: FontStyle.italic,
decoration: TextDecoration.underline),
)),
backgroundColor: Color.fromRGBO(35, 112, 192, 1),
),
body: FutureBuilder(
future: connectToFirebase(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(child: CircularProgressIndicator());
} else {
return StreamBuilder<DocumentSnapshot> (
stream: database.getTodos(),
builder: (context, AsyncSnapshot<DocumentSnapshot> snapshot) {
if(!snapshot.hasData) {
return CircularProgressIndicator();
} else {
Map<String, dynamic> items = snapshot.data.data;
return ListView.separated(
separatorBuilder: (BuildContext context, int index) {
return SizedBox(
height: 10,
);
},
padding: EdgeInsets.all(10),
itemCount: items.length,
itemBuilder: (BuildContext, i) {
String key = items.keys.elementAt(i);
return ToDoItem(
key,
items[key]!,
() => toggleDone(key, items[key]),
);
});
}
}
);
}
},
)
);
}
}
这是红色下划线:
Stream: database.getTodos()
还有这个:
snapshot.data.data
这是与 Firebase 交互的 class:
class DatabaseService {
final String userID;
DatabaseService(this.userID);
final CollectionReference userTodos =
FirebaseFirestore.instance.collection('userTodos');
Future setTodo(String item, bool value) async {
return await userTodos.doc(userID).set(
{item:value}, SetOptions(merge: true));
}
Future deleteTodo(String key) async {
return await userTodos.doc(userID).update(
{key: FieldValue.delete(),}
);
}
Future checkIfUserExists() async {
if((await userTodos.doc(userID).get()).exists) {
return true;
}
else {
return false;
}
}
Stream getTodos() {
return userTodos.doc(userID).snapshots();
}
}
最后,这是错误:
Error: Property 'data' cannot be accessed on 'DocumentSnapshot<Object?>?' because it is potentially null.
- 'DocumentSnapshot' is from 'package:cloud_firestore/cloud_firestore.dart' ('/C:/flutter/.pub->cache/hosted/pub.dartlang.org/cloud_firestore-2.5.1/lib/cloud_firestore.dart').
- 'Object' is from 'dart:core'.
Try accessing using ?. instead.
Map<String, dynamic> items = snapshot.data.data;
lib/Pages/Home_Page.dart:347:62: Error: A value of type 'Object? Function()' can't be assigned to a variable of type 'Map<String, dynamic>'.
- 'Object' is from 'dart:core'.
- 'Map' is from 'dart:core'.
Map<String, dynamic> items = snapshot.data.data;
^
lib/Pages/Home_Page.dart:342:32: Error: The argument type 'Stream<dynamic>' can't be assigned to the parameter type 'Stream<DocumentSnapshot<Object?>>?'.
- 'Stream' is from 'dart:async'.
- 'DocumentSnapshot' is from 'package:cloud_firestore/cloud_firestore.dart' ('/C:/flutter/.pub->cache/hosted/pub.dartlang.org/cloud_firestore-2.5.1/lib/cloud_firestore.dart').
- 'Object' is from 'dart:core'.
stream: database.getTodos(),
^
FAILURE: Build failed with an exception.
* Where:
Script 'C:\flutter\packages\flutter_tools\gradle\flutter.gradle' line: 1035
* What went wrong:
Execution failed for task ':app:compileFlutterBuildDebug'.
Process 'command 'C:\flutter\bin\flutter.bat'' finished with non-zero exit value 1
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
* Get more help at https://help.gradle.org
BUILD FAILED in 14s
Exception: Gradle task assembleDebug failed with exit code 1
希望我已经提供了所有必要的数据,以便可以解决这两个问题。 如果没有,请写信给我,我会尽力将您需要的 material 发送给您。
Stream: database.getTodos()
的第一个问题是您的 getTodos()
方法需要 return 类型,例如 Stream<DocumentSnapshot<Object?>>? getTodos()
.
snapshot.data.data
的第二个问题是 snapshot.data
可以是 null
,您无法访问最终可能是 null
的内容。但是,由于您已经在 !snapshot.hasData
中检查了它,这似乎是误报,因此您可以通过分配值 snapshot.data!.data
来消除它的可空性,!
告诉编译器在此点 snapshot.data
不能有 null
值。