【发布时间】:2020-11-05 04:14:15
【问题描述】:
所以我的 Flutter 应用程序中有这个屏幕,它应该显示特定用户的所有笔记。我对 Firestore 进行了结构化,以便有一组笔记,每个用户都有一个名为他们的 uid 的文档。然后他们所有的笔记都存储在他们文档下的集合(用户笔记)中。
我在这里遇到的问题是,当您尝试访问应用程序中的注释页面时,您会收到错误
在 null 上调用了 getter 'uid'。 接收方:空 尝试调用:uid
但是当我从 Flutter 应用程序中单击运行时,一切正常。您可以在屏幕上看到所有注释。这是我的笔记屏幕。
import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'welcome_screen.dart';
class NoteScreen extends StatefulWidget {
static const String id = 'note_screen';
@override
_NoteScreenState createState() => _NoteScreenState();
}
class _NoteScreenState extends State<NoteScreen> {
final _auth = FirebaseAuth.instance;
User loggedInUser;
@override
void initState() {
super.initState();
getCurrentUser();
}
void getCurrentUser() async {
try {
final user = await _auth.currentUser;
if (user != null) {
loggedInUser = user;
}
} catch (e) {
print(e);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Field Notes'),
actions: <Widget>[
IconButton(
icon: const Icon(Icons.chat),
tooltip: 'Messages',
onPressed: () {},
),
IconButton(
icon: const Icon(Icons.exit_to_app),
tooltip: 'Log Out',
onPressed: () {
_auth.signOut();
Navigator.pushNamed(context, WelcomeScreen.id);
},
),
],
),
body: StreamBuilder(
stream: FirebaseFirestore.instance
.collection('notes').doc(loggedInUser.uid).collection('usernotes')
.snapshots(),
builder: (ctx, streamSnapShot) {
if(!streamSnapShot.hasData) return const Text('Loading...');
if (streamSnapShot.connectionState == ConnectionState.waiting) {
return Center(
child: CircularProgressIndicator(),
);
}
final noteData = streamSnapShot.data.docs;
return ListView.builder(
itemCount: noteData.length,
itemBuilder: (ctx, index) => Container(
padding: EdgeInsets.all(8),
child: Text(noteData[index]['text']),
),
);
},
),
floatingActionButton:
FloatingActionButton(child: Icon(Icons.add), onPressed: () {
FirebaseFirestore.instance.collection('notes').doc(loggedInUser.uid).collection('usernotes').add({
'text' : 'This was added by clicking the button!'
});
}),
);
}
}
【问题讨论】:
-
在调用 await _auth.currentUser 之前调用的构建方法。这就是在 null 上调用 loggedInUser.uid 的原因。
-
我不明白它是如何工作的。我的 await _auth.currentUser 在 build 方法之上。
-
根据 firebase auth 的更新插件,您不需要使用 await 获取当前用户,只需使用 _auth.currentUser.uid。如果您有最新版本的 firebase 身份验证。
-
不知道为什么这个问题被否决了。我该如何改进这个问题?我的问题有什么问题?
标签: firebase flutter dart firebase-authentication