Last active
April 4, 2022 04:33
-
-
Save rido-ramadan/2416608284bba042234989d572e906d8 to your computer and use it in GitHub Desktop.
GridView 1:1 Ratio
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import 'dart:convert'; | |
| import 'package:flutter/material.dart'; | |
| import 'package:http/http.dart'; | |
| class SimpleGridScreen extends StatelessWidget { | |
| SimpleGridScreen({Key? key}) : super(key: key); | |
| final httpClient = Client(); | |
| @override | |
| Widget build(BuildContext context) { | |
| return Scaffold( | |
| appBar: AppBar( | |
| title: const Text('Grid 1:1'), | |
| ), | |
| body: FutureBuilder<List<String>>( | |
| future: fetchProducts(), | |
| builder: (context, snapshot) { | |
| if (snapshot.hasData) { | |
| return _buildGrid(context, snapshot.data!); | |
| } else { | |
| return _buildLoading; | |
| } | |
| }, | |
| ), | |
| ); | |
| } | |
| Widget _buildGrid(BuildContext context, List<String> images) { | |
| return GridView.builder( | |
| gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( | |
| crossAxisCount: 3, | |
| crossAxisSpacing: 4, | |
| mainAxisSpacing: 4, | |
| ), | |
| itemBuilder: (context, index) { | |
| return Card( | |
| child: Image.network(images[index]), | |
| ); | |
| }, | |
| itemCount: images.length, | |
| ); | |
| } | |
| Widget get _buildLoading { | |
| return const Center( | |
| child: CircularProgressIndicator(), | |
| ); | |
| } | |
| Future<List<String>> fetchProducts() async { | |
| const url = 'https://fakestoreapi.com/products?limit=20'; | |
| final response = await httpClient.get(Uri.parse(url)); | |
| if (response.statusCode >= 200 && response.statusCode < 400) { | |
| return (jsonDecode(response.body) as List<dynamic>) | |
| .map((product) => product['image'] as String) | |
| .toList(); | |
| } else { | |
| return []; | |
| } | |
| } | |
| } | |
| void main() => runApp(MaterialApp(home: SimpleGridScreen())); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment