Flutter. How to shape the Future<list<product>Enterprise</list<product>



  • There is a method of requesting:

    Future<List<Product>> fetchAlbum() async {
      final response = await http
          .get(Uri.parse('https://fakestoreapi.com/products'));
      if (response.statusCode == 200) {
        Iterable l = json.decode(response.body);
        List<Product> products= List<Product>.from(l.map((i) => Product.fromJson(i)));
        return products;
      } else {
        throw Exception('Failed to load album');
      }
    }
    

    He's returning a list of products from the shop: https://fakestoreapi.com/

    How do you like it? title Second element? Verst:

    @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'Fetch Data Example',
          theme: ThemeData(
            primarySwatch: Colors.blue,
          ),
          home: Scaffold(
            appBar: AppBar(
              title: const Text('Fetch Data Example'),
            ),
            body: Center(
              child: FutureBuilder<Product>(
                future: futureAlbum,
                builder: (context, snapshot) {
                  if (snapshot.hasData) {
                    return Text(snapshot.data.title);
                  } else if (snapshot.hasError) {
                    return Text('${snapshot.error}');
                  }
                  // By default, show a loading spinner.
                  return const CircularProgressIndicator();
                },
              ),
            ),
          ),
        );
      }
    }
    

    Subject:

    class Product {
      final int id;
      final String title, description, category;
      final double price;
      final String image;
      final Map rating;
    

    Product({
    @required this.id,
    @required this.title,
    @required this.description,
    @required this.category,
    @required this.price,
    @required this.image,
    @required this.rating
    });

    factory Product.fromJson(Map<String, dynamic> json) {
    return Product(
    id: json['id'],
    title: json['title'],
    description: json['description'],
    category: json['category'],
    price: json['price'],
    image: json['image'],
    rating: json['rating'],
    );
    }
    }



  • Generic FutureBuilder is not correct. It should be the same as returning the meaning of the future. Then you can turn to the second element. snapshot.data.products.[2].title




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2