I'm trying to print a single field from an API but it doesn't recognize the parameter, I tried to print the whole Future, but it only prints Instance of Future <List<Sponsor>>:
The result of the json is:
{
"data": [
{
"spo_id": "1",
"spo_nome": "GENERALI",
"spo_foto": "https://www.bkgchallenge.it/badmin/uploads/files/pnmbdtqzk9g_hfc.jpg",
"spo_attivo": "1"
},
{
"spo_id": "2",
"spo_nome": "VISIONOTTICA SALCIARINI",
"spo_foto": "https://www.bkgchallenge.it/badmin/uploads/files/zawy1vefn48lsk6.jfif",
"spo_attivo": "1"
},
{
"spo_id": "3",
"spo_nome": "RISTORANTE CATIGNANO",
"spo_foto": "https://www.bkgchallenge.it/badmin/uploads/files/l3ymxrebdpjqt51.jpg",
"spo_attivo": "1"
}
]
}
I have two questions:
How can I print a single item from an Api (For example, printing only "spo_attivo = 1 ")?
How can I print a single field from an Api (For example, printing all spo_foto)?
This is the code:
main.dart:
import 'package:carousel_restapi_01/screens/initial_page.dart';
import 'package:flutter/material.dart';
import 'api_management/api_controller.dart';
import 'api_management/api_fetch.dart';
Future<List<Sponsor>> futureSponsor = fetchSponsor();
void stampa() async {
print(await futureSponsor);
}
void main(List<String> args) {
stampa();
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
initialRoute: "/",
routes: {"/": (context) => InitialPage()},
);
}
}
api_fetch.dart:
import 'api_controller.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
Future<List<Sponsor>> fetchSponsor() async {
final response = await http
.get(Uri.parse('https://www.bkgchallenge.it/badmin/APIM/getsponsor.php'));
if (response.statusCode == 200) {
// If the server did return a 200 OK response,
// then parse the JSON.
return (jsonDecode(response.body)['data'] as List<dynamic>)
.map((json) => Sponsor.fromJson(json))
.toList();
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Non sono riuscito a decodificare le squadre');
}
}
api_controller.dart:
class Sponsor {
final String spoId;
final String spoNome;
final String spoFoto;
final String spoAttivo;
const Sponsor({
required this.spoId,
required this.spoNome,
required this.spoFoto,
required this.spoAttivo,
});
factory Sponsor.fromJson(Map<String, dynamic> json) {
return Sponsor(
spoId: json['spo_id'],
spoNome: json['spo_nome'],
spoFoto: json['spo_foto'],
spoAttivo: json['spo_attivo'],
);
}
}
