Flutter Web - Error code: XML Http Request Error - flutter

I am trying to fetch a simple JSON file from my HTTPS server in flutter web however, it doesn't fetch the JSON and simply prints :-
Error code: XMLHTTPRequest error
How do I fix this issue? Here's my code -
Future<List<GamesJSON>> fetch(String link) async {
final res = await get(Uri.parse(link));
if (res.statusCode == 200) {
final data = json.decode(res.body);
final rest = data;
list = rest.map<GamesJSON>((json) => GamesJSON.fromJson(json)).toList()
as List<GamesJSON>;
}
return list;
}

You need to change this line
list = rest.map<GamesJSON>((json) => GamesJSON.fromJson(json)).toList()
as List<GamesJSON>;
to this
List<GamesJSON> list = rest.map<GamesJSON>((json) => GamesJSON.fromJson(json)).toList();

Related

i am using django as a backend to flutter

when i get data from API Arabix words doesn't show and it show like this
is this from flutter or Django Restframework?
flutter request
'''
final url = Uri.parse('http://127.0.0.1:8000');
final data = await http.get(url);
final flats = json.decode(data.body) as List<dynamic>;
if(flats==null) {
return;
}
print(flats)
'''
The solution was to use dio instead of http.

not able to access json file in flutter api call

I want to use JSON from this link https://howtodoandroid.com/movielist.json.
This is my code where I want to call API from the above link
Future getMovieList() async {
final response = await http.get(Uri.parse("https://howtodoandroid.com/movielist.json"));
if (response.statusCode == 200) {
allMovielist = jsonDecode(response.body);
}
}
i got error "failed to load response data: no data found for resource with given identifier"
Future<List<YourModel>> getMovieList() async {
final response = await http.get(Uri.parse("https://howtodoandroid.com/movielist.json"));
if (response.statusCode == 200) {
/// On first the data will get is always unassigned or just dynamic
/// which cant be identify
final List<dynamic> list = jsonDecode(response.body);
/// try to print or log the data if the data goes to status 200 and able
/// to see it
log(list.map((e) => e).toList().toString());
/// this one will return the indicate assigned data
return list.map((e)=> YourModel.fromJson(e)).toList();
} else{
return [];
}
}
If you are trying this on the web run this command flutter run -d chrome --web-renderer html
if you still get a CROS error disable the web security.
1- Go to flutter\bin\cache and remove a file named: flutter_tools.stamp
2- Go to flutter\packages\flutter_tools\lib\src\web and open the file chrome.dart.
3- Find '--disable-extensions'
4- Add '--disable-web-security'
I get this answer from this link
or consider this package also
Example Code
Future getMoviesList() async {
var headers = <String, String>{'Content-Type': 'application/json'};
var url = Uri.parse('https://howtodoandroid.com/movielist.json');
var response = await http.get(url, headers: headers);
if (response.statusCode == 200) {
var result = json.decode(response.body);
print(result);
return result;
}
}

How to convert multiPartRequest's response into normal http response in flutter?

I have to send api request to upload a file to the server.
the pattern:
repo,
provider
service
i have followed fails because of the response multipartRequest sends
how can i convert the request got into normal get/post request ?
Future mutliPartPostRequest(
{required String method,
required String url,
Map<String, String>? headers,
File? file,
String? document,
Map? data}) async {
Map<String, dynamic> jsonResponse;
try {
var request = http.MultipartRequest(method, Uri.parse(url));
data!.forEach((key, value) {
request.fields[key] = value.toString();
});
request.headers['Authorization'] = headers!['authorization']!;
/// [FILTERING] : the null image if there are no photos in the request it will skip adding the photo in the request
if (file != null) {
var picture = await http.MultipartFile.fromPath("photo", file.path);
request.files.add(picture); //adds the photo to the request
}
// Checking the document if it is empty, if it is empty it will skip to add the document in the request
if (document != null) {
var doc = await http.MultipartFile.fromPath('document', document);
request.files.add(doc); // adds the document to the request
}
///Our case starts from this line, while sending multipart request, the response we get is quite different than the normal json data response.
// response => stores the response got
var response = await request.send().timeout(const Duration(seconds: 10)); //sends the request body to the server
// result => coverts the multipart response got from the server to the normal request
var result = await http.Response.fromStream(response);
jsonResponse = returnResponse(result); /// returns the response according to the status code from [returnResponse] function
} on SocketException {
throw FetchDataException({"detail": "No Internet Connection"});
}
return jsonResponse;
}

How can I fetch and use data with this design in flutter

I have this design, I created it and put the data manually, the question is how can I get the data in the image and it is from this website (https://jsonplaceholder.typicode.com/posts) and display it in the same design
var url = Uri.parse("https://jsonplaceholder.typicode.com/posts");
var response = await http.get(url);
if (response.statusCode == 200) {
var responseJson = jsonDecode(response.body);
responseJson as List;
return responseJson.map((e) => YourModel.fromJson(e)).toList();
}
Firstly, you can paste your JSON in the link below, click convert and get your Dart classes for free.
Secondly, you can copy the result which is named JsonPlaceHolderResponse and create a new file in your project, and paste the result there.
Finally, you can use this code to get your data from defined API:
import 'package:http/http.dart';
Future<JsonPlaceHolderResponse?> getData(String url) async {
final _response = await Client().get(
url
);
if (_response.successResponse) {
final _json = jsonDecode(_response.body);
return JsonPlaceHolderResponse.fromJson(_json);
} else {
return null;
}
return null;
}
extension ResponseExtension on Response {
bool get hasWrongCredentials => statusCode == 422;
bool get tooManyRequests => statusCode == 429;
bool get successResponse => statusCode >= 200 && statusCode < 300;
}

Writing a query parameter with an array of values in Flutter

I'm using the Http package on flutter. I have a query request that should take a large list of values
localhost/accounts/fax-info?ids=(66, 97) this works in post man however. In flutter I tried this exact thing and it just gives me a general error that doesn't tell me anything.
Future<List<CustomerInfo>> getFaxinfo(
List<UnfinishedAccount> accounts,
) async {
final baseUrl = 'localhost';
final int port = 3003;
final accountsPath = '/accounts';
final accountsFaxInfoPath = '$accountsPath/fax-info';
try {
final uri = Uri.parse('http://localhost:3003/accounts/fax-info?ids=(66, 97)');
final response = await http.get(uri, headers: headers);
if (response.statusCode == 200) {
print(jsonDecode(response.body));
}
return [CustomerInfo(sent: 200, received: 300, name: 'Test')];
} catch (err) {
print(err);
rethrow;
}
I tried mapping the values of accounts.id then converting that to a list, I'm not sure if that's the correct way to put it in the query as a list of values because it looks like (66,97) not [66, 97].