I am wondering if there are faster ways of doing this fetch, the for loop currently takes approx 10s but it's waiting for each fetch to finish before starting on the next one I also tried a forEach loop but then I had issues with the responses array being empty. Is there any smart Dart way of fetching it faster then returning the array to flamingotest
Here is my code!
import 'package:http/http.dart' as http;
import 'dart:convert';
import '../classes/flamingo_test.dart';
import '../classes/convert_wallet.dart' as walletfunc;
import 'package:flutter_settings_screens/flutter_settings_screens.dart';
import '../utilities/assets.dart' as assets; // Object of assets
Future<FlamingoTest> fetchPost() async {
String apiUrl = "xxxxxx";
var responses = [];
for (var mapEntry in assets.assets.entries) {
var wallet = Settings.getValue<String>("user-wallet", "");
print(wallet);
var userWalletSeed = walletfunc.convertWallet(wallet);
print(userWalletSeed);
var body = json.encode({
"jsonrpc": "2.0",
"method": "invokefunction",
"params": [
"4d92194e8d73980dadbadfc1993b2014c9fbd9da",
"checkFLM",
[
{"type": "Hash160", "value": userWalletSeed},
{"type": "Hash160", "value": mapEntry.value}
]
],
"id": 3
});
Map<String, String> headers = {
'Content-type': 'application/json',
'Accept': 'application/json',
};
var response =
await http.post(Uri.parse(apiUrl), body: body, headers: headers);
print(response);
if (response.statusCode == 200) {
print(response);
var uncoded = jsonDecode(response.body);
responses.add(uncoded);
} else {
throw Exception('Failed to load post');
}
}
return new FlamingoTest.fromJson(responses);
}
You can use Future.wait like this. The map will return a Iterable of Future<Response> and perform the post simultaneously.
Future<Response> fetchResponse(var mapEntryValue) async {
//The code in your for-loop goes here
...
return response;
}
Future<FlamingoTest> fetchPost() async {
var responses = [];
await Future.wait(
assets.assets.entries
.map<Future<Response>>(
(MapEntry me) => fetchResponse(me.value),
)
.toList(),
).then((listOfResponses) {
responses.addAll(listOfResponses);
});
return new FlamingoTest.fromJson(responses);
}
Related
while creating a flutter chatbot application using openAI (chatgpt) I couldn't able to send message and the response from the bot is null please anyone could help to get rid of this
Thanking You
My code
import 'dart:convert';
import 'package:http/http.dart' as http;
String apikey = "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";
class Apiservices {
static String baseurl = "https://openai.com/v1/completions";
static Map<String, String> header = {
'content-Type': 'application/json',
'Authorization': 'Bearer $apikey',
};
static sendMessage(String? message) async {
var res = await http.post(Uri.parse(baseurl),
headers: header,
body: jsonEncode({
"model": "text-davinci-003",
"prompt": '$message',
"temperature": 0,
"max_tokens": 100,
"top_p": 1,
"frequency_penalty": 0.0,
"presence_penalty": 0.0,
"stop": ["Human:", "AI:"]
}));
if (res.statusCode == 200) {
var data = jsonDecode(res.body.toString());
var msg = data['choices'][0]['text'];
return msg;
} else {
print("failed to fetch data");
}
}
}
The error which i am getting
I want to create a login method to post http request. I use the following code to post user data into the server and get a response:
import 'dart:convert';
import 'dart:html';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import '../Services/baseHttp.dart' as base;
class Services {
late var token = '';
Future<http.Response> login(String username, String password) async {
var url = base.BaseURL.loginUrl;
Map data = {"username": username, "password": password};
var body = json.encode(data);
var response = await http.post(Uri.parse(url),
headers: {
"Content-Type": "application/json",
"Accept": "application/json"
},
body: body);
print(response.statusCode);
token = response.body;
print(token);
return response;
}
}
I tried to use try catch inside the method:
Future<http.Response> login(String username, String password) async {
try {
var url = base.BaseURL.loginUrl;
Map data = {"username": username, "password": password};
var body = json.encode(data);
var response = await http.post(Uri.parse(url),
headers: {
"Content-Type": "application/json",
"Accept": "application/json"
},
body: body);
print(response.statusCode);
token = response.body;
print(token);
return response;
} catch (e) {
print(e);
}
}
I want to send statusCode instead of print(e) when any exception is thrown. How can I do that?
To check whether a response is valid, you can check the status code if it's equal to 200 like this:
if (response.statusCode == 200){
// Do something
} else {
// Throw exception
}
Taking a look the official documentation. You will see the following:
Future<Album> fetchAlbum() async {
final response = await http
.get(Uri.parse('https://jsonplaceholder.typicode.com/albums/1'));
if (response.statusCode == 200) {
// If the server did return a 200 OK response,
// then parse the JSON.
return Album.fromJson(jsonDecode(response.body));
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to load album');
}
}
I'm new to programming in general and very new to flutter, I get this following error message on both the "body" and "header" in the code which is marked in bold. I have tried everything I could find online for any help, but now found any solution, I figure this probobly isn't the hardest thing for someone who knows programming to solve, but I'm a beginner so I would really like the help. Thanks in advance.
import 'dart:convert';
import 'dart:async';
import 'package:http/http.dart' as http;
import 'model.dart';
const API_URL = 'https://todoapp-api-pyq5q.ondigitalocean.app';
const API_KEY = '7037674e-2262-4502-a2e1-29c940bd2a7a';
class Api {
static Future addTodoModel(TodoModel todo) async {
var json = todo.toJson();
var bodyString = jsonEncode(json);
var response = await http.post(Uri.parse('$API_URL/todos?key=$API_KEY',
**body: bodyString, headers:** {'Content-Type': 'application/json'}));
if (response.statusCode == 200) {
return response;
} else {
print('error on add');
return null;
}
}
static Future updateTodo(TodoModel todo, todoId) async {
var json = todo.toJson();
var bodyString = jsonEncode(json);
var response = await http.put(Uri.parse('$API_URL/todos/$todoId?key=$API_KEY',
**body: bodyString, headers:** {'Content-Type': 'application/json'}));
if (response.statusCode == 200) {
return response;
} else {
print('error on update');
return null;
}
}
static Future removeTodoModel(String todoId) async {
try {
var response = await http.delete(Uri.parse('$API_URL/todos/$todoId?key=$API_KEY'));
if (response.statusCode == 200) {
return response;
}
print('exception on remove');
} catch (exception) {
throw exception;
}
}
static Future<List<TodoModel>> getTodoModel() async {
try {
var response = await http.get(Uri.parse('$API_URL/todos?key=$API_KEY'));
var json = jsonDecode(response.body);
return json.map<TodoModel>((data) {
return TodoModel.fromJson(data);
}).toList();
} catch (exception) {
throw exception;
}
}
}
The Uri.parse funtion has no "header" or "body" parameter.
"headers" and "body" should be post method's params, like this:
Body and Headers are available in method of http.
For example:
import 'package:http/http.dart' as http;
// POST method
final response = await http.post(
url,
headers: {}, // Map<String*, String*>* headers
body: json.encode(params), // params is Map<String, dynamic>
);
The open api request I'm trying to use requires an image binary value with content-type of multipart/form-data format.
I know you can't use dart:io in flutter web. I tried to upload an image in multipart/form-data format to the api server in flutter web while looking at several posts.
However, only a message appeared stating that the image could not be recognized.
This is the last thing I tried to create multipart types in flutter web.
import 'package:dio/dio.dart';
import 'package:http/http.dart' as http;
import 'package:flutter/material.dart';
import 'package:file_picker/file_picker.dart';
PlatformFile? objFile;
pickImage() async {
var result = await FilePicker.platform.pickFiles(
withReadStream: true,
);
setState(() {
objFile = result!.files.single;
});
uploadImage();
}
uploadImage() async {
FormData formData = FormData.fromMap({'image' : MultipartFile(test!, objFile!.size, filename: objFile!.name)});
Dio dio = new Dio();
var response = await dio.post('API url', data: formData);
}
I additionally used Multipart.form Bytes from http , Multipart.form Bytes from dio . But the result was the same.
The value checked by the request body through the postman interceptor.
content-type=multipart/form-data;bounary=--dio-boundary-1105759322
----dio-boundary-1105759322
content-disposition: form-data; name="image"; filename="test.jpeg"
content-type: application/octet-stream
ÿØÿÛC
%# , #&')*)-0-(0%()(ÿÛC
(((((((((((((((((((((((((((((((((((((((((((((((((((ÿÀŽv"ÿÄÿÄC!1AQaq"‘2¡±#BÁÑR3CðñSbr’á‚Â$&4c“ÿÄÿÄ&!1A2Q"a3BRÿÚ?ù× „É<$/cŸt8D`aú¦Ä#bálŒZVM„ٔʓTL›eOò¢“
èKÇ(p¢‰¥C’ÄÙ‚Ñx²Ù1Jcœ)B›¢$ ¢‚&
‚7› ˜Žp”{&ÊÀÁAî¤Æ
‚nÈ CØÃêOýÒ›§á$sÊ‚r¡ìLÂ…;"éMI½î«gæV<æ6οÙ%_ƒY®}7Òû€¯MŒ&g¹å|µ£ëÐúc\tÚƵƈúÕ]#kQ‹D/Ÿú·cu9«Hà/¢lÚ–êè·¼&Þt
¯H‚&ɶìÛà®iƒh²SöãÔTs[l›/?[s(’˜¨o€¤Û‹*¥AÖ”ðbUgYR’!äJ!M‹™‹«›î©aÉ*ᕨ4p SÉ…¤)‰ì§=‘âJ» oÙGDRåÌy0—²û r ò€·²?Te8±KSTR8ŹDAååþ7)Oˆk)õ²Qk#Ù€Œ ?DÜû&Ä›„ÍÅ”lQjð¡NÑ%HTWP˜²wýÒc(Ÿð¤ð¢S<*6º>ÊaCœ „Ù0
^J(ª%¢ƒFPm‘^u4^èM‘åL…##•0Qÿ ºi…32§ÙC•D¿&Èw’ˆº‘Ü"…”<&ýРwP {p ¸DCd¼&ÿ©#¨ˆ› La~¨p¦„)’÷‚ˆº²æÒ›ªĘ̀Šaá€0‹n <ò¦M“YM„ L«=ÕnæÊlªŽÂƒóc„m‚—È™Uó ªºäªÛ•F†\…}7?¨ªZL`*£è¾ŽÝÌ1¤ÜBúk6
---------------------------SKIP------------------------------
PTiMÂ!¢(èÊ€YÊÂœ"ÑÂ_T<Ñ5îPp™ð ¨„ôOˤ?¢z\ÂÚ¡½ÐiÊc쨟ÝHŸ¢“3ÝA˜( ‘ÊH›(l€Å¼)Ä‘rEÈ[€‹¬”¼x
W7q?ΣHt®“§¤y\½Ìÿ:ÿÍtÖ§T°AÊÕ\ËZVƒÔPha30%1*¶›Ž!7è¥|f›„îÕQ±„9N6åW,¨^Ù8PHN./Ê€îª2ß*{(l¡™šOU¢Ôå3œ*ꜨŠ‹“3¼$«B*ÌŒS„+EÒ‘Ý VHpV±`²³ó€µgܪ‚#“Ü)À!NPCƒÝIÅԛ–”xý”²™# ?U‚‹n€å!Œ¦&é*ƒ™¨wÄÖØY¢>«}&ü¢×\Ý?ó*9ç%Òº˜#çò H€¥&ꃒ¤(
‚0O8##EÎéÊœ#TÕr‚ºT¹ÈÔ7T“2¢ƒœbÅsuOî¶Ô0>‹ŸT|Gô•Óa®ïšÔÇe¤T
he<,¨[ü¶[…·M#ZOˆjtˤÝE© QÿÙ
----dio-boundary-1105759322--
When I use the MultipartFile.fromFile method used in flutter ios, I got the response normally. So I'm pretty sure there must be some mistake or misinformation in the flutter web setup.
Thanks in advance!
this is how I managed to upload an image to Laravel backend using Flutter Web
import 'dart:io';
import 'package:dio/dio.dart' as dio;
import 'package:file_picker/file_picker.dart';
Future pickupUserImage2() async {
PlatformFile? objFile;
var picked = await FilePicker.platform.pickFiles();
objFile = picked!.files.single;
String? apiUrl = Get.find<MainController>().apiUrl;
String url = '';
if (apiUrl != null) url = apiUrl + 'images';
List<int> list;
list = List<int>.from(objFile.bytes!);
dio.FormData formData = dio.FormData.fromMap({'file': dio.MultipartFile.fromBytes(list, filename: objFile.name)});
DioNetworking _dio = new DioNetworking();
dynamic result = await _dio.postData(
url,
formData,
contentType: 'multipart/form-data',
);
if (result['status'] == true) {
showToast(result['message']);
return ImageModel.Image.fromJson(result['data']);
}
}
I added a file using MultipartFile.fromBytes which has the first parameter as List which I created from this method "List.from(objFile.bytes!);"
Notes :
ImageModel.Image is a model I created to handle the image result
DioNetworking is a class that perform dio requests , I just created it to do the
authentication stuff
import 'package:dio/dio.dart';
class DioNetworking {
Dio _dio = new Dio();
Future postData(
String url,
dynamic data, {
String? contentType,
}) async {
try {
Response response = await _dio.post(url,
data: data,
options: Options(headers: {
'content-type': contentType != null ? contentType : 'application/json',
'Accept': 'application/json',
// 'Authorization': 'Bearer ${token ?? ''}'
// other headers
}));
if (response.statusCode == 200) {
dynamic data = response.data;
return data;
} else {
print(response.statusCode);
}
} on DioError catch (e) {
print(e);
if (e.type == DioErrorType.connectTimeout) {
return {'status': 'Connect Timed Out'};
}
if (e.type == DioErrorType.receiveTimeout) {
return {'status': 'Receive Timed Out'};
}
if (e.type == DioErrorType.response) {
print(e.response!.data);
print(e.response!.headers);
}
}
}
}
I work on Music App with Flutter. I want to get music data from YouTube with Youtube API but I just want to list the music. How can I do this on flutter? Music CategoryId = 10 but how can I make a query with this? (Note: I get the Youtube API.)
The code below is an API service code that I have coded:
import 'dart:convert';
import 'dart:io';
import 'package:http/http.dart' as http;
import 'package:beatifun/models/channe_model.dart';
import 'package:beatifun/models/video_model.dart';
import 'package:beatifun/utilities/keys.dart';
class APIService {
APIService._instantiate();
static final APIService instance = APIService._instantiate();
final String _baseUrl = 'www.googleapis.com';
String _nextPageToken = '';
Future<Channel> fetchChannel({String channelId}) async {
Map<String, String> parameters = {
'part': 'snippet, contentDetails, statistics',
'id': channelId,
'key': API_KEY,
};
Uri uri = Uri.https(
_baseUrl,
'/youtube/v3/channels',
parameters,
);
Map<String, String> headers = {
HttpHeaders.contentTypeHeader: 'application/json',
};
// Get Channel
var response = await http.get(uri, headers: headers);
if (response.statusCode == 200) {
Map<String, dynamic> data = json.decode(response.body)['items'][0];
Channel channel = Channel.fromMap(data);
// Fetch first batch of videos from uploads playlist
channel.videos = await fetchVideosFromPlaylist(
playlistId: channel.uploadPlaylistId,
);
return channel;
} else {
throw json.decode(response.body)['error']['message'];
}
}
Future<List<Video>> fetchVideosFromPlaylist({String playlistId}) async {
Map<String, String> parameters = {
'part': 'snippet',
'playlistId': playlistId,
'maxResults': '8',
'pageToken': _nextPageToken,
'key': API_KEY,
};
Uri uri = Uri.https(
_baseUrl,
'/youtube/v3/playlistItems',
parameters,
);
Map<String, String> headers = {
HttpHeaders.contentTypeHeader: 'application/json',
};
// Get Playlist Videos
var response = await http.get(uri, headers: headers);
if (response.statusCode == 200) {
var data = json.decode(response.body);
_nextPageToken = data['nextPageToken'] ?? '';
List<dynamic> videosJson = data['items'];
// Fetch first eight videos from uploads playlist
List<Video> videos = [];
videosJson.forEach(
(json) => videos.add(
Video.fromMap(json['snippet']),
),
);
return videos;
} else {
throw json.decode(response.body)['error']['message'];
}
}
Future<List<Video>> fetchVideosFromCategory({int categoryId}) async {
Map<String, dynamic> parameters = {
'part': 'snippet',
'categoryId': categoryId,
'maxResults': '80',
'pageToken': _nextPageToken,
'key': API_KEY,
};
Uri uri = Uri.https(
_baseUrl,
'/youtube/v3/videos',
parameters,
);
Map<String, String> headers = {
HttpHeaders.contentTypeHeader: 'application/json',
};
// Get Playlist Videos
var response = await http.get(uri, headers: headers);
if (response.statusCode == 200) {
var data = json.decode(response.body);
_nextPageToken = data['nextPageToken'] ?? '';
List<dynamic> videosJson = data['items'];
// Fetch first eight videos from uploads playlist
List<Video> videos = [];
videosJson.forEach(
(json) => videos.add(
Video.fromMap(json['snippet']),
),
);
return videos;
} else {
throw json.decode(response.body)['error']['message'];
}
}
}