how can I get access to a document in firebase? - firebase

in my project im trying to get the id of the video and then open the video in my video but im struggling in 3 points
how can I can save real id into firebase?
this is how im doing it right know
uploadVideo() async {
setState(() {
isuploading = true;
});
try {
var firebaseuseruid = FirebaseAuth.instance.currentUser.uid;
DocumentSnapshot userdoc = await FirebaseFirestore.instance
.collection('meinprofilsettings')
.doc(firebaseuseruid)
.get();
var alldocs = await FirebaseFirestore.instance.collection('videos').get();
int length = alldocs.docs.length;
String videourl = await uploadvideotostorage("Video $length");
String previewimage = await uploadimagetostorage("Video $length");
FirebaseFirestore.instance.collection('videos').doc("Video $length").set({
'username': userdoc.data()['username'],
'uid': firebaseuseruid,
'profilepic': userdoc.data()['url'],
'id':"Video $length",
'likes': [],
'commentcount': 0,
'sharecount': 0,
'hashtag1': hashtagcontroller.text,
'hashtag2': hashtagcontroller2.text,
'hashtag3': hashtagcontroller3.text,
'videourl': videourl,
'previewimage': previewimage,
'ratings': [],
});
Navigator.pop(context);
} catch (e) {
print(e.toString());
}
}
}
what I want is the real id of the video instead of "Video $length"
2. how can I get access to the id when its created like how can I call it ? ?
3. How can I create a new collection with this id and then like saving some data but like this
new collection=> videoed => new field with some data , new field with some data
Heres how I upload it
the picture is for preview picture
getpreviewimage() async {
final previewimage = await flutterVideoCompress.getThumbnailWithFile(
widget.videopath_asstring,
);
return previewimage;
}
compressvideo() async {
if (widget.imageSource == ImageSource.gallery) {
return widget.videofile;
} else {
final compressvideo = await flutterVideoCompress.compressVideo(
widget.videopath_asstring,
quality: VideoQuality.MediumQuality);
return File(compressvideo.path);
}
}
uploadvideotostorage(String id) async {
final video = await allvideos.child(id).putFile(await compressvideo());
String url = await video.ref.getDownloadURL();
return url;
}
uploadimagetostorage(String id) async {
final video = await allimages.child(id).putFile(await getpreviewimage());
String url = await video.ref.getDownloadURL();
id=url;
return url;
}

If I understood correctly, change them to look like this:
Future<String> uploadvideotostorage(String id) async {
final video = await allvideos.child(id).putFile(await compressvideo());
String url = await video.ref.getDownloadURL();
return url;
}
Future<String> uploadimagetostorage(String id) async {
final video = await allimages.child(id).putFile(await getpreviewimage());
String url = await video.ref.getDownloadURL();
return url;
}
and this:
String videourl = await uploadvideotostorage(firebaseuseruid);
'id':videourl,
This is assuming that compressvideo() is working correctly.

Related

Is there any way to save flutter_tts file to firebase storage?

I am working on a flutter project in which user is supposed to create some scripts and by typing them in text and then flutter_tts library is supposed to convert them to audio file which works fine for that time being but I want to save that file into firebase storage for later user. I have tried the following code but it just saves blank audio file in the firebase storage. Any kind of help will be appreciated.
The code I have tried is:
final FlutterTts _flutterTts = FlutterTts();
late var fileName;
/// creation of audio script
Future createAudioScript(
String name,
String script,
String firebasepath,
) async {
await _flutterTts.setLanguage("en-US");
await _flutterTts.setSpeechRate(1.0);
await _flutterTts.setVolume(1.0);
await _flutterTts.setPitch(1.0);
await _flutterTts.setVoice(
{"name": "en-us-x-tpf-local", "locale": "en-US"},
);
await _flutterTts.speak(script);
fileName = GetPlatform.isAndroid ? '$name.wav' : '$name.caf';
print('FileName: $fileName');
var directoryPath =
"${(await getApplicationDocumentsDirectory()).path}/audio/";
var directory = Directory(directoryPath);
if (!await directory.exists()) {
await directory.create();
print('[INFO] Created the directory');
}
var path =
"${(await getApplicationDocumentsDirectory()).path}/audio/$fileName";
print('[INFO] path: $path');
var file = File(path);
if (!await file.exists()) {
await file.create();
print('[INFO] Created the file');
}
await _flutterTts.synthesizeToFile(script, fileName).then((value) async {
if (value == 1) {
print('generated');
var file = File(
'/storage/emulated/0/Android/data/com.solution.thriving/files/$fileName',
);
print(file);
moveFile(file, path, '$firebasepath/$fileName').then((value) {
print('move file: $value');
_app.link.value = value;
print('link: ${_app.link.value}');
});
}
});
}
/// move file from temporary to local storage and save to firebase
Future<String> moveFile(
File sourceFile,
String newPath,
String firebasePath,
) async {
String audioLink = '';
print('moved');
await sourceFile.copy(newPath).then((value) async {
print('value: $value');
await appStorage.uploadAudio(value, fileName, firebasePath).then((audio) {
print(audio);
audioLink = audio;
return audioLink;
});
}).whenComplete(() async {
customToast(message: 'Audio has been generated successfully.');
});
return audioLink;
}
After spending whole day and with the help of a friend, I finally managed to figure out the issue which was being caused because I was using synthesizeToFile() and speak() functions at the same time, which I managed to resolved the issue by changing my code to the following code snippet.
final FlutterTts _flutterTts = FlutterTts();
late var fileName;
/// converting text to speech
Future createAudioScript(
String name,
String script,
String firebasepath,
) async {
await _flutterTts.setLanguage("en-US");
await _flutterTts.setSpeechRate(1.0);
await _flutterTts.setVolume(1.0);
await _flutterTts.setPitch(1.0);
await _flutterTts.setVoice(
{"name": "en-us-x-tpf-local", "locale": "en-US"},
);
if (GetPlatform.isIOS) _flutterTts.setSharedInstance(true);
// await _flutterTts.speak(script);
fileName = GetPlatform.isAndroid ? '$name.wav' : '$name.caf';
log('FileName: $fileName');
await _flutterTts.synthesizeToFile(script, fileName).then((value) async {
if (value == 1) {
log('Value $value');
log('generated');
}
});
final externalDirectory = await getExternalStorageDirectory();
var path = '${externalDirectory!.path}/$fileName';
log(path);
saveToFirebase(path, fileName, firebasPath: '$firebasepath/$name')
.then((value) => {log('Received Audio Link: $value')});
}
/// saving converted audio file to firebase
Future<String> saveToFirebase(String path, String name,
{required String firebasPath}) async {
final firebaseStorage = FirebaseStorage.instance;
SettableMetadata metadata = SettableMetadata(
contentType: 'audio/mpeg',
customMetadata: <String, String>{
'userid': _app.userid.value,
'name': _app.name.value,
'filename': name,
},
);
var snapshot = await firebaseStorage
.ref()
.child(firebasPath)
.putFile(File(path), metadata);
var downloadUrl = await snapshot.ref.getDownloadURL();
print(downloadUrl + " saved url");
return downloadUrl;
}

DateTime not a subtype of type TimeStamp/Unhandled Exception: Invalid argument: Instance of 'Future<LocationData>

So I am using the nearby connections API to discover devices around me and store their data in firestore however I keep getting 2 warnings about the location I am getting from the user that I came in contact with and the time i came in contact with them
These are the 2 warnings:
1)DateTime not a subtype of type TimeStamp
2)Unhandled Exception: Invalid argument: Instance of Future<.LocationData.>
as I try to add these values to firestore
here is my discovery method:
void discovery() async {
try {
bool a = await Nearby().startDiscovery(loggedInUser.email, strategy,
onEndpointFound: (id, name, serviceId) async {
print('I saw id:$id with name:$name'); // the name here is an email
var docRef =
_firestore.collection('users').document(loggedInUser.email);
// When I discover someone I will see their email
docRef.collection('met_with').document(name).setData({
'email': await getUsernameOfEmail(email: name),
'contact time': DateTime.now() as Timestamp ,
'contact location': location.getLocation(),
});
}, onEndpointLost: (id) {
print(id);
});
print('DISCOVERING: ${a.toString()}');
} catch (e) {
print(e);
}
}
This is another method where I retrieve the info I discovered from firestore:
void addContactsToList() async {
await getCurrentUser();
_firestore
.collection('users')
.document(loggedInUser.email)
.collection('met_with')
.snapshots()
.listen((snapshot) {
for (var doc in snapshot.documents) {
String currEmail = doc.data['email'];
DateTime currTime = doc.data.containsKey('contact time')
? (doc.data['contact time'] as Timestamp).toDate()
: null;
String currLocation = doc.data.containsKey('contact location')
? doc.data['contact location']
: null;
String _infection = doc.data['infected'];
if (!contactTraces.contains(currEmail)) {
contactTraces.add(currEmail);
contactTimes.add(currTime);
contactLocations.add(currLocation);
infection.add(_infection);
}
}
setState(() {});
print(loggedInUser.email);
});
}
Any fix for this please?
Use an async function to convert the Future<.LocationData.> to LocationData.
var data;
void convertData() async{
var futuredata = await FutureLocationData;
setState(() {
data = futuredata });
}

