Flutter / Controller / Api data pass to view
Api Data pass to view
-
STEPS
See also listview
1. pubspec.yaml
dependencies: flutter: sdk: flutter get: ^4.6.1 http: ^0.14.0 2. model
class Product { final int id; final String name; final double price; final String imageUrl; Product({ required this.id, required this.name, required this.price, required this.imageUrl, }); factory Product.fromJson(Map json) { return Product( id: json['id'], name: json['name'], price: json['price'].toDouble(), imageUrl: json['imageUrl'], ); } } Controller
import 'package:get/get.dart'; import 'package:http/http.dart' as http; class ProductController extends GetxController { var products = [].obs; @override void onInit() { super.onInit(); fetchProducts(); } void fetchProducts() async { try { final response = await http.get(Uri.parse('https://api.example.com/products')); if (response.statusCode == 200) { final List data = json.decode(response.body); products.assignAll(data.map((productData) => Product.fromJson(productData)).toList()); } else { throw Exception('Failed to fetch data'); } } catch (e) { print('Error: $e'); } } } Product Screen
import 'package:flutter/material.dart'; import 'package:get/get.dart'; class ProductListPage extends StatelessWidget { final ProductController productController = Get.put(ProductController()); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Product List'), ), body: Obx(() { if (productController.products.isEmpty) { return Center( child: CircularProgressIndicator(), ); } else { return ListView.builder( itemCount: productController.products.length, itemBuilder: (context, index) { final product = productController.products[index]; return ListTile( leading: Image.network( product.imageUrl, width: 50, height: 50, fit: BoxFit.cover, ), title: Text(product.name), subtitle: Text('\$${product.price.toStringAsFixed(2)}'), // Add more details or actions for each product if needed ); }, ); } }), ); } }