I'm trying to use Dart's aync programming with mongo model
I'm looking at the source for DbCollection and it appears the DbCollection.find() returns a Stream
https://github.com/vadimtsushko/mongo_dart/blob/master/lib/src/database/dbcollection.dart
I want to turn a response into a List of Maps so im doing the following:
try {
finder = await collection.find(query);
} catch(e) {
print(e);
}
try {
list = await finder.toList();
} catch(e) {
print(e);
}
Problem:
1. Execution bombs out out collection.find
2. No error is trapped
Question: Is there a different approach to working with this api the i need to be using?
Take a look at package readme. There are some examples.
Something like this should do:
var collection = db.collection('user');
await collection.find(where.lt("age", 18)).toList();
But actually even with superfluos await it should work too.
I've made a simple example with your snippet and it work for me as is
import 'package:mongo_dart/mongo_dart.dart';
main() async {
Db db = new Db('mongodb://127.0.0.1:27017/mongo_dart-test','sample_test');
DbCollection newColl;
await db.open();
newColl = db.collection("new_collecion");
await newColl.remove();
await newColl.insertAll([{"a":1}]);
var finder;
try {
finder = await newColl.find();
} catch(e) {
print(e);
}
List list;
try {
list = await finder.toList();
} catch(e) {
print(e);
}
print(list);
await db.close();
}
Related
Whenever I try to check for a folder's existence, it appropriately does but whenever I try to change the directory, it does not work. This is the code and it only prints the first 'exists' and not the second even though the directory /ultimate/mods does exist on the remote device. The remote device does not need a password(set to anonymous mode) so I don't think that permissions are an issue. If anyone can help it would be greatly appreciated.
import 'package:ftpconnect/ftpconnect.dart';
void main() async {
final FTPConnect _ftpConnect = FTPConnect(
"10.0.0.6",
user: "guiege",
port: 5000,
);
Future<void> _log(String log) async {
print(log);
await Future.delayed(Duration(seconds: 1));
}
Future<void> _uploadStepByStep() async {
try {
await _ftpConnect.connect();
if(await _ftpConnect.checkFolderExistence('ultimate'))
{
await _log('exists');
_ftpConnect.changeDirectory('ultimate');
if(await _ftpConnect.checkFolderExistence('mods'))
{
await _log('exists2');
}
}
await _ftpConnect.disconnect();
} catch (e) {
await _log('Error: ${e.toString()}');
}
}
Im having issues with my code and since I'm new at using Flutter, I have no clue on how to fix it. I was trying to fix the http.get(string) and I kind of did, but now I'm having issues with then(()).
void submitForm(FeedbackForm feedbackForm) async {
try {
await http.get(Uri.parse(URL + feedbackForm.toParams()).then((response)) {
callback(convert.jsonDecode(response.body['status']));
});
} catch (e) {
print(e);
}
}
}
It seems you got a parenthesis missplaced:
await http.get(...).then((response) => callback(...))
The them allows you to use the result of the previous Future, as soon as it becomes available. If you find it confusing you can declare one variable at a time.
final response = await http.get(...);
// Check if response was as expected
await callback();
I am using a mongodb database with backend based on NodeJS. I am calling one api to show a list of task (custom class) in front end and calling another API to delete a task. I want to read the list of task again when a task is deleted. How do I do that?
Function to get a list of tasks
Future<List<Task>> listOfTask() async {
List<Task> result;
try {
final response = await http.get('api link');
if (response.statusCode == 200) {
List<Task> taskList = response.body.map<Task>((entry) {
return Task.fromJson(entry);
}).toList();
result = taskList;
}
} catch (e) {
print(e.toString());
}
return result;
}
Getting the list of tasks in initState
#override
void initState() {
DatabaseServices().listOfTask().then((value) {
setState(() {listOfTask = value;});
});
super.initState();
}
Function to delete task
Future<http.Response> taskDelete(task) async {
try {
final response = await http.delete('api link');
return response;
} catch (e) {
print("Error: " + e.toString());
return null;
}
}
Deleting task from frontend
onPressed: () async {
dynamic result = await DatabaseServices(token: token).taskDelete(task);
},
How do I make sure the list of task is updated once I click delete. (Note: the Function to get task list and delete works)
I need to read and write files on Flutter.
Write works, but read not or I think it doesn't because the terminal output is flutter: Instance of 'Future<String>'.
What does it means?
This is the code :
Future<String> get _localPath async {
final directory = await getApplicationDocumentsDirectory();
return directory.path;
}
Future<File> get _localFile async {
final path = await _localPath;
return File('$path/hello.txt');
}
Future<File> writeHello() async {
final file = await _localFile;
// Write the file.
return file.writeAsString('HelloWorld');
}
Future<String> readHello() async {
try {
final file = await _localFile;
// Read the file.
return await file.readAsString();
} catch (e) {
// If encountering an error, return 0.
return "Can't read";
}
}
.
.
.
writeHello();
print(readHello());
Future<String> is of type Future hence you need to resolve the future, You can either await before printing or use .then() to resolve the Future.
Using await
String data = await readHello();
print(data);
Using .then()
readHello().then((data){ //resolve the future and then print data
print(data);
});
Note: There is no need to add extra "await" here on line 2 as you already are awaiting at line 1:
Future<String> readHello() async {
try {
final file = await _localFile; //Line 1
// Read the file.
return await file.readAsString(); //Line 2
} catch (e) {
// If encountering an error, return 0.
return "Can't read";
}
}
Now I got it, I understood what you said me thank you!
I created a new function that mix write and read.
The problem is that I called async functions in my program body where I can't use await , I should call them in other async functions to handle them in the right way.
I solved with this :
void _RWHello(String text) async {
writeHello();
print(await readHello());
}
.
.
.
_RWHello("HelloWorld");
Protractor click if displayed is not working using async await. I have tried with the following method:
public static async clickIfDisplayed(targetElement: ElementFinder) {
if (await targetElement.isPresent() && await targetElement.isDisplayed()) {
await PageHelper.click(targetElement);
}
}
The above sometime clicks even if element is not present or displayed. Please help to understand where I am going wrong here.
The following worked well with async-await:
public static async clickIfDisplayed(targetElement: ElementFinder) {
const isPresent = await targetElement.isPresent();
if (isPresent) {
const isDisplayed = await targetElement.isDisplayed();
if (isDisplayed) {
await PageHelper.click(targetElement);
}
}
}
public static async clickIfDisplayed(targetElement: ElementFinder) {
await targetElement.isPresent().then(bool1 => {
await targetElement.isDisplayed().then (bool2 => {
if (bool1 && bool2) {
await PageHelper.click(targetElement);
}
});
}
}
Does this work?