How to store image in fire base and store url in firestore

i want to send coupon card to fire store that contain ( name - address - coupon ) and i want to make user set an specific image for every single card
that's my FireStoreService file
class FireStoreService {
FireStoreService._internal();
static final FireStoreService firestoreService = FireStoreService._internal();
Firestore db = Firestore.instance ;
factory FireStoreService() {
return firestoreService;
}
Stream<List<Coupon>> getCoupon() {
return db.collection('coupon').snapshots().map(
(snapshot) => snapshot.documents.map(
(doc) => Coupon.fromMap(doc.data, doc.documentID),
).toList(),
);
}
Future<void> addCoupon(Coupon coupon) {
return db.collection('coupon').add(coupon.toMap());
}
Future<void> deleteCoupon(String id) {
return db.collection('coupon').document(id).delete();
}
Future<void> updateCoupon(Coupon coupon) {
return db.collection('coupon').document(coupon.id).updateData(coupon.toMap());
}
}
and this is Coupon Model file
class Coupon {
final String id;
final String storeName;
final String storeLink;
final String couponCode;
Coupon(
{this.id, this.storeName, this.storeLink, this.couponCode});
Coupon.fromMap(Map<String, dynamic> data, String id)
: storeName = data["storeName"],
storeLink = data['storeLink'],
couponCode = data["couponCode"],
id = id;
Map<String, dynamic> toMap() {
return {
"storeName": storeName,
'storeLink': storeLink,
'couponCode': couponCode,
};
}
}
and this is Image Picker code and it's work fine and picked up the image
Future getImage() async {
try {
File image = await ImagePicker.pickImage(source: ImageSource.gallery);
setState(() {
image = image;
});
} catch (e) {
print(e);
}
}
any help ?
This is a function that asks for an imageFile. If you run your code (getImage function): pass the image variable to the uploadImage function.
String myUrl = await uploadImage(file);
Then you can use setData or updateData to put the url in the database.
Firestore.instance.collection('books').document()
.setData({ 'title': 'title', 'url': '$myUrl' })
final StorageReference storageRef = FirebaseStorage.instance.ref();
Future<String> uploadImage(imageFile) async {
StorageUploadTask uploadTask =
storageRef.child("myPath&Name.jpg").putFile(imageFile);
StorageTaskSnapshot storageSnap = await uploadTask.onComplete;
String downloadURL = await storageSnap.ref.getDownloadURL();
return downloadURL;
}

i want to send the data under the userid and also fetch the same data

