getting null input in widget,data - flutter

I have an issue while writing my code
in the main page of my app i'm requesting a get from my json file and receiving a list of users + their info and when tapped on each of these users a new page opens up with some additional information.
in the 2nd page i make a new get request and this is where the problem happens and I get this error:
The following NoSuchMethodError was thrown building FutureBuilder(dirty, state: _FutureBuilderState get http
and my widget.data. returns as null
some help would be appreciated.
try {
String url =
'http://10.0.0.21:8000/api/users/' + widget.employee.id.toString();
individualData = await http.get(Uri.parse(url));
var test = individualData;
} catch (e) {
print(e.toString());
}

i forgot to put an if else to check if data exists

String? employeeId = widget.employee.id;
if(employeeId!=null){
try {
String url =
'http://10.0.0.21:8000/api/users/' + employeeId;
individualData = await http.get(Uri.parse(url));
var test = individualData;
} catch (e) {
print(e.toString());
}
}else{
print('Getting employeeId as null');
}
So first check employeeId is not getting a null and then call a API.

Related

Need to parallelise async operation using stream in dart

Problem: I am building an application on an RSS feed reader.
In a feed:
There are various items and each item is an article which has a URL.
Each URL has open graph metadata which needs to be fetched and takes time.
As soon as URL open graphs metadata is loaded it needs to be shown in the list on the UI.
Now I want to run 2 and 3 in parallel, am doing this in the code for now:
Stream<News> _getNewsRssFeed(Categories selectedCategory) async* {
try {
final rssUrl = _getRssUrl(selectedCategory);
RssFeed feed = await _getRssFeed(rssUrl);
if (feed.items != null) {
for (int itemIndex = 0; itemIndex < feed.items!.length; itemIndex++) {
final item = feed.items![itemIndex];
try {
Future<News> news = _processRssFeedItem(item, feed);
news.then((value){
yield value; // This is not working
});
} catch (error) {
print("Error while parsing ${item.link} error = $error");
}
}
}
} catch (error) {
print("Error while parsing RssFeed url $error");
}
}
The problematic line I have commented in above code, can you please let me know what is the best way here?
Basically, news.then returns Future and you are not awaiting for the result to be available.
You can change it by changing code to following
try {
final value = await _processRssFeedItem(item, feed);
yield value;
} catch (error) {
print("Error while parsing ${item.link} error = $error");
}

how to input text parameter to GET api with space

I have an http service to GET movies api data it works fine but if i input 2 words for example
"The Batman" it's not working because it will return null but if i only input 1 word "Batman" it works fine, im still new with query query things
if you have the answer can you please answer with my full code ? because im quite slow to understand some logic
here is my code
Future searchMovie(movieName) async {
Uri url = Uri.parse('https://api.themoviedb.org/3/search/movie?api_key={key}&query=$movieName');
var response = await http.get(url);
if (response.statusCode == 200) {
List data = jsonDecode(response.body)['results'];
List<SearchMovieModel> searchedMovies = [];
for (var item in data) {
searchedMovies.add(SearchMovieModel.fromJson(item));
}
return searchedMovies;
} else {
throw Exception('Error get data');
}
}
you can try this way.
String query ='The Batman';
await get(Uri.parse('https://api.themoviedb.org/3/search/movie').replace(
queryParameters: {
'api_key' :'key',
'query' : query
}
));

How can apply optimization for optimize route while launch google map url?

I want to redirect to device default google map app. So i am calling bellow url using some parameters but optimization parameter not working. So, any one have idea how apply optimization true or false while launch google map url.
This is Output Url.
String mapOptions = [
'origin=${widget.currentLocation.latitude.toString()}%2C${widget.currentLocation.longitude.toString()}',
'destination=${(destinationAddress.replaceAll(',', '%2C')).replaceAll(' ', '%20')}',
'destination_place_id=${widget.routeDeliveryDetail.deliveryList[widget.routeDeliveryDetail.deliveryList.length - 1].placeId}',
'waypoints=$wayPoint',
'waypoint_place_ids=$wayPointPLaceId',
'optimization=true',
'travelmode=driving'
].join('&');
String googleUrl = 'https://www.google.com/maps/dir/?api=1&$mapOptions';
print(googleUrl);
try {
if (await canLaunch(googleUrl)) {
await launch(googleUrl);
} else {
throw 'Could not open the map.';
}
} catch (e) {
print(e);
}
You have to pass "optimize:true" as the first argument within the waypoints parameter to allow the Directions service to optimize the provided route by rearranging the waypoints in a more efficient order.
String mapOptions = [
'origin=${widget.currentLocation.latitude.toString()}%2C${widget.currentLocation.longitude.toString()}',
'destination=${(destinationAddress.replaceAll(',', '%2C')).replaceAll(' ', '%20')}',
'destination_place_id=${widget.routeDeliveryDetail.deliveryList[widget.routeDeliveryDetail.deliveryList.length - 1].placeId}',
'waypoints=$wayPoint',
'waypoint_place_ids=optimize:true|$wayPointPLaceId',
'travelmode=driving'
].join('&');
String googleUrl = 'https://www.google.com/maps/dir/?api=1&$mapOptions';
print(googleUrl);
try {
if (await canLaunch(googleUrl)) {
await launch(googleUrl);
} else {
throw 'Could not open the map.';
}
} catch (e) {
print(e);
}

Post Api not return any response in nest js

I use nestjs and psql and I want upload files and save the url in the database . when I run the api , data save on db but it doesn’t return any response .
this is my service:
async uploadFiles(files){
if (!files) {
throw new HttpException(
{
errorCode: UploadApplyOppErrorEnum.FileIsNotValid,
message: UploadApplyOppMsgEnum.FileIsNotValid,
},
HttpStatus.UNPROCESSABLE_ENTITY,
);
}
const filedata = OrderFilesData(files);
return filedata.map(async(filePath) => {
let orderFile = new OrderFile();
orderFile.fileUrl = filePath.fileUrl;
orderFile.type = filePath.fileType;
try {
let result = await this.orderFileRepository.save(orderFile);
return await result
} catch (error) {
throw new BadRequestException(error.detail);
}
});
}
and this is my controller
#UploadOrderFilesDec()
#Post('upload')
uploadFiles(#UploadedFiles() files){
return this.ordersService.uploadFiles(files);
}
You can't return an array of async methods without using Promise.all(), otherwise the promises haven't resolved yet. You can either use return Promise.all(fileData.map(asyncFileMappingFunction)) or you can use a regular for loop and await over the results.

Having trouble saving document to mongoDB

so I'm having a really hard time getting the document to save to the database in the case where the product already exists in the cart. I am able to target the item from the database, make changes to it and console output the correct values but in this particular case it wont save the result to the Database. I've tried rewriting it using the updateOne() function and I had little luck. I could really use the help i'm super stuck on this probem. Pics for more info: Block of code that's not working, console output that reflects desired change, mongoDB document that the changes will not save to.
If anyone could point me in the right direction I would greatly appreciate it.
router.post('/add-to-cart',[
auth,
check('productId','productId is required').not().isEmpty(),
check('quantity', 'quantity is required').not().isEmpty()
] , async (req,res) => {
//checks field validation
const errors = validationResult(req);
if(!errors.isEmpty()){
res.status(400).json({errors:errors.array()});
};
//Takes token from the header
const token = req.header('x-auth-token');
if (!token){
return res.status(401).json({ msg: 'no token, auth denied'});
}
//decode token and find associated user
const decoded = jwt.verify(token, config.get('jwtSecret'));
let userPayload = decoded.user;
//build cart object
try{
//populate from request body
const {productId, quantity} = req.body;
//find User using the payload
let user = await User.findById(userPayload.id);
//get the product from db
let product = await Product.findById(productId);
//calculate price of item(s) added to cart
let total = ( quantity * product.price);
//create cart object
//Check to see if cart already exists
let iscart = await Cart.findOne({user:user});
//there is an existing cart
*if(iscart){
let found = false;
for (i=0;i<iscart.orderItems.length;i++)
{
if(iscart.orderItems[i].product._id.toString() == product._id.toString()){
found=true;
console.log('found that product!');
iscart.orderItems[i].qty += quantity;
try{
await iscart.save();
console.log(iscart);
}
catch(err){
console.error(err);
res.status(500).send('server error');
}
res.status(200).send(iscart.orderItems[i]);
break;
}*
}
if(!found){
await Cart.updateOne(
{user:iscart.user},
{$push:{orderItems:
{
product:product,
qty:quantity,
total:total
}}
}
)
res.status(200).send('product pushed to orderItems')
}
}
//there isnt an existing cart so we create one
else{
const cart = new Cart({
user,
orderItems:
{ product:product,
qty:quantity,
total:total
}
})
await cart.save();
res.status(200).send('cart created and saved');
}
}
catch(err){
console.error(err);
res.status(500).send('server error');
}
})
Figured it out!! When you are updating a nested object inside of a document you have to mark the object as modified so it knows to update it. this line fixed my issue:
iscart.markModified('orderItems');