I have made a helper function which is a task to fetch data from the server and return it as a promise-based response.
Btw. I am a Flutter newbie :)
Helper function:
import 'dart:convert';
import 'package:http/http.dart' as http;
class FetchModules {
void fetchAllModules() async {
var url = Uri.parse('https://jsonplaceholder.typicode.com/todos/');
var response = await http.get(url);
if (response.statusCode == 200) {
String data = response.body;
var decodedData = jsonDecode(data);
return decodedData;
}
}
}
Widget where I want to get a response:
void initState() {
super.initState();
FetchModules().fetchAllModules().then((){});
}
VSCode Error:
This expression has a type of 'void' so its value can't be used.
Try checking to see if you're using the correct API;
there might be a function or call that returns void you didn't expect.
Also check type parameters and variables which might also be void.dart(use_of_void_result)
So, how to fix this?
Thanks!
Related
this is mycode .please solve this problem
import 'dart:convert' as convert;
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:http/http.dart';
import 'package:internetconnectivityusingbloc/repos/user_model.dart';
class UserRepositories {
Future<void> getUsers() async {
List<UserData>? userData = [];
String urlEndPoint = "https://reqres.in/api/users?page=2";
// Await the http get response, then decode the json-formatted response.
Response response = await http.get(Uri.parse(urlEndPoint));
if (response.statusCode == 200) {
userData = [];
// final List result = jsonDecode(response.body);
return userData.addAll(UserModel.fromjson(response.body));
} else {
throw Exception(response.reasonPhrase);
// print('Request failed with status: ${response.statusCode}.');
}
}
}
i am trying to solve this problem .but i am failed.so i expecting u are solve this problem
Add [] inside addAll:
return userData.addAll([UserModel.fromjson(response.body)]);
If you are only adding one model is better to only use the method add.
Howerver you are trying to add a type UserModel to a list of UserData and that might throw another error if UserModel is not a child of UserData. So if you are expecting to fill the variable userData you should use UserData.fromjson(response.body) to fill the new data, so you should adjust UserData parameters to get the data that response.body will bring.
So I'm new to flutter and dart and am trying to call from the CoinMarketCap API. I'm using the HTTP package to call the data and the API. I'm not super familiar with them but here's what I came up with...
import 'package:http/http.dart' as http;
import 'dart:convert';
Future<Payload> getCryptoPrices() async {
var response = await http.get(Uri.parse(
"https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest?start=1&limit=5000&convert=USD"),
headers: {
'X-CMC_PRO_API_KEY': 'my-key',
"Accept": "application/json",
});
if (response.statusCode == 200) {
Payload payload = payloadFromJson(data.body);
return payload;
}
}
I get a couple of errors:
The name 'Payload' isn't a type so it can't be used as a type argument
The function 'payloadFromJson' isn't defined
Undefined name 'data'
Am I not successfully importing JSON? I'm not sure how to fix the error. What do I need to do to successfully make a API Call? Any feedback would be great.
CODE UPDATED #1
import 'package:wnetworking/wnetworking.dart';
class CoinMarketCap {
static const _apiKey = '111111111111111111111111111111';
static const _url = 'https://pro-api.coinmarketcap.com/v1/cryptocurrency';
static Future<void> getListingLatest(int limit) async {
var url = '$_url/listings/latest?start=1&limit=$limit&convert=USD';
var result = await HttpReqService.get<JMap>(
url,
auth: AuthType.apiKey,
authData: MapEntry('X-CMC_PRO_API_KEY', _apiKey)
);
var coins = (result?['data'] as List).cast<JMap>().map<String>((e) => e['name']);
print(coins);
}
}
void main(List<String> args) async {
await CoinMarketCap.getListingLatest(7);
print('\nJob done!');
}
Output:
(Bitcoin, Ethereum, Tether, USD Coin, BNB, XRP, Cardano)
Job done!
'Payload' is not a flutter class so it does not exist. were you trying to use a Custom made Class?
the 'payloadFromJson' error means it does not exist so you probably did not import it properly if it is in another class
Undefined name 'data' means that data has not been defined if you want the body of the response use 'response.body'
I was trying to pass a data to a variable that returns future but it returns out to be null even though I'm using async and await. what is I'm missing here ?
import 'package:http/http.dart' as http;
import 'dart:convert';
const apiKey = 'deac2cf3c5bb6ee4e7350802f47595bd';
const apiURL =
'https://api.openweathermap.org/data/2.5/weather?lat=35&lon=139&appid=$apiKey';
var lon;
void main() async {
lon = await Weather().longitude;
print(lon); // returns null
}
class Weather {
var longitude;
Weather({this.longitude});
void getWeatherData() async {
Uri parsedUrl = Uri.parse(apiURL);
http.Response response = await http.get(parsedUrl);
if (response.statusCode == 200) {
longitude = jsonDecode(response.body)['coord']['lon'];
}
}
}
Expected output :
139
Actual output:
null
you are awaiting the constructor, which is not an async function anyway plus you are accessing the variable longtiude which has not been set yet, you need to call the function getWeatherData first
final weather = Weather();
await weather.getWeatherData();
print(weather.longtiude);
I have an API (which does work and returns a response, and I even can see the response 1 line above the return statement), but for some reason, when the data should be passed to the variable, I receive null, instead of the returned value.
the service DOES return data I DO get the value from the API, at least it shows that there is data in the variable before the return.
The resp variable, which should contain the data, shows that the value is empty.
api_service.dart <= Returns a value
import 'dart:io';
import 'package:http/http.dart' as http;
import 'dart:convert';
class RemoteServices {
static var client = http.Client();
static Future sendImageForAnalysis(String filename) async {
var request =
http.MultipartRequest('POST', Uri.parse("http://10.0.2.2:8000/api"));
request.files.add(http.MultipartFile('picture',
File(filename).readAsBytes().asStream(), File(filename).lengthSync(),
filename: filename.split("/").last));
var res = await request.send();
if (res.statusCode == 200) {
http.Response.fromStream(res)
.then((response) {
var dataAsJson = json.decode(response.body);
/* The variable from above does have data, it's not empty and none of the errors appears*/
return dataAsJson;
})
.catchError((error) => print('Something went wrong')) /* Error is not showing */
.whenComplete(() => print('Got data from the server'));
} else {
/* Code does not get here */
return {'name': 'x'};
}
}
}
controller_results.dart <= Shows null, instead of the value.
import 'package:face_search/services/api_service.dart';
import 'package:get/get.dart';
class ResultsController extends GetxController {
final data = {}.obs;
final name = ''.obs;
void getItemData(imagePath) async {
var resp = await RemoteServices.sendImageForAnalysis(imagePath);
print(resp); /* This is empty for some reason */
if (resp != null) {
data.value = resp;
}
}
}
You're missing a return before http.Response.fromStream(res).
Does the result of the api return json? If its return json why dont try to create a model for it and call the list on your controller so that you can freely know if its having a data to return.
I'm fetching data in flutter and created a helper class as seen below
import 'dart:convert';
import 'package:http/http.dart' as http;
class HttpClient {
final Map<String, String> _headers = {};
void setHeader(String key, String value) {
if (!_headers.containsKey(key)) {
_headers[key] = value;
}
}
Future<http.Response> get(String url) async {
try {
var uri = Uri.parse(url);
var response = await http.get(uri, headers: _headers);
if (response.statusCode == 200) {
dynamic result = jsonDecode(response.body);
return result;
} else {
throw Error();
}
} on Exception catch (_) {
rethrow;
}
}
}
HttpClient appClient = HttpClient();
I call the method from a class as shown below
abstract class AbstractTodoService {
dynamic getTodos() {}
}
class HttpTodoService implements AbstractTodoService {
#override
Future<Response> getTodos() async {
try {
var todos =
await appClient.get('https://jsonplaceholder.typicode.com/todos');
print(todos);
return todos;
} on Exception catch (error) {
print(error);
rethrow;
}
}
}
However, when I print todos or any string in the HttpTodoService after the await call to the HttpClient I do not see anything. However, when I print the result inside the HttpClient I see the response but does not return. When I return a normal string or map everything works normally but when I attempt to use the jsonDecoded response nothing returns.
Your jsonDecode(response.body); returns a List<dynamic> type, but your function return type is Future<http.Response>. This is why you are not getting data.
You can check runtime datatype of a variable by
print(result.runtimeType); // variable_name.runtimeType
Change function return types to Future<List<dynamic>> of get(String url) and getTodos() functions.
It might be because your function returns a future of http.Response which is actually the type of the response after you use http.get. After you use jsonDecode you should get a Map<String, dynamic> which represent the json.
From the documentation:
By looking at the dart:convert documentation, you’ll see that you can decode the JSON by calling the jsonDecode() function, with the JSON string as the method argument.
Map<String, dynamic> user = jsonDecode(jsonString);
print('Howdy, ${user['name']}!');
print('We sent the verification link to ${user['email']}.');
Unfortunately, jsonDecode() returns a Map<String, dynamic>, meaning that you do not know the types of the values until runtime. With this approach, you lose most of the statically typed language features: type safety, autocompletion and most importantly, compile-time exceptions. Your code will become instantly more error-prone.
For example, whenever you access the name or email fields, you could quickly introduce a typo. A typo that the compiler doesn’t know about since the JSON lives in a map structure.
After you use jsonDecode you should turn the map into the object you want to work with using factory fromJson method.
You can read more about is in the documentation https://flutter.dev/docs/development/data-and-backend/json