i am not able to send it under the current userid and also not able to fetch it for current userid.
basically i want to send the data under the userid and also fetch the same data.
So for that i want to change the current document name as the user id. but whenever i do that and i call _sendToServer() in an on pressed button it gives me error.
_sendToServer() {
if (_key.currentState.validate()) {
_key.currentState.save();
DatabaseReference ref = FirebaseDatabase.instance.reference();
final Firestore _db = Firestore.instance;
var data = {
"name": name,
"profession": profession,
"message": message,
};
_db
.collection('Profile')
.document('KoMna0Hv7VXoeABwFTGH7LTo1No2')
.setData(data)
.then((v) {
_key.currentState.reset();
});
}
}
also while fetching data i am not able to do this. as i am getting error in the below code.
fetchUser() async{
Future<List<Text>> getAllProfiles() async {
List<Text> returnList = [];
final Firestore _db = Firestore.instance;
await _db.collection("profile").getDocuments().then((QuerySnapshot snapshot) {
snapshot.documents.forEach((doc) {
var keys = snapshot.value.keys;
var data = snapshot.value;
allData.clear();
for (var key in keys) {
myData d = new myData(
data[key]['name'],
data[key]['message'],
data[key]['profession'],
);
allData.add(d);
}
setState(() {
print('Length : ${allData.length}');
});
});
});
return returnList;
}
}
i must provide these key value pair for fetching the data but unfortunately i am not able to do so.
I have added the orderByChild('id') and equalTo('${user.uid}') filed in the code with firebase user. and i also one more item to my list which is data[key]['id'], my current user id. this way everytime the user tries to fetch the data it will look into the list item for current userid and if it matches it will fetch that particular database only.
#override
// ignore: must_call_super
void initState() {
FirebaseAuth.instance.currentUser().then((user) {
fetchUser(user);
});
}
fetchUser(FirebaseUser user) {
DatabaseReference ref = FirebaseDatabase.instance.reference();
ref
.child('node-name')
.orderByChild('id')
.equalTo('${user.uid}')
.once()
.then((DataSnapshot snap) {
var keys = snap.value.keys;
var data = snap.value;
print(snap.value.toString());
allData.clear();
for (var key in keys) {
myData d = new myData(
data[key]['name'],
data[key]['number'],
data[key]['address'],
data[key]['id'],
data[key]['location'],
data[key]['website'],
);
allData.add(d);
}
setState(() {
print('Length : ${allData.length}');
});
});
}
_sendToServer() async{
FirebaseUser user = await FirebaseAuth.instance.currentUser();
if (_key.currentState.validate()) {
_key.currentState.save();
DatabaseReference ref = FirebaseDatabase.instance.reference();
var data = {
"id": user.uid,
"name": name,
"number": number,
"address": address,
"location":location,
"website":website,
};
ref.child('node-name').child(user.uid).set(data).then((v) {
_key.currentState.reset();
});
} else {
setState(() {
_autovalidate = true;
});
}
}

I made database structure in Firestore like this: I have two collections: 1)students 2)schools. I can not get array from my database

I have two collections in my Firestore database.
From first collection('schools'), I need to get current user school. I did it and it is Ok. But I also need to use this school and get array of his school's available courses.
This array is situated in collection('students'). And as document I use schoolNameString which I took in previous collection. So in document(schoolNameString).data['available'], available is array of swings and I need
setState(){
myarrayvar = document(schoolNameString).data['available']
}
I can not do that and always see
error /flutter (25070): Tried calling: []("available")
This is my code:
class _Coirses_PageState extends State<Coirses_Page> with TickerProviderStateMixin
{
final _firesore = Firestore.instance;
String appBarName;
String studentSchoolString = 'mal';
String aseetRoadforCorcs;
List availableCorsces = [];
#override
void initState() {
FirebaseUser user;
super.initState();
getCurrentUser();
getCouses();
try {
var studentSchool = _firesore.collection('schools');
var docSchool = studentSchool.document(loggedInUser.uid);
docSchool.get().then((documents) {
setState(() {
studentSchoolString = documents.data['schoolName'];
print(studentSchoolString);
});
print(studentSchoolString);
});
} catch (e) {
print(e);
}
tabs = [
Tab(text: 'Barlyǵy',),
Tab(text: 'Oqyp jatyrmyn',),
Tab(text: 'Aıaqtadym',)
];
pages = [Progress_Bar()];
_controller = TabController(length: tabs.length, vsync: this);
}
Future<List<dynamic>> getCouses() async {
var document = Firestore.instance.collection("students").document(studentSchoolString). get();
return await document.then((doc) {
setState(() {
availableCorsces = doc.data['available'];
});
print('dsasdasdjnasndklasndasdkasld' + doc.data['available']);
return availableCorsces;
});
}
void getCurrentUser() async {
try {
final user = await _auth.currentUser();
if (user != null) {
loggedInUser = user;
print(loggedInUser.email);
}
} catch (e) {
print(e);
}
}
}
I expected that I can use it in my UI like Text: ('available[0]' ......)
But I can't.

Resources