【发布时间】:2020-05-10 07:13:14
【问题描述】:
我是 Flutter/Dart 的新手,但我一直在尝试找出我正在从事的项目的数据库规则。我知道有很多关于 Firebase DB 规则的帖子,但我发现和尝试的一切都没有奏效。在下面的特定情况下,我希望任何人都能够读取数据,但只有作者能够编写和编辑它。我将 Doc ID 设置为 uid,并且在删除权限的情况下可以正常工作,但是当我添加受限规则时,我无法正常工作。我做错了什么?
堆栈跟踪消息
I/flutter (17900): PlatformException(Error performing setData, PERMISSION_DENIED: Missing or insufficient permissions., null)
E/flutter (17900): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: setState() called after dispose(): _RegisterState#1360e(lifecycle state: defunct, not mounted)
我的 Firebase 规则:
service cloud.firestore {
match /databases/{database}/documents {
match /brews/{userId} {
allow read: if request.auth.uid != null;
allow write: if request.auth.uid == userId;
}
}
}
数据库代码
class DatabaseService {
final String uid;
DatabaseService({this.uid});
//Collection reference
final CollectionReference brewCollection =
Firestore.instance.collection('brews');
Future updateUserData(String sugars, String name, int strength) async {
return await brewCollection.document(uid).setData({
'sugars': sugars,
'name': name,
'strength': strength,
});
}
//brew list from snapshot
List<Brew> _brewListFromSnapshot(QuerySnapshot snapshot) {
return snapshot.documents.map((doc) {
return Brew(
name: doc.data['name'] ?? '',
strength: doc.data['strength'] ?? 0,
sugars: doc.data['sugars'] ?? '0',
);
}).toList();
}
//userData from snapshot
UserData _userDataFromSnapshot(DocumentSnapshot snapshot) {
return UserData(
uid: uid,
name: snapshot.data['name'],
sugars: snapshot.data['sugars'],
strength: snapshot.data['strength'],
);
}
//Get the collection stream
Stream<List<Brew>> get brews {
return brewCollection.snapshots().map(_brewListFromSnapshot);
}
//get user doc stream
Stream<UserData> get userData {
return brewCollection.document(uid).snapshots().map(_userDataFromSnapshot);
}
}
验证码:
class Authenticate extends StatefulWidget {
@override
_AuthenticateState createState() => _AuthenticateState();
}
class _AuthenticateState extends State<Authenticate> {
bool showSignIn = true;
void toggleView() {
setState(() {
showSignIn = !showSignIn;
});
}
@override
Widget build(BuildContext context) {
if (showSignIn) {
return SignIn(toggleView: toggleView);
} else {
return Register(toggleView: toggleView);
}
}
}
【问题讨论】:
-
你分享的代码是读写的。哪一个不行?当该代码运行时会发生什么?任何错误消息/堆栈跟踪?另外:由于您要求用户在您的规则中进行身份验证,因此您需要他们登录代码。您共享的代码不会显示/如何用户签名,也不会在读/写之前检查用户是否已登录。请花一些时间isolating a single problem,因为这会增加有人提供帮助的机会。
标签: firebase flutter dart google-cloud-firestore firebase-security