Совместное получение данных APIAndroid

Форум для тех, кто программирует под Android
Ответить
Anonymous
 Совместное получение данных API

Сообщение Anonymous »

У меня возникает эта проблема на главном экране при получении нескольких API на одном экране. Проблема заключается в том, что при загрузке экрана сначала он вызывает API баннера, а затем через 2 секунды вызывает данные Gridview при прокрутке верхней части экрана, как немного Анимация, поэтому я не хочу, чтобы это произошло, я просто хочу, чтобы все API извлекались вместе, а не один за другим... Итак, кто-нибудь может мне помочь в этом, пожалуйста,
Это мои вызовы API
Future fetchbanner() async{
final response = await http.get(Uri.parse('${AppColors.api}/app/banners'));
if(response.statusCode == 200){
final Map responseMap = json.decode(response.body);
final Map dataMap = responseMap['data'];
final List bannerData = dataMap['results'];
return bannerData.map((json) => BannerItem.fromJson(json)).toList();

} else {
throw Exception('Failed to load banners');
}
}

Future fetchProducts() async {
final response = await http.get(Uri.parse('${AppColors.api}/products'));
if (response.statusCode == 200) {
final Map responseMap = json.decode(response.body);
final Map dataMap = responseMap['data'];
final List productList = dataMap['results'];
SharedPreferences prefs = await SharedPreferences.getInstance();
List 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(
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 GRIDVIEW
FutureBuilder(
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,
) ,
)

],
),
),
],
),


Подробнее здесь: https://stackoverflow.com/questions/792 ... a-together
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Android»