我试图从Woocommerce API获取产品数据,并尝试在主页上显示此数据的Flutter,但我无法在首页上显示数据.我得到响应.身体成功,并在终端打印,但我不知道为什么它不显示在主屏幕上.有人可以请帮助我解决这个问题吗?
Woocommerce产品我提到的壁纸。
下面是要获取数据的wallpaper.dart文件:
import 'package:flutter/material.dart';
import 'dart:async';
import '../model/wallpaper_model.dart';
import './home.dart';
import '../helper_services/helperservices.dart';
class WallpaperWidget extends StatefulWidget {
const WallpaperWidget({Key? key}) : super(key: key);
@override
State<WallpaperWidget> createState() => _WallpaperWidgetState();
}
class _WallpaperWidgetState extends State<WallpaperWidget> {
List<Products>? wallpapers;
var isLoaded = false;
@override
void initState() {
super.initState();
getData(); // Call getData to fetch wallpapers when the widget is initialized
}
getData() async {
wallpapers = await HelperService().getWallpapers();
if (wallpapers != null) {
setState(() {
isLoaded = true;
});
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Visibility(
visible: isLoaded,
child: ListView.builder(
itemCount: wallpapers?.length,
itemBuilder: (context, index) {
final wallpaper = wallpapers?[index];
return ListTile(
title: Text(wallpaper?.name ?? ''),
// Display other properties of the wallpaper as needed.
);
}
),
replacement: Center(
child: CircularProgressIndicator(),
),
),
);
}
}
字符串
下面是用于API调用的helperservice.dart:
import 'dart:convert';
import 'package:http/http.dart' as http;
import '../model/wallpaper_model.dart'; // Import the Products class from your product_model.dart file
class HelperService {
final String consumerKey = ''; // Replace with your actual consumer key
final String consumerSecret = ''; // Replace with your actual consumer secret
Future<List<Products>> getWallpapers() async {
final String url = 'https://my_site.in/wp-json/wc/v3/products';
// Encode consumer key and secret to base64
final String credentials = base64Encode(
utf8.encode('$consumerKey:$consumerSecret'),
);
try {
final response = await http.get(
Uri.parse(url), // Removed the per_page query parameter
headers: {
'Authorization': 'Basic $credentials',
},
);
if (response.statusCode == 200) {
// If the request is successful, parse the response
List<Products> products = productsFromJson(response.body);
return products;
} else {
throw Exception('Failed to load products');
}
} catch (e) {
print('Error: $e');
throw Exception('Error: $e');
}
}
}
型
我尝试了大部分的方式来展示产品
1条答案
按热度按时间ee7vknir1#
GetData
是一个cnrc函数。这意味着它需要时间来执行,并且结果不能立即获得(简单来说)。所以,当build函数执行时,你还没有这些数据。即使你把函数放在initState函数中,执行顺序是:initState() -> build() -> "when have time getData()"
(同样,为了使它更简单)。这是因为flutter是单线程的。为了在不重新加载的情况下显示数据,只需使用FutureBuilder()
,它在加载您提供的数据时构建一个小部件。字符串
你可能想编辑一些东西(我现在不在编辑器上)。