我在主屏幕中在同一屏幕中获取多个 Api 时遇到此问题,问题是当屏幕加载时,它首先调用横幅 Api,然后 2 秒后它从滚动屏幕顶部调用 Gridview 数据,就像一个小动画一样我不希望这种情况发生,我只是希望所有 Api 一起获取,而不是一个接一个地获取。那么有人可以帮我吗? 这是我的 Api 调用:
Future<List<BannerItem>> fetchbanner() async{
final response = await http.get(Uri.parse('${AppColors.api}/app/banners'));
if(response.statusCode == 200){
final Map<String, dynamic> responseMap = json.decode(response.body);
final Map<String, dynamic> dataMap = responseMap['data'];
final List<dynamic> bannerData = dataMap['results'];
return bannerData.map((json) => BannerItem.fromJson(json)).toList();
} else {
throw Exception('Failed to load banners');
}
}
Future<List<Product>> fetchProducts() async {
final response = await http.get(Uri.parse('${AppColors.api}/products'));
if (response.statusCode == 200) {
final Map<String, dynamic> responseMap = json.decode(response.body);
final Map<String, dynamic> dataMap = responseMap['data'];
final List<dynamic> productList = dataMap['results'];
SharedPreferences prefs = await SharedPreferences.getInstance();
List<String> productIds = productList.map((json) => Product.fromJson(json).id).toList();
await prefs.setStringList('productIds', productIds);
return productList.map((json) => Product.fromJson(json)).toList();
} else {
throw Exception('Failed to load products');
}
}
FutureBuilder<List<BannerItem>>(
future: _futureBanners,
builder: (context, snapshot){
if(snapshot.connectionState == ConnectionState.waiting){
return Center(child: CircularProgressIndicator(color: AppColors.buttonColor,),);
} else if (snapshot.hasError) {
return Center(child: Text('Error: ${snapshot.error}'));
}else if (!snapshot.hasData || snapshot.data!.isEmpty) {
return const Center(child: Text('No products available'));
} else {
final banners = snapshot.data!;
return AnimatedSize(
duration: const Duration(milliseconds: 300),
child: Container(
width: double.infinity,
decoration: BoxDecoration(
color: AppColors.backgroundColor,
borderRadius: BorderRadius.circular(0),
),
child: Padding(
padding: const EdgeInsets.only(top: 10.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
width: double.infinity,
height: MediaQuery.of(context).size.height * 0.2,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(30),
color: const Color.fromARGB(255, 249, 255, 249),
),
child: PageView.builder(
controller: _pageController,
onPageChanged: (index) {
setState(() {
_currentPage = index;
});
},
itemCount: banners.length,
itemBuilder: (context, index) {
return GestureDetector(
onTap: () async {
final url = Uri.parse(banners[index].url);
if (await canLaunchUrl(url)) {
await launchUrl(url, mode: LaunchMode.externalApplication);
} else {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Could not launch $url')),
);
}
},
child: Container(
margin: const EdgeInsets.symmetric(horizontal: 10.0),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(30),
color: AppColors.lightTheme,
),
clipBehavior: Clip.hardEdge,
child: Image.network(
banners[index].image,
fit: BoxFit.cover,
width: double.infinity,
height: double.infinity,
),
),
);
},
),
),
const SizedBox(height: 10),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: List.generate(banners.length, (index) {
return Container(
margin: const EdgeInsets.symmetric(horizontal: 4),
width: 10,
height: 10,
decoration: BoxDecoration(
shape: BoxShape.circle,
color: _currentPage == index
? AppColors.buttonColor
: Colors.green.shade200,
),
);
}),
),
网格视图API
FutureBuilder<List<Product>>(
future: _futureProducts,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return const Center(child: CircularProgressIndicator(
color: AppColors.buttonColor,
));
} else if (snapshot.hasError) {
return Center(child: Text('Error: ${snapshot.error}'));
} else if (!snapshot.hasData || snapshot.data!.isEmpty) {
return const Center(child: Text('No products available'));
} else {
final products = snapshot.data!;
return Padding(
padding: const EdgeInsets.all(8.0),
child: GridView.builder(
controller: _gridScrollController,
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
crossAxisSpacing: 10.0,
mainAxisSpacing: 10.0,
childAspectRatio: 0.99,
),
itemCount: products.length,
itemBuilder: (context, index) {
final product = products[index];
final isFavorite = favoriteProvider.isFavorite(product);
return GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ItemDetailsScreen(productId: product.id),
),
);
},
child: Card(
color: Colors.white,
elevation: 5,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15),
),
child: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
border: Border.all(
color: Colors.white,
width: 5,
),
),
child: Stack(
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Flexible(
flex: 2,
child: ClipRRect(
borderRadius: const BorderRadius.vertical(top: Radius.circular(15)),
child: Container(
color: AppColors.lightTheme,
child: Image.network(
product.imageUrl,
fit: BoxFit.cover,
width: double.infinity,
),
),
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
product.title,
style: const TextStyle(
fontSize: 16,
fontWeight: FontWeight.bold,
),
),
Text(
'₹${product.marketPrice}',style:TextStyle(
fontSize: 16,
fontWeight: FontWeight.bold,
color: AppColors.priceColor,
) ,
)
],
),
),
],
),
我已经调试了代码并得到了为什么会发生这种情况的答案,因为我已经使用了 Animatedsize 并且我已经删除了它,现在它正在按我想要的方式运行