Flutter - How to retrieve data from firebase and save in sharedpreference - firebase

I'm trying to retrieve user name, photourl and email from user and save this info to shared preferences.
What I tried so far:
Future<bool> _saveNameAndEmailPreference(String name, String email) async {
final pref = await SharedPreferences.getInstance();
await pref.setString('name', name);
await pref.setString('email', email);
return pref.commit();
}
Firebase
DatabaseReference reference =
FirebaseDatabase.instance.reference().child("users").child(uid);
reference.once().then((DataSnapshot dataSnapShot) {
var keys = dataSnapShot.value.keys;
var values = dataSnapShot.value;
for (var key in keys) {
Users userinformation = new Users(
values[key]["name"],
values[key]["email"],
values[key]["photourl"],
);
userinformationList.add(userinformation);
}
setState(() {
nametxt = userinformationList[0].name;
emailtxt = userinformationList[1].email;
_saveNameAndEmailPreference(nametxt, emailtxt);
});
});

Related

how can I get access to a document in 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.

Import csv to sqlite in Flutter (insert issue)

I've already read the related article and solution + mentioned method, but still I don't get it what should I add to my code for importing csv to sqlite table List<<Map<String, dynamic>. I need to replace existing table with a new one and insert each lines of converted csv. How can I solve it? Here's my code below.The problem is importVoca() of db.dart.
db.dart
class DBHelper {
var _db;
// create database
Future<Database> get database async {
if (_db != null) return _db;
_db = openDatabase(
join(await getDatabasesPath(), 'vocas.db'),
onCreate: (db, version) {
return db.execute(
"CREATE TABLE vocas(id TEXT PRIMARY KEY, word TEXT, meaning TEXT, createTime TEXT)",
);
},
version: 1,
);
return _db;
}
// insert voca
Future<void> insertVoca(Voca voca) async {
final db = await database;
await db.insert('vocas', voca.toMap(),
conflictAlgorithm: ConflictAlgorithm.replace);
}
// Voca list
Future<List<Voca>> vocas() async {
final db = await database;
final List<Map<String, dynamic>> maps = await db.query('vocas');
return List.generate(maps.length, (i) {
return Voca(
id: maps[i]['id'],
word: maps[i]['word'],
meaning: maps[i]['meaning'],
createTime: maps[i]['createTime']);
});
}
//update voca list
Future<void> updateVoca(Voca voca) async {
final db = await database;
await db.update(
'vocas',
voca.toMap(),
where: "id = ?",
whereArgs: [voca.id],
);
}
//delete voca
Future<void> deleteVoca(String id) async {
final db = await database;
await db.delete(
'vocas',
where: "id = ?",
whereArgs: [id],
);
}
//find voca to edit
Future<List<Voca>> findVoca(String id) async {
final db = await database;
final List<Map<String, dynamic>> maps =
await db.query('vocas', where: 'id = ?', whereArgs: [id]);
return List.generate(maps.length, (i) {
return Voca(
id: maps[i]['id'],
word: maps[i]['word'],
meaning: maps[i]['meaning'],
createTime: maps[i]['createTime'],
);
});
}
//export voca to csv
Future exportVoca() async {
var year = DateFormat('yy').format(DateTime.now());
var month = DateFormat('MM').format(DateTime.now());
var day = DateFormat('d').format(DateTime.now());
final db = await database;
var result = await db.query('vocas');
var csv = mapListToCsv(result);
final directory = await getApplicationDocumentsDirectory();
final pathOfFile = await directory.path;
File file = File("$pathOfFile/dontForget_$year$month$day.csv");
file.writeAsString(csv);
}
//import csv to sqlite
Future importVoca() async {
File file = await FilePicker.getFile(
type: FileType.custom, allowedExtensions: ['csv']);
final data = file.openRead();
final fields = await data
.transform(utf8.decoder)
.transform(new CsvToListConverter())
.toList();
Database _db = await openDatabase(
join(await getDatabasesPath(), 'vocas.db'),
version: 1, onCreate: (Database db, int version) async {
await db.execute("DROP TABLE IF EXISTS vocas");
await db.execute(
"CREATE TABLE vocas(id TEXT PRIMARY KEY, word TEXT, meaning TEXT, createTime TEXT)");
});
}
}

Flutter platform error when querying for data

Can I know how can I resolve this issue?
Flutter - PlatformException : error, Invalid document reference. Document references must have an even number of segments, but users has 1, null
The following is my code to query the name of my user.
class Auth {
FirebaseUser mCurrentUser;
FirebaseAuth auth;
final firestoreInstance = Firestore.instance;
String name = '';
String uid = "";
void getCurrentUser () async {
mCurrentUser = await auth.currentUser();
uid = mCurrentUser.uid;
print(uid);
}
void getName1() async {
if(uid != null){
DocumentSnapshot document = await Firestore.instance.collection('User').document(uid).get();
name = document.data['Name'];
}
}
Try the following:
void getName1() async {
FirebaseUser mCurrentUser = await auth.currentUser();
DocumentSnapshot document = await Firestore.instance.collection('User').document(mCurrentUser.uid).get();
name = document.data['Name'];
}
Create a local variable, and retrieve the current useruid inside the method getName1()

I want to fetch current user data from firebase database in my flutter application

My Question is that i want to fetch data of the current user only. but this code below is fetching data of all the users present in my Database. how can i fetch the data of only and only current user.
This is the code with which i am fetching data from firebase(I am using Realtime DataBase).
in this 'node-name' is the field under which my data is being stored.
class ShowDataPage extends StatefulWidget {
#override
_ShowDataPageState createState() => _ShowDataPageState();
}
class _ShowDataPageState extends State<ShowDataPage> {
List<myData> allData = [];
#override
void initState() {
DatabaseReference ref = FirebaseDatabase.instance.reference();
ref.child('node-name').once().then((DataSnapshot snap) {
var keys = snap.value.keys;
var data = snap.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}');
});
});
}
This is the code from which i am uploading my data to the firebase under the name of 'node-name'. this code is stored in another file and is having another necessary fields also but this is the field which uploads my data to the firebase.
_sendToServer() {
if (_key.currentState.validate()) {
_key.currentState.save();
DatabaseReference ref = FirebaseDatabase.instance.reference();
var data = {
"name": name,
"profession": profession,
"message": message,
};
ref.child('node-name').push().set(data).then((v) {
_key.currentState.reset();
});
} else {
setState(() {
_autovalidate = true;
});
}
}
My data base in firebase looks like given below.
Use the user uid:
ref.child('node-name').child("M5CCSXQo3Upq5OC7y3lw").once()
.then((DataSnapshot snap) {...}
If you don't know the uid and didn't use it, then perform a query by the name fore example.
#override
void initState() {
FirebaseAuth.instance.currentUser().then((user){
fetchUser(user);
});
}
fetchUser(FirebaseUser user)
{
DatabaseReference ref = FirebaseDatabase.instance.reference();
ref.child('node-name').child(user.uid).once().then((DataSnapshot snap) {
var keys = snap.value.keys;
var data = snap.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}');
});
});
}
you can use like this
...
ref.child('node-name').child('/** current_user_key **/').once()
...

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;
});
}
}

Resources