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.
Related
I'm trying to filter the list of books to only show books of a certain category, but the problem is that it doesn't return nor show anything.
import 'dart:convert';
import 'package:ebook_app/models/book.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
class BooksProvider with ChangeNotifier {
final baseUrl =
"https://www.googleapis.com/books/v1/volumes?q=search-terms&key=AIzaSyApFEv-TWN0ijCKcKUXdyWQ1ziSr093QmY";
dynamic _booksList = [];
dynamic get booksList {
return _booksList!;
}
Future fetchBooks() async {
final url = Uri.parse(baseUrl);
final response = await http.get(url);
if (response.statusCode == 200) {
final responseData = response.body;
// _booksList = responseData;
_booksList = Book.fromJson(jsonDecode(responseData));
print(_booksList.items);
}
}
categoryCheck(cat) {
print(_booksList.items.where((book) => book.volumeInfo.categories == cat));
return _booksList.items.where((book) => book.volumeInfo.categories == cat);
}
}
I've tried putting adding to List but apparently, that's not the problem. Note that the problem is not from the cat, since I've tested it before and it printed the argument perfectly.
The issue is with the categoryCheck() method.
The problem is that _booksList.items are of type List<dynamic> and where() returns an Iterable, which can't be assigned directly to a variable.
You should use the .toList() method to convert the iterable returned by where() to a list and then assign it to the variable you want.
categoryCheck(cat) {
var filteredList = _booksList.items.where(
(book) => book.volumeInfo.categories == cat
).toList();
return filteredList;
}
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.
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'm trying to integrate a stock API into my app. I'm trying to create a service page but I get this error. I searched for similar topics but I couldn't find a solution.
import 'dart:convert';
import 'dart:io';
import 'package:myapp/models/apis/stocks.dart';
import 'package:http/http.dart' as http;
class StocksService {
final String url = "https://api.collectapi.com/economy/hisseSenedi";
Future<StocksModel> fetchStocks() async {
var res = await http.get(Uri.parse(url),
headers: {
HttpHeaders.authorizationHeader:
"apikey xxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
},
);
if (res.statusCode == 200) {
var jsonBody = StocksModel.fromJson(jsonDecode(res.body));
return jsonBody;
} else {
print("İstek başarısız oldu => ${res.statusCode}");
}
}
}
You are not returning anything in your else block. It this is what you require in your code then change the return type of the function to dynamic. And if not then you are required to return the same data type in the else block too.
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!