'Can't manage to fetch data from a second JSON file

I'm trying to use a fetched data from a JSON file to make another fetch on a second screen.

Let's say I have a JSON file that was fetched via www.fruits.com/data. Then one of the fruits has an ID of 1. In order to have more information about this fruit, I have to access another JSON file on www.fruits.com/data/1.

I have both of these fetch functions to access JSON and drag said data:

List<Fruitmodel> parseFruit(String responseBody) {
  var list = json.decode(responseBody) as List<dynamic>;
  List<Fruitmodel> fruits = list.map((model) => Fruitmodel.fromJson(model)).toList();
  return fruits;
}


List<FruitDetails> parseDetails(String responseBody) {
  var list = json.decode(responseBody) as List<dynamic>;
  List<FruitDetails> fruit_details = list.map((model) => FruitDetails.fromJson(model)).toList();
  return fruit_details;
}
Future<List<FruitModel>> fetchFruit() async {
  final response = await http.get(Uri.parse('https://fruits.com/data'));
    
  if (response.statusCode == 200){
    return compute(parseFruits, response.body);
  }
  else{
    throw Exception('Failed to get fruits.');
  }
}

Future<List<FruitDetails>> fetchDetails(int? a) async {      //"int a" is to get the fruit's ID
  String newUrl = 'https://fruits.com/data/' + a.toString();
  final response = await http.get(Uri.parse(newUrl));
    
  if (response.statusCode == 200){
    return compute(parseDetails, response.body);
  }
  else{
    throw Exception('Failed to get details.');
  }
}

On my homepage, I used the first fetch function (FetchFruit), and managed to make a fruit list with the first JSON file by using Future Builder (snapshots), then my next task is to click on a fruit and show its details.

...
onTap:(){
  Navigator.push(context,
  new MaterialPageRoute(builder: (context)
  => DetailsPage(snapshot.data[index])));
...

So, on my next page, I'm initializing it with data from the fruit I've chosen. Then, I try to make the other fetch function (fetchDetails) by using said fruit's ID contained on the other JSON.

...
body: Center(
  child: FutureBuilder(
    future: fetchDetails(this.fruit.id),    //Using ID to mount the correct URL
...

But... It doesn't work. I did a condition to tell me that if the snapshot has an error, it prints "Data not available" on the screen, and it does that instead of reading the second JSON file. What should I do for the second fetch to be done correctly?

In resume: 1st JSON file -> ID -> used to access 2nd JSON file -> not working



Solution 1:[1]

Try using this

String newUrl = 'https://fruits.com/data/$a';

and make sure the value won't be null.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Lakshydeep Vikram Sah