Raj*_*Jr. 3 dart firebase flutter google-cloud-firestore
我有一个名为的收藏company。所有公司都将像我的屏幕快照中那样存储。
当我添加其他公司时,我想检查是否name已经存在。如何执行?
在这里,“ Nova”和“ Tradetech”是两家公司。
当我尝试再次在该字段中添加“ Nova”name: "nova"时,我想显示一个通知:“公司已经存在!” 。
您可以简单地使用where查询来仅接收具有该查询的文档,name然后检查是否获取了文档。这是async将执行您想知道的内容的示例方法。
Future<bool> doesNameAlreadyExist(String name) async {
final QuerySnapshot result = await Firestore.instance
.collection('company')
.where('name', isEqualTo: name)
.limit(1)
.getDocuments();
final List<DocumentSnapshot> documents = result.documents;
return documents.length == 1;
}
Run Code Online (Sandbox Code Playgroud)
如您所见,我仅收到name字段与给定匹配的文档name。我还要补充一点limit(1),以确保我不会不必要地检索超过1个文档(理论上永远不会发生),然后我只检查集合length中所有文档的in company是否等于1。如果等于1,则已经有一个公司使用该名称,否则不使用。
您也可以删除limit(1)和进行检查documents.length > 1,这也可以,但是可能会检索不必要的文档。
@override
Widget build(BuildContext context) {
return FutureBuilder(
future: doesNameAlreadyExist('nova'),
builder: (context, AsyncSnapshot<bool> result) {
if (!result.hasData)
return Container(); // future still needs to be finished (loading)
if (result.data) // result.data is the returned bool from doesNameAlreadyExists
return Text('A company called "Nova" already exists.');
else
return Text('No company called "Nova" exists yet.');
},
);
}
Run Code Online (Sandbox Code Playgroud)
在这里,我没有显示错误消息,使用示例方法也很容易实现。但是,使用build了一些小部件的方法。例如,这可以在对话框中工作,但我决定这样做以使其简单易懂。该FutureBuilder发生在doesNameAlreadyExist,在这种情况下,一个名为“新星”从你的问题,并会在年底,返回一个Text小部件,说明名字是否已经存在。
该where查询区分大小写。这意味着如果您键入例如“ noVa”而不是“ nova”,则该检查将不起作用。因为这对您可能很重要,所以您可以使用这个不错的方法,在该方法中,您将创建一个不敏感的额外字段,例如,所有字母都很小,然后您将像这样简单查询:
.where('name_insensitive', isEqualTo: name.toLowerCase())
Run Code Online (Sandbox Code Playgroud)
I have solved this issue with the follwoing code, thanks for helping me!
IN THE FOLLOWING CODE I USED TO FIND
1)A DOCUMENT IS EXISTING OR NOT?
2)A KEY IS EXISTING OR NOT?
3)A VALUE IS EXISTING OR NOT?
SIMPLE METHOD
//////////////////////////////////////////////////////////////////////
import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'dart:async';
String myText1 = 'temp1';
String myText2 = 'temp2';
String myText3 = 'temp3';
String myText4 = 'temp4';
String myText5 = 'temp5';
String myText6 = 'temp6';
StreamSubscription<DocumentSnapshot> subscription;
final DocumentReference documentReference =
Firestore.instance.document("company/Nova");
class Clean extends StatefulWidget {
@override
_CleanState createState() => _CleanState();
}
class _CleanState extends State<Clean> {
@override
void initState() {
super.initState();
subscription = documentReference.snapshots().listen((datasnapshot) {
//FINDING A SPECIFICDOCUMENT IS EXISTING INSIDE A COLLECTION
if (datasnapshot.exists) {
setState(() {
myText1 = "Document exist";
});
} else if (!datasnapshot.exists) {
setState(() {
myText2 = "Document not exist";
});
}
//FINDING A SPECIFIC KEY IS EXISTING INSIDE A DOCUMENT
if (datasnapshot.data.containsKey("name")) {
setState(() {
myText3 = "key exists";
});
} else if (!datasnapshot.data.containsKey("name")) {
setState(() {
myText4 = "key not exists";
});
}
//FINDING A SPECIFIC VALUE IS EXISTING INSIDE A DOCUMENT
if (datasnapshot.data.containsValue("nova")) {
setState(() {
myText5 = "value exists";
});
} else if (!datasnapshot.data.containsValue("nova")) {
setState(() {
myText6 = "value not exists";
});
}
});
}
@override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
new Text(myText1),
new Text(myText2),
new Text(myText3),
new Text(myText4),
new Text(myText5),
new Text(myText6),
],
);
}
}
Run Code Online (Sandbox Code Playgroud)
MY OLD COMPLEX METHOD BASED ON MY EXISTING CODE ////////////////////////////////////////////////////////
it has a search bar,when you type it will show the company name ie existing or not in
一Card和RaisedButton。为了避免搜索错误,我在Firestore中使用小写字母。我已将TextFormField输出强制为小写toLowercase()。您可以将其更改为自己的文本格式。
//if the name is not existing it will show a raised button so u can clcik on that to
//go to a COMPANY ADDING PAGE,otherwise it will only show a **CARD** so that you
//can't go to the next page to add your company
//code:
import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'dart:async';
import './fullscreen.dart';
const blue = 0xFF3b78e7;
String filter = '';
StreamSubscription<DocumentSnapshot> subscription;
final TextEditingController _usercontroller = new TextEditingController();
class CheckAvail extends StatefulWidget {
@override
HomeState createState() => HomeState();
}
class HomeState extends State<CheckAvail> {
@override
Widget build(BuildContext context) {
return Scaffold(
resizeToAvoidBottomPadding: false,
body: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
// CHILD1
new Flexible(
child: StreamBuilder(
stream: Firestore.instance
.collection('company')
.where('name', isGreaterThanOrEqualTo: filter.toLowerCase())
.limit(1)
.snapshots(),
builder: (BuildContext context,
AsyncSnapshot<QuerySnapshot> snapshot) {
if (!snapshot.hasData) {
return new Column(
children: <Widget>[
new Card(
elevation: 5.0,
child: new Image.asset('assets/progress.gif'),
)
],
);
} else {
return FirestoreListView1(documents: snapshot.data.documents);
}
},
),
),
new Card(
elevation: 0.0,
color: Colors.white,
shape: new RoundedRectangleBorder(
borderRadius: BorderRadius.circular(60.0)),
child: Container(
padding: new EdgeInsets.only(left: 8.0),
child: new TextField(
controller: _usercontroller,
onChanged: (String z) {
setState(() {
filter = z;
});
},
decoration: const InputDecoration(
hintText: "Search...",
hintStyle: TextStyle(
fontFamily: 'roboto',
color: Colors.black38,
fontSize: 16.0,
letterSpacing: -0.500),
fillColor: Colors.white,
border: InputBorder.none,
),
),
),
),
],
),
backgroundColor: Color(blue),
);
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
class FirestoreListView1 extends StatelessWidget {
final List<DocumentSnapshot> documents;
FirestoreListView1({this.documents});
@override
Widget build(BuildContext context1) {
return ListView.builder(
itemCount: documents.length,
padding: new EdgeInsets.all(1.0),
itemBuilder: (BuildContext context1, int index) {
String name = documents[index].data['name'];
if (name.contains(filter.toLowerCase()) &&
name.length == filter.length) {
return new Container(
padding: new EdgeInsets.only(top: 45.0),
child: new Card(
child: new Text(
"Error:Already a Company Exists with this name\nTry another name")),
);
} else {
return (filter.length >= 1)
? new Container(
padding: new EdgeInsets.only(top: 15.0),
child: new RaisedButton(
onPressed: () => Navigator.push(
context1,
new MaterialPageRoute(
builder: (context1) => new NextPage(
value1: name,
))),
disabledColor: Colors.white,
child: new Text(
"Good!You can use this company name",
),
),
)
: new Container(padding: new EdgeInsets.only(top: 250.0),
child: new Card(child: new Text("CHECK IF YOUR COMPANY NAME \n AVAILABLE OR NOT",style: new TextStyle(fontSize: 20.0),)),
);
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
final QuerySnapshot result =
await Firestore.instance.collection('users').where('nickname', isEqualTo:
nickname).getDocuments();
final List < DocumentSnapshot > documents = result.documents;
if (documents.length > 0) {
//exists
} else {
//not exists
}
Run Code Online (Sandbox Code Playgroud)
小智 5
使用该功能:
snapshot.data!.data()!.containsKey('key_name')
Run Code Online (Sandbox Code Playgroud)
检查文档中是否存在某个字段。
附言。我刚刚在我的代码 RN 中使用了它并且它有效
| 归档时间: |
|
| 查看次数: |
5949 次 |
| 最近记录: |