Home > front end >  How to print a single object from an Api? Instance of Future<List<Sponsor>> instead of t
How to print a single object from an Api? Instance of Future<List<Sponsor>> instead of t

Time:09-23

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>>:

image

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:

  1. How can I print a single item from an Api (For example, printing only "spo_attivo = 1 ")?

  2. 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'],
    );
  }
}

CodePudding user response:

void stampa() async {
  // print(await futureSponsor);
  var sponsorObjectList = await fetchSponsor();
  
  print('${sponsorObject[0].spoAttivo}');

  for (var element in sponsorObjectList) {
    print('spoFoto = ${element.spoFoto}');
  }
}

CodePudding user response:

You should use FutureBuilder. Then the code will be very simple as follow

// printing only "spo_attivo = 1 "
children = snapshot.data.where((el) => el?['spo_attivo'] = 1).toList();

// printing all spo_foto with loop
for (var i = 0; i < children.length; i  ) { print(children[i]['spo_foto']); }

Here is the full working FutureBuilder widget code which you can render as child: where you want to display the data.

 FutureBuilder<String>(
  future: fetchSponsor(),
  builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
    List<Widget> children;
    if (snapshot.hasData) {
      // printing only "spo_attivo = 1 "
      children = snapshot.data.where((el) => el?['spo_attivo'] = 1).toList();

      // printing all spo_foto with loop
      for (var i = 0; i < children.length; i  ) {
        print(children[i]['spo_foto']);
      }
    } else if (snapshot.hasError) {
      children = <Widget>[
        const Icon(
          Icons.error_outline,
          color: Colors.red,
          size: 60,
        ),
        Padding(
          padding: const EdgeInsets.only(top: 16),
          child: Text('Error: ${snapshot.error}'),
        ),
      ];
    } else {
      children = const <Widget>[
        SizedBox(
          width: 60,
          height: 60,
          child: CircularProgressIndicator(),
        ),
        Padding(
          padding: EdgeInsets.only(top: 16),
          child: Text('Awaiting result...'),
        ),
      ];
    }
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: children,
      ),
    );
  },
)

CodePudding user response:

Try this:

void stampa() async {
  var _list = await futureSponsor;
  for (var element in _list) {
      print('spoAttivo = ${element.spoAttivo}');
  }
  
}

Or if you want to print your response you can do this:

factory Sponsor.fromJson(Map<String, dynamic> json) {
    print('spo_attivo = ${json['spo_attivo']}');
    return Sponsor(
      spoId: json['spo_id'],
      spoNome: json['spo_nome'],
      spoFoto: json['spo_foto'],
      spoAttivo: json['spo_attivo'],
    );
  }
  • Related