how to input text parameter to GET api with space - flutter

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

Related

Not able to receive value in response in flutter to cashfree API

I'm trying to receive response order_token from test API https://sandbox.cashfree.com/pg/orders which is used to create session of a payment gateway. Here is the code.
CFEnvironment environment = CFEnvironment.SANDBOX;
Future<dynamic> createOrder() async {
var response = await http.post(
Uri.https('https://sandbox.cashfree.com/pg/orders'),
headers: {
'Content-Type': 'application/json',
'x-client-id': 'your x-client-id',
'x-client-secret': 'your x-client-secret',
'x-api-version': '2022-01-01',
'x-request-id': 'developer_name',
},
body: jsonEncode(
{
"order_id": widget.cartId,
"order_amount": widget.grandTotal,
"order_currency": "INR",
"order_note": "Additional order info",
"customer_details": {
"customer_id": widget.address.id,
"customer_name": "name",
"customer_email": widget.email,
"customer_phone": widget.address.phone,
}
},
),
);
if (response.statusCode == 200) {
if (jsonDecode(response.body)['status'] == 'OK') {
debugPrint(jsonDecode(response.body)['order_id']);
debugPrint('log');
Logger.i(response.body);
return jsonDecode(response.body)['order_id'];
}
}
return '';
}
createSession() {
createOrder().then((value) {
try {
var session = CFSessionBuilder()
.setEnvironment(environment)
.setOrderId(widget.cartId!)
.setOrderToken(value)
.build();
return session;
} on CFException catch (e) {
debugPrint(e.message);
}
});
return null;
}
But the response seems to null and payment gateway doesn't open. What might be going wrong with my code? I tried printing response but there in null value there,What might be going wrong? How do I get a response? I've done this in postman I get a response.
replace header placeholders with actual values like your x-client-secret and others
Try this
var decodedResponse = jsonDecode(utf8.decode(response.bodyBytes)) as Map;
orderId = decodedResponse["order_id"] as String;
orderToken = decodedResponse["order_token"] as String;
Once the order is created and session is created, there are further steps, then only the checkout page will open. Refer this example - https://pub.dev/packages/flutter_cashfree_pg_sdk/example
Note :- Ideally, you shouldn't be creating order from app level. It should be done from your backend (Move the order creation to your backend).

getting null input in widget,data

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.

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

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