I am creating a language app and the class material is stored in a CSV. So far I can read a specific cell from the CSV but I don't know how to update a specific cell and I can't find anything online on how to accomplish that. How can I code that?
I am using the csv package from pub.dev. This is how I am reading from the csv:
readCSV(row, col) async {
var csvFILE = await rootBundle.loadString("assets/class01.csv");
List<List<dynamic>> csvDATA = CsvToListConverter().convert(csvFILE);
setState(() {
displayText = csvDATA[row][col];
});
}
Related
I have a collection called Orders. This collection stores various orders. Each document has a field stockQuantity. Every day when new stock is added, it is added to this field (which is a map) alongside the date. Now I want to be able to list all the last values of the stock added for each order i.e. the stock added on the latest date. This is me trying to achieve this. I am getting an error error: The operator '[]' isn't defined for the type 'Object'. (line 40).
Also I am not sure if this will work.
class StockService {
static Future<List<in
t>> getLatestStockQuantity() async {
List<int> latestStockedQuantityList = [];
QuerySnapshot snapshot = await FirebaseFirestore.instance.collection(
'orders').get();
for (var doc in snapshot.docs) {
Map<String, dynamic> stockedQuantityMap = doc.data()!['stockQuantity'];
if (stockedQuantityMap != null) {
int latestStockedQuantity = stockedQuantityMap.values
.last['stockedThisDay'];
latestStockedQuantityList.add(latestStockedQuantity);
}
}
return latestStockedQuantityList;
}
}
on another page I am using a ListView.builder to display the data
I have tried troubleshooting by looking at other posts on stack, etc. still no luck.
Hi I am pretty new to Firebase real time database and this is my first project. Sorry if this is a stupid question.
I am saving my data as follows.
firebase database structure:
Now I want to retrieve all parent chat ids on which the student is participating, using the student_id variable.
I tried as per this SO question and this structure database and retrieve data documentation, but its not retrieving values. Anybody have an idea?
I would suggest saving the chatroom IDs your students are in in a separate location. For example:
Path:
“/users/$uid/chatrooms”
Data:
{
0: 350,
1: 423
}
Thus you could retrieve the chat room ids first before getting the chatroom data.
import { initializeApp } from “firebase”;
import { getDatabase, get, set, ref } from “firebase/database”;
const userChatroomIdsRef = ref(db, ‘/users/${uid}/chatrooms‘);
get(userChatroomIdsRef).then(result => {
const chatroomIds = result.val();
if (!(chatroomIds && chatroomIds instanceof Array)) return; // firebase will return null if its an empty array.
const getChatroomInfoPromises = chatroomIds.map(id => get(ref(db, ‘/chat/${id}/${uid}’)).then(result => result.val());
Promise.all(getChatroomInfoPromises).then(chatroomInfoArray => { YOUR LOGIC HERE });
});
Removing/adding students from/to chatrooms would now be simple as you could just change the array of chatroomIds.
const userChatroomIdsRef = ref(db, ‘/users/${uid}/chatrooms‘);
get(userChatroomIdsRef).then(result => {
const oldIds = result.val();
const newChatroomIds = oldIds.filter(id => id !== ID TO DELETE);
return set(userChatroomIdsRef, newChatroomIds)
});
This is of course assuming that you know the uid of your student_id. If you do not know what uid each student_id has, you must must store a reference. I would suggest saving all student info in the “/users/$uid/” directory. Here you could save the studentId so you can programmatically use it.
In all other firebase logic I would try to use the native firebase uid for querying. This will make your life easier.
It’s always good the keep information organized on the database so your logic is simple.
Please check my code for syntax errors; I wrote this on an iPhone.
I wanna use open-weather API for my application. for that i thought i might be able to save cities and their IDs in my own app in a json file and whenever i user wants a locations weather, app selects city's ID from json and make API call.
for that i downloaded a 30MB Json file provided by Openweather, it contains all countries and all theirs cities. putting a 30MB in my app isn't a good idea apparently. so i decided to extract my country cities only. but the point is, this idea could not be done. so many cities from different countries has same names. and extracted json was huge again. even some coutry codes are cities in other countries.
i wonder if there is a way better implementation. or any idea or way to extract just cities of a country.
any help to implement weather call in my app for different cities would be appreciated
I know this question is old but I recently bumped into this problem too. The way I ended up doing it was making city.list.json in to a default exported JSON object and writing a node script to then strip cities out by country code:
var fs = require('fs');
var cityList = require('./city.list.js');
let output = {};
let countryCodes = [];
cityList.forEach((city) => {
const country = city.country;
if (country) {
if (!countryCodes.includes(country)) {
countryCodes.push(country);
}
if (!output[country]) {
output[country] = [];
}
output[country].push({
id: city.id,
name: city.name,
});
}
});
for (const [key, value] of Object.entries(output)) {
const fileName = 'city.' + key.toLowerCase() + '.json';
fs.writeFile(fileName, JSON.stringify(value), function (err) {
if (err) console.error(err.message);
console.log(fileName + ' - saved!');
});
}
fs.writeFile('countrycodes.json', JSON.stringify(countryCodes), function (err) {
if (err) console.error(err.message);
console.log('countrycodes.json' + ' - saved!');
});
This totally worked! Only problem I then ran into is city.list.json includes country names, and they are not differentiated in the data...
I want to save an image inside the sqflite database and the later on, I want to display it in a SliverAppBar as a background. Till now I am able to save the image(not sure if it is right, but throws no error XD):
Directory directory = await getApplicationDocumentsDirectory();
String path = directory.path;
File newImage = await _image.copy('$path/${recipeName.text}.png'); //_image already taken with image_picker plugin
String base64Encoded = base64Encode(newImage.readAsBytesSync());
And this String I am saving inside the database. But I also want to display. And as far I know, I have to get the String, but from now I on, I do not know anything how to get further. I have written a function to get the String, but do not know what I should do with this String. The function looks like this:
Future fetchRecipe(String name) async{
var dbHelper = new DBHelper();
Future<List<Recipes>> recipes = dbHelper.getSpecRecipe(name);
return recipes;
}
The getSpecRecipe(name) points to this function:
Future<List<Recipes>> getSpecRecipe(String recipeName) async{
List<Map> list = await _db.rawQuery("SELECT * FROM recipes WHERE name = ?", [recipeName]);
List<Recipes> recipes = new List();
for(int i =0; i < list.length; i++){
recipes.add(new Recipes(list[i]["id"], list[i]["name"], list[i]["definition"], list[i]["duration"], list[i]["favorite"], list[i]["timestamp"], list[i]["image"], list[i]["backgroundColor"]));
}
return recipes;
}
It would be awesome, if somebody would be able to solve my problem. Thanks in advanceXD
From the snippets provided, it seems that you're trying to save the image as a base64 on your database. And as mentioned by #Nordeast in the comments, it's better to save the image on the device's storage and store the file path instead. Also, given the snippets provided, it's difficult to replicate the behavior locally.
Given the data structure below in firebase, i want to run a query to retrieve the blog 'efg'. I don't know the user id at this point.
{Users :
"1234567": {
name: 'Bob',
blogs: {
'abc':{..},
'zyx':{..}
}
},
"7654321": {
name: 'Frank',
blogs: {
'efg':{..},
'hij':{..}
}
}
}
The Firebase API only allows you to filter children one level deep (or with a known path) with its orderByChild and equalTo methods.
So without modifying/expanding your current data structure that just leaves the option to retrieve all data and filter it client-side:
var ref = firebase.database().ref('Users');
ref.once('value', function(snapshot) {
snapshot.forEach(function(userSnapshot) {
var blogs = userSnapshot.val().blogs;
var daBlog = blogs['efg'];
});
});
This is of course highly inefficient and won't scale when you have a non-trivial number of users/blogs.
So the common solution to that is to a so-called index to your tree that maps the key that you are looking for to the path where it resides:
{Blogs:
"abc": "1234567",
"zyx": "1234567",
"efg": "7654321",
"hij": "7654321"
}
Then you can quickly access the blog using:
var ref = firebase.database().ref();
ref.child('Blogs/efg').once('value', function(snapshot) {
var user = snapshot.val();
ref.child('Blogs/'+user+'/blogs').once('value', function(blogSnapshot) {
var daBlog = blogSnapshot.val();
});
});
You might also want to reconsider if you can restructure your data to better fit your use-case and Firebase's limitations. They have some good documentation on structuring your data, but the most important one for people new to NoSQL/hierarchical databases seems to be "avoid building nests".
Also see my answer on Firebase query if child of child contains a value for a good example. I'd also recommend reading about many-to-many relationships in Firebase, and this article on general NoSQL data modeling.
Given your current data structure you can retrieve the User that contains the blog post you are looking for.
const db = firebase.database()
const usersRef = db.ref('users')
const query = usersRef.orderByChild('blogs/efg').limitToLast(1)
query.once('value').then((ss) => {
console.log(ss.val()) //=> { '7654321': { blogs: {...}}}
})
You need to use limitToLast since Objects are sorted last when using orderByChild docs.
It's actually super easy - just use foreslash:
db.ref('Users').child("userid/name")
db.ref('Users').child("userid/blogs")
db.ref('Users').child("userid/blogs/abc")
No need of loops or anything more.