Flutter 商品列表开发:使用 API 获取数据并展示/n/n本教程将展示如何在 Flutter 应用中使用 API 获取商品列表数据,并将其展示在 ListView 中。我们将使用一个示例 API 和一个简单的 Product 模型,并提供一个完整的示例代码。/n/n1. 创建 Product 模型/n/n首先,创建一个 Product 模型来表示商品数据:/n/ndart/nclass Product {/n final String imageUrl;/n final String title;/n final double price;/n/n Product({required this.imageUrl, required this.title, required this.price});/n/n factory Product.fromJson(Map<String, dynamic> json) => Product(/n imageUrl: json['imageUrl'],/n title: json['title'],/n price: double.parse(json['price']),/n );/n}/n/n/n2. 创建 API 服务类/n/n创建一个 GetProductService 类来处理 API 请求:/n/ndart/nimport 'dart:convert';/nimport 'package:http/http.dart' as http;/nimport 'package:video_book_ecommerce/model/Product.dart';/n/nclass GetProductService {/n static Future<List<Product>> getProducts(int page, int limit) async {/n final response = await http.get(Uri.parse('https://example.com/api/products?page=$page&limit=$limit'));/n/n if (response.statusCode == 200) {/n final List<dynamic> data = json.decode(response.body)['data'];/n return data.map((product) => Product.fromJson(product)).toList();/n } else {/n throw Exception('Failed to load products');/n }/n }/n}/n/n/n3. 在 Home 页面中获取和展示商品列表/n/n在 Home 页面中,使用 GetProductService 获取商品数据,并在 ListView.builder 中展示:/n/ndart/nimport 'package:flutter/material.dart';/nimport 'package:video_book_ecommerce/compoment/ProductCard.dart';/nimport 'package:video_book_ecommerce/model/Product.dart';/nimport 'package:video_book_ecommerce/service/GetProduct.dart';/n/nclass Home extends StatefulWidget {/n @override/n _HomeState createState() => _HomeState();/n}/n/nclass _HomeState extends State<Home> {/n List<Product> _products = [];/n/n @override/n void initState() {/n super.initState();/n _loadProducts();/n }/n/n void _loadProducts() async {/n final products = await GetProductService.getProducts(1, 10); // 获取第一页,每页10个商品/n setState(() {/n _products = products;/n });/n }/n/n @override/n Widget build(BuildContext context) {/n return Scaffold(/n appBar: AppBar(/n title: Text('商品列表'),/n ),/n body: ListView.builder(/n itemCount: _products.length,/n itemBuilder: (context, index) {/n final product = _products[index];/n return ProductCard(/n imageUrl: product.imageUrl,/n title: product.title,/n price: product.price.toString(),/n );/n },/n ),/n );/n }/n}/n/n/n4. 使用 ProductCard 展示商品信息/n/nProductCard 是一个自定义 Widget,用于展示单个商品的信息:/n/ndart/nimport 'package:flutter/material.dart';/n/nclass ProductCard extends StatelessWidget {/n final String imageUrl;/n final String title;/n final String price;/n/n const ProductCard({Key? key, required this.imageUrl, required this.title, required this.price}) : super(key: key);/n/n @override/n Widget build(BuildContext context) {/n return Card(/n child: Container(/n padding: const EdgeInsets.all(16.0),/n child: Column(/n crossAxisAlignment: CrossAxisAlignment.start,/n children: <Widget>[/n Image.network(imageUrl),/n const SizedBox(height: 8.0),/n Text(title, style: const TextStyle(fontWeight: FontWeight.bold)),/n const SizedBox(height: 4.0),/n Text('价格: /$' + price),/n ],/n ),/n ),/n );/n }/n}/n/n/n完整代码示例:/n/ndart/nimport 'dart:convert';/nimport 'package:flutter/material.dart';/nimport 'package:http/http.dart' as http;/n/n// Product 模型/nclass Product {/n final String imageUrl;/n final String title;/n final double price;/n/n Product({required this.imageUrl, required this.title, required this.price});/n/n factory Product.fromJson(Map<String, dynamic> json) => Product(/n imageUrl: json['imageUrl'],/n title: json['title'],/n price: double.parse(json['price']),/n );/n}/n/n// API 服务类/nclass GetProductService {/n static Future<List<Product>> getProducts(int page, int limit) async {/n final response = await http.get(Uri.parse('https://example.com/api/products?page=$page&limit=$limit'));/n/n if (response.statusCode == 200) {/n final List<dynamic> data = json.decode(response.body)['data'];/n return data.map((product) => Product.fromJson(product)).toList();/n } else {/n throw Exception('Failed to load products');/n }/n }/n}/n/n// Home 页面/nclass Home extends StatefulWidget {/n @override/n _HomeState createState() => _HomeState();/n}/n/nclass _HomeState extends State<Home> {/n List<Product> _products = [];/n/n @override/n void initState() {/n super.initState();/n _loadProducts();/n }/n/n void _loadProducts() async {/n final products = await GetProductService.getProducts(1, 10); // 获取第一页,每页10个商品/n setState(() {/n _products = products;/n });/n }/n/n @override/n Widget build(BuildContext context) {/n return Scaffold(/n appBar: AppBar(/n title: Text('商品列表'),/n ),/n body: ListView.builder(/n itemCount: _products.length,/n itemBuilder: (context, index) {/n final product = _products[index];/n return ProductCard(/n imageUrl: product.imageUrl,/n title: product.title,/n price: product.price.toString(),/n );/n },/n ),/n );/n }/n}/n/n// ProductCard Widget/nclass ProductCard extends StatelessWidget {/n final String imageUrl;/n final String title;/n final String price;/n/n const ProductCard({Key? key, required this.imageUrl, required this.title, required this.price}) : super(key: key);/n/n @override/n Widget build(BuildContext context) {/n return Card(/n child: Container(/n padding: const EdgeInsets.all(16.0),/n child: Column(/n crossAxisAlignment: CrossAxisAlignment.start,/n children: <Widget>[/n Image.network(imageUrl),/n const SizedBox(height: 8.0),/n Text(title, style: const TextStyle(fontWeight: FontWeight.bold)),/n const SizedBox(height: 4.0),/n Text('价格: /$' + price),/n ],/n ),/n ),/n );/n }/n}/n/n/n注意:/n/n- 替换示例 API 地址 https://example.com/api/products 为您的实际 API 地址。/n- 确保您的 API 返回的是 JSON 数据,并且数据结构与 Product 模型一致。/n- 如果您的 API 需要身份验证,您需要在 GetProductService 类中添加身份验证逻辑。/n- 可以根据您的需求对 ProductCard Widget 进行定制,例如添加其他商品信息。/n/n希望本教程能够帮助您在 Flutter 应用中使用 API 获取商品列表数据,并将其展示在 ListView 中。

Flutter 商品列表开发:使用 API 获取数据并展示

原文地址: https://www.cveoy.top/t/topic/nJoM 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录