Fetching and Displaying Images from the Network

This example shows how to fetch and display images from the internet.

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Image Fetch Example',
      theme: ThemeData(primarySwatch: Colors.blue),
      home: ImageList(),
    );
  }
}

class ImageList extends StatefulWidget {
  @override
  _ImageListState createState() => _ImageListState();
}

class _ImageListState extends State<ImageList> {
  List _images = [];
  bool _loading = true;

  @override
  void initState() {
    super.initState();
    _fetchImages();
  }

  Future<void> _fetchImages() async {
    final response = await http.get(Uri.parse('https://api.example.com/images'));

    if (response.statusCode == 200) {
      setState(() {
        _images = json.decode(response.body);
        _loading = false;
      });
    } else {
      throw Exception('Failed to load images');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Image Fetch Example')),
      body: _loading
          ? Center(child: CircularProgressIndicator())
          : GridView.builder(
              gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
              itemCount: _images.length,
              itemBuilder: (context, index) {
                return Image.network(_images[index]['url']);
              },
            ),
    );
  }
}

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *