Flutter showDialog with loading spinner and confirmation - flutter

In flutter, I have a showDialog() with cancel and confirm button. The confirm button will trigger a call to an API. What I need is to show a "loading..." in the showDialog window after the click and once the API call is finished to show a success or failure. How can I manage this? Or should I close the window, waiting for the reply and popup a new dialog window with success or false? Thx for any help or better suggestion. Here what I have so far:
void _showAlert(String textLabel, String action, String linkId) {
showDialog(
context: context,
//barrierDismissible: false, // on external click
builder: (_) => new AlertDialog(
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10.0)),
title: new Text(
'Please confirm:',
style: TextStyle(color: Colors.deepOrange, fontWeight: FontWeight.bold),
textAlign: TextAlign.center,
),
content: new Text(
textLabel,
style: new TextStyle(fontSize: 20.0),
),
actions: <Widget>[
new FlatButton(
onPressed: () {
Navigator.pop(context);
},
child: new Text('CANCEL')),
new FlatButton(
onPressed: () {
_postAction(action, linkId).then((_) => setState(() {}));
Navigator.pop(context);
},
child: new Text('I CONFIRM')),
],
));
}

You can try this,this is just the idea..
class _SampleState extends State<Sample> {
bool isSuccessFromApi = false;
bool isLoading = false;
Widget popup() {
showDialog(context: context, builder: (builder) {
return AlertDialog(
content: !isSuccessFromApi ? Container(
child: Text('Are you Sure???'),
) : Container( child: isLoading ? CircularProgressIndicator() : Text('Success'),),
actions: <Widget>[
Text('Cancel'),
InkWell(child: Text('OK'), onTap: apiCall,)
],
);
});
}
void apiCall(){
setState(() {
isLoading = true;
});
//call the api
//after success or failure
setState(() {
isLoading = false;
isSuccessFromApi = true;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: popup(),
);
}
}

Related

flutter close alert dialog builder after speech recognition finished

Hello friends i am working on speech recognition in flutter i made custom alert dialogue like native dialog when user click on button alert dialog appear and when user speak it show text on alert dialog my problem is that i want when user finishing his speech alert dialogue will automatically close please let me know how i can perform this task?
stt.SpeechToText speechToText = stt.SpeechToText();
bool islistening = false;
late String text = 'Example:Genesis chapter 1 verse 5';
bool complete=false;
final GlobalKey _dialogKey = GlobalKey();
ValueNotifier<bool> buttonClickedTimes =ValueNotifier(false);
_showDialog() async {
showDialog(
context:context,
barrierDismissible: true,
builder: (BuildContext context) {
return StatefulBuilder(
key: _dialogKey,
builder: (context, setState) {
return Container(
child: Dialog(
child: Padding(
padding: const EdgeInsets.all(8),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const AvatarGlow(
glowColor: Colors.blue,
endRadius: 80,
duration: Duration( milliseconds: 2500),
repeat: true,
showTwoGlows: true,
repeatPauseDuration: Duration( milliseconds: 150),
child: Material(
elevation: 5,
shape: CircleBorder(),
child: CircleAvatar(
backgroundColor: Colors.white,
child: Icon(Icons.mic, color: Colors.blue, size: 40,),
radius: 40,
),
),
),
Text(text),
const SizedBox(height: 10),
TextButton(
onPressed: () => Navigator.pop(context, false), // passing false
child: const Text('Cancel Voice'),
),
],
),
),
),
);
},
);
},
);
}
final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey();
void _listen() async {
if (!islistening) {
bool available = await speechToText.initialize(
onStatus: (val) => print('onStatus: $val'),
onError: (val) => print('onError: $val'),
);
if (available) {
setState(() {
islistening = true;
});
speechToText.listen(
onResult: (result) =>
setState(() {
text = result.recognizedWords;
if (_dialogKey.currentState != null && _dialogKey.currentState!.mounted && speechToText.isListening) {
_dialogKey.currentState!.setState(() {
text =result.recognizedWords;
});}
else{
if(text.contains('Genesis')){
setState(() {
String bigSentence =text;
var voice= bigSentence.split(" ");
var bookname=voice[0];
var booknumber=1;
int chapternumber=int.parse(voice[2]);
int versenumber=int.parse(voice[4]);
if(_regExp.hasMatch(chapternumber.toString())&&_regExp.hasMatch(versenumber.toString())){
Navigator.push(
context,
MaterialPageRoute(builder: (context) => Allverse(bookname, booknumber,chapternumber, versenumber)),
);
}else{
Fluttertoast.showToast(
msg: "check chapter number or versenumber",
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.CENTER,
backgroundColor: Colors.red,
textColor: Colors.white,
fontSize: 16.0
);
}
});
}
}
})
);
}
} else
{
setState(() => islistening = false);
speechToText.stop();
}
}

How to add a new button when onPressed is called?

I have an Elevated Icon Button that when pressed displays a Dialog that prompts a user to enter text and select an amount from a NumberPicker. The showDialog function is called that saves the user's entry in a TextEditingController:
How would I create a function that once the user saves their entry in Dialog, creates a new button that displays TextEditingController.text as shown in the below:
_addItem code:
Future<void> _addItem(BuildContext context) async {
valueText = '';
return showDialog(
context: context,
builder: (context) {
return AlertDialog(
title: Text('Example'),
content: Row(
children: [
Container(
width: 150,
child: TextField(
onChanged: (value) {
setState(() {
valueText = value;
});
},
controller: _textController,
decoration: InputDecoration(hintText: '"Example"'),
),
),
NumberPicker(
value: _currentValue,
minValue: 0,
maxValue: 100,
onChanged: (value) => setState(() => _currentValue = value),
),
],
),
actions: <Widget>[
ElevatedButton(
child: Text('CANCEL'),
onPressed: () {
setState(() {
Navigator.pop(context);
});
},
),
ElevatedButton(
child: Text('OK'),
onPressed: () {
setState(() {
codeDialog = valueText;
Navigator.pop(context);
});
},
),
],
);
});
}
Currently the button updates to the textEditingController.text. I want to replace the Icon with the number selected by the user but I'll figure that out later. Probably best to just replace it with a conditional statement that renders a list of different buttons. They need to be buttons so they can be edited if needed before all data is sent to a server.
You have to use statement in the build method of your Stateful widget
... State of your widget ...
final TextController _textController;
final int _currentValue;
Widget build(context) {
return YourWidgetTree(
child: Row(
children: [
ElevatedButton(child: Text('Add item')),
if(_controller.text.isNotEmpty)
ElevatedButton(child: Text('$_currentValue ${_controller.text}', onPressed: (){ ... })),
])
)
}
Future<void> _addItem(BuildContext context) {...}

Update an AlertDialog with success or fail message after network communication

Summarize the Problem:
My application sends information to a server and the server responds with success or failure. I am having trouble updating an AlertDialog with the result of network communication. I am sending multiple items to the server when the user saves their settings and I need to track if all the settings were successfully sent. So when all the settings were successfully sent, I can update the AlertDialog with success. The issue I am seeing with current implementation is it takes me two times to activate the TextButton before I see the correct message. AlertDialog should show the correct message after the first TextButton press labeled as "save". One of the cases I need to solve is if the server is down and the app's connection request times out. Then I need to use something like a CircularProgressIndicator so the user can wait while network communication is being done.
The variable successPrompt is what contains the message with the result of the network transaction. This needs to be updated to the correct message by the time the AlertDialog pops up.
2: What I've tried:
I've tried using FutureBuilder to create the AlertDialog but I got the same result. I need a way to bring up the AlertDialog when I know the result of the network transaction. What happens is the AlertDialog will be brought up but the application is still trying to connect to the server in the background. I want to bring up the widget once this step is done and the socket is closed.
3: Here's the relevant code. Please don't mind the debug prints and commented out code.
import 'package:flutter/material.dart';
import 'dart:io';
import 'globals.dart';
import 'dart:convert' show utf8;
import 'package:local_auth/local_auth.dart';
class SystemsSettingsPage extends StatefulWidget {
final int index;
SystemsSettingsPage({ required this.index});
#override
_SystemsSettingsPage createState() => _SystemsSettingsPage();
}
class _SystemsSettingsPage extends State<SystemsSettingsPage> {
bool tileValTemp = false;
bool tileValDetect = false;
bool tileValCamOff = false;
bool tileValSystem = false;
bool connected = false;
int successCount = 0;
String successPrompt = "";
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.black,
appBar: AppBar(
backgroundColor: Colors.blueAccent,
title: Text("Base Station Settings"),
),
body: Column(
children: <Widget> [
SwitchListTile(value: tileValDetect,
onChanged: (bool val){ setState(() {
tileValDetect = val;
});},
title: Text('Detection notifications', style: TextStyle(color: Colors.white))
),
SwitchListTile(value: tileValTemp,
onChanged: (bool val){ setState(() {
tileValTemp = val;
});},
title: Text('Temperature threshold out of range', style: TextStyle(color: Colors.white))
),
TextButton(
child: const Text("save", style: TextStyle(fontSize: 20.0)),
style: ButtonStyle(foregroundColor: MaterialStateProperty.all<Color>(Colors.white),
padding: MaterialStateProperty.all<EdgeInsets>(EdgeInsets.all(10.0)),
backgroundColor: MaterialStateProperty.all<Color>(Colors.blueAccent)),
onPressed: () {
//successPrompt = "Loading.. Wait 5 seconds to update.";
successCount = 0;
Socket.connect(baseStationAddresses[0], baseStationPort,timeout: Duration(seconds: 5)).then(
(socket) {
print('Connected to: '
'${socket.remoteAddress.address}:${socket
.remotePort}');
String command = "SETSYSTEM," + baseStationNames[0] + ",detectMotion," + "$tileValDetect";
socket.write(command);
socket.listen((data) {
String socketData = utf8.decode(data);
if(socketData == "REQUEST_CONFIRMED") {
successCount += 1;
}
},
onDone: () {
socket.destroy();
},
);
},
).catchError((onError) {
print("here 1");
successPrompt = "There was a problem. Please retry.";
});
Socket.connect(baseStationAddresses[0], baseStationPort,timeout: Duration(seconds: 5)).then(
(socket) {
print('Connected to: '
'${socket.remoteAddress.address}:${socket
.remotePort}');
String command = "SETSYSTEM," + baseStationNames[0] + ",tempThreshold," + "$tileValTemp";
socket.write(command);
socket.listen((data) {
String socketData = utf8.decode(data);
if(socketData == "REQUEST_CONFIRMED") {
successCount += 1;
}
},
onDone: () {
print("SuccessCount $successCount");
if(successCount == 2)
{
print("here 2");
successPrompt = "Setting successfully saved.";
}
else
{
print("here 3");
successPrompt = "Couldn't save, please retry.";
}
socket.destroy();
},
);
}
).catchError((onError) {
print("here 4");
successPrompt = "There was a problem. Please retry.";
});
showDialog(context: context, builder: (context) =>
AlertDialog(
title: Text("Save results"),
content: Text(successPrompt),
actions: <Widget>[
TextButton(onPressed: () => Navigator.pop(context),
child: const Text("OK"),
)
]
)
);
/*
FutureBuilder<String>(
future: getSaveStatus(),
builder: (context, snapshot) {
String nonNullableString = snapshot.data ?? 'Error';
if(snapshot.hasData) {
return AlertDialog(
title: Text("Save results"),
content: Text(nonNullableString),
actions: <Widget>[
TextButton(onPressed: () => Navigator.pop(context),
child: const Text("OK"),
)
]
);
}
return Center(child: CircularProgressIndicator());
},
);*/
}
),
Center(
child:ClipRRect(
borderRadius: BorderRadius.circular(4),
child: Stack(
children: <Widget>[
Positioned.fill(
child: Container(
decoration: const BoxDecoration(
color: Colors.red,
),
),
),
TextButton(
style: TextButton.styleFrom(
padding: const EdgeInsets.all(16.0),
primary: Colors.white,
textStyle: const TextStyle(fontSize: 20),
),
onPressed: () {},
child: const Text('Remove System'),
),
],
),
),
)
],
)
);
}
Future<String> getSaveStatus() async {
return await new Future(() => successPrompt);
}
}
Any suggestion would be helpful.
Wrap the content of the dialog inside of a StatefulBuilder until that your AlertDialog behave as stateless widget Refer:
await showDialog<void>(
context: context,
builder: (BuildContext context) {
int selectedRadio = 0;
return AlertDialog(
content: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Text(successPrompt);
},
),
);
},
);

Flutter how to reload entire page

In my application, a user enters data and then it is uploaded to firestore. After this, I would like all the fields to be empty and basically, the entire page reloaded. How do you reload the whole page after an action or button click? I have added the respective stateful classes.
Main Class
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: TestForm(),
),
);
}
}
class TestForm extends StatefulWidget {
#override
_TestFormState createState() => _TestFormState();
}
How to reload this entire form by clicking a button but without going to a new page and being able to go back again.
class _TestFormState extends State<TestForm> {
final _formKey = GlobalKey<FormState>();
File _imageFile;
String locWorking;
Model model = Model();
Future<void> _getLocation() async {
Position position = await Geolocator()
.getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
print(position.toString());
setState(() {
model.location = position.toString();
});
}
Future<void> _pickImage(ImageSource source) async {
File selected = await ImagePicker.pickImage(source: source);
setState(() {
_imageFile = selected;
String fileName = 'images/${DateTime.now()}.png';
model.picName = fileName;
model.picCheck = true;
});
}
#override
Widget build(BuildContext context) {
final halfMediaWidth = MediaQuery.of(context).size.width / 2.0;
model.checkBox = false;
return Scaffold(
appBar: AppBar(
title: Text("Form Demo"),
),
body: Form(
key: _formKey,
child: Column(
children: <Widget>[
Container(
alignment: Alignment.topCenter,
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Container(
alignment: Alignment.topCenter,
width: halfMediaWidth,
child: MyTextFormField(
hintText: 'Name',
validator: (String value) {
if (value.isEmpty) {
return 'Enter your first name';
}
return null;
},
onSaved: (String value) {
model.firstName = value;
},
),
),
Container(
alignment: Alignment.topCenter,
width: halfMediaWidth,
child: RaisedButton(
color: Colors.blueAccent,
onPressed: () {
_getLocation();
},
child: Text("Get Location")))
],
),
),
MyTextFormField(
hintText: 'Description',
validator: (String value) {
if (value.isEmpty) {
return 'Please Enter Description';
}
return null;
},
onSaved: (String value) {
model.email = value;
},
),
StatefulBuilder(
builder: (context, setState) => CheckboxListTile(
title: Text("Need urgent repair"),
value: model.checkBox,
onChanged: (bool newValue) {
setState(() {
model.checkBox = newValue;
});
},
controlAffinity:
ListTileControlAffinity.leading, // <-- leading Checkbox
),
),
RaisedButton(
color: Colors.blueAccent,
onPressed: () {
if (_formKey.currentState.validate()) {
print(locWorking);
_formKey.currentState.save();
if (model.location == null) {
print("No location");
setState(() {
model.dataCheck = false;
});
print(model.dataCheck);
showDialog(
context: context,
builder: (context) => AlertDialog(
title: new Text("Error"),
content:
new Text("No location has been picked up"),
actions: <Widget>[
new FlatButton(
onPressed: () {
Navigator.of(context).pop();
},
child: new Text("Close"))
],
));
} else {
print("All checks passed...");
setState(() {
model.dataCheck = true;
});
print(model.dataCheck);
}
if (model.picCheck == false || model.picCheck == null) {
showDialog(
context: context,
builder: (context) => AlertDialog(
title: new Text("Notice"),
content: new Text("No picture has been added..."),
actions: <Widget>[
new FlatButton(
onPressed: () {
setState(() {
model.picCheck = true;
model.picName = "Null";
});
Navigator.of(context).pop();
},
child: new Text("No Picture Needed")),
new FlatButton(
onPressed: () {
Navigator.of(context).pop();
},
child: new Text("Close"))
],
));
}
}
},
child: Text(
'Check Data',
style: TextStyle(
color: Colors.white,
),
),
),
if (_imageFile != null) ...[
Uploader(
file: _imageFile,
fileName: model.picName,
),
],
if (model.dataCheck == true && model.picCheck == true) ...[
DataAdder(model: this.model),
],
],
),
),
bottomNavigationBar: BottomAppBar(
child: Row(
children: <Widget>[
IconButton(
icon: Icon(Icons.photo_camera),
onPressed: () => _pickImage(ImageSource.camera),
),
IconButton(
icon: Icon(Icons.photo_library),
onPressed: () => _pickImage(ImageSource.gallery),
),
],
),
),
);
}
}
Update How to reset the state of the app:
The question wanted to reset the state of the app, not the text field. You can achieve this using the Flutter Phoenix package.
How to reset the TextField input after pressing a button:
setState() rebuilds the build() method in you class every time it's called, but I assume what you mean is you want the text fields to become empty after the user have clicked a button, you could do this by using a TextEditingController.
Declaration:
TextEditingController controller = TextEditingController();
use case:
Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
TextField(
controller: controller,
decoration: InputDecoration(
hintText: "Enter your first name",
),
),
RaisedButton(onPressed: () {
controller.clear();
child:
Text(
"Clear",
);
})
],
),
This should clear the TextField each time the button is pressed.

I want to get an integer value from the Future which printing Instance of Future 'dynamic' function in flutter and firestore

I want to get an integer value in Future function which must be compared in a if condition when i'm pressing my fab button but instead of getting the number of documents in the collection it's giving in the log console 'Instance of Future' but I need my method to return a number.
this is my code:
class MembresPage extends StatefulWidget {
#override
_MembresPageState createState() => _MembresPageState();
}
class _MembresPageState extends State<MembresPage> {
Map<String, String> sublingData = {};
String nomComplet;
String adresse;
String ldNais;
QuerySnapshot subling;
CrudMethods crudObj = new CrudMethods();
Future<bool> addDialog(BuildContext context) async{
return showDialog(
context: context,
barrierDismissible: false,
builder: (BuildContext context){
return AlertDialog(
title: Text('Ajouter Membre', style: TextStyle(fontSize: 15.0)),
content: Column(
children: <Widget>[
TextField(
decoration: InputDecoration(hintText: 'Nom Complet'),
onChanged: (value){
this.nomComplet =value;
},
),
SizedBox(height: 8.0),
TextField(
decoration: InputDecoration(hintText: 'Ex: Kinshasa, le 21/12/1960'),
onChanged: (value){
this.ldNais = value;
},
),
SizedBox(height: 8.0),
TextField(
decoration: InputDecoration(hintText: 'Adresse'),
onChanged: (value){
this.adresse = value;
},
),
],
),
actions: <Widget>[
FlatButton(
child: Text('Ajouter'),
textColor: Colors.deepOrangeAccent[400],
onPressed: () async {
Navigator.of(context).pop();
sublingData = {
'nomComplet':this.nomComplet,
'ldNais': this.ldNais,
'adresse':this.adresse
};
PaiementStripe().addMembers(sublingData).then((result){
dialogTrigger(context);
}).catchError((e){
print(e);
});
},
)
],
);
});
}
Future<bool> updateDialog(BuildContext context, selectedDoc) async{
return showDialog(
context: context,
barrierDismissible: false,
builder: (BuildContext context){
return AlertDialog(
title: Text('Modifier Membre', style: TextStyle(fontSize: 15.0)),
content: Column(
children: <Widget>[
TextField(
decoration: InputDecoration(hintText: 'Nom Complet'),
onChanged: (value){
this.nomComplet =value;
},
),
SizedBox(height: 8.0),
TextField(
decoration: InputDecoration(hintText: 'Ex: Kinshasa, le 21/12/1960'),
onChanged: (value){
this.ldNais = value;
},
),
SizedBox(height: 8.0),
TextField(
decoration: InputDecoration(hintText: 'Adresse'),
onChanged: (value){
this.adresse = value;
},
),
],
),
actions: <Widget>[
FlatButton(
child: Text('Modifier'),
textColor: Colors.deepOrangeAccent[400],
onPressed: (){
Navigator.of(context).pop();
/*sublingData = {
'nomComplet':this.nomSubling,
'lieuNais': this.lieuNais,
'dateNais':this.dateNais
};*/
PaiementStripe().updateMembers(selectedDoc,{
'nomComplet':this.nomComplet,
'ldNais': this.ldNais,
'adresse':this.adresse
}).then((result){
//dialogTrigger(context);
}).catchError((e){
print(e);
});
PaiementStripe().getMembers().then((result){
setState(() {
subling = result;
});
});
},
)
],
);
});
}
Future<bool> dialogTrigger(BuildContext context) async{
return showDialog(
context: context,
barrierDismissible: false,
builder: (BuildContext context){
return AlertDialog(
title: Text('Info', style: TextStyle(fontSize: 15.0)),
content: Text('Membre ajouté'),
actions: <Widget>[
FlatButton(
child: Text('OK'),
textColor: Colors.deepOrangeAccent[400],
onPressed: (){
PaiementStripe().getMembers().then((result){
setState(() {
subling = result;
});
});
Navigator.of(context, rootNavigator: true).pop();
},
)
],
);
});
}
void showSnackBar(BuildContext context, docID){
var snackBar = SnackBar(
content: Text("Voulez vous Supprimer le membre?"),
action: SnackBarAction(
label: "OUI",
onPressed: (){
PaiementStripe().deleteMembers(docID);
PaiementStripe().getMembers().then((result){
setState(() {
subling = result;
});
});
}
),
);
Scaffold.of(context).showSnackBar(snackBar);
}
void seeSnackBar(BuildContext context){
var snackBar = SnackBar(
content: Text("Vous avez le maximum de membres"),
);
Scaffold.of(context).showSnackBar(snackBar);
}
#override
void initState(){
PaiementStripe().getMembers().then((result){
setState(() {
subling = result;
});
});
super.initState();
}
// the method that I need to return an Integer value
Future<int> countDocuments() async {
FirebaseUser user = await FirebaseAuth.instance.currentUser();
QuerySnapshot _myDoc = await Firestore.instance.collection('users').document(user.uid).collection('sublings').getDocuments();
List<DocumentSnapshot> _myDocCount = _myDoc.documents;
return _myDocCount.length;
//Count of Documents in Collection
}
#override
Widget build(BuildContext context) {
return Scaffold(
floatingActionButton:Column(
crossAxisAlignment: CrossAxisAlignment.end,
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
FloatingActionButton(
heroTag: 'fab1',
onPressed: (){
//the test comparison
if (countDocuments() < 5){
addDialog(context);
print(countDocuments());
}
else{
seeSnackBar(context);
}
},
child: Icon(
Icons.add,
color: Colors.white,
),
backgroundColor: Colors.deepOrangeAccent,
),
]
),
body:_sublingList(),
);
}
Widget _sublingList(){
if(subling!=null){
return ListView.separated(
itemCount: subling.documents.length,
padding: EdgeInsets.all(5.0),
itemBuilder: (context, i){
return ListTile(
leading: Icon(Icons.account_circle,
size: 60.0,),
title: Text(subling.documents[i].data['nomComplet'],
style: TextStyle(
fontWeight: FontWeight.bold,
fontFamily: 'OpenSans'
),),
subtitle: Text(subling.documents[i].data['ldNais'] +'\n'+subling.documents[i].data['adresse']),
onTap: (){
updateDialog(context, subling.documents[i].documentID);
PaiementStripe().getMembers().then((result){
setState(() {
subling = result;
});
});
},
onLongPress: (){
showSnackBar(context,subling.documents[i].documentID);
},
);
},
separatorBuilder: (context, i){
return Divider();
},
);
}
else{
return Center(
child: CircularProgressIndicator(),
);
}
}
}
when I am pressing the fab button, I am getting this message:
Instance of Future'dynamic'
5 //which is the number of documents
that's why it's not possible to compare it
you need to await the Future function to finish
onPressed: () async {
//the test comparison
int count = await countDocuments();
if (count < 5){
addDialog(context);
print(countDocuments());
}
else{
seeSnackBar(context);
}
},
you can do that
void getCount(){
countDocuments().then((count ) {
// print(result);
if (count < 5){
addDialog(context);
print(countDocuments());
}
else{
seeSnackBar(context);
}
});
}