Flutter Images and Assets

This section will introduce image loading, local asset management, and network image handling in Flutter.


Image Widget - Image Display

Example: Various Image Loading Methods

// Load image from network
Image.network(
  'https://example.com/image.png',
  width: 200,
  height: 200,
  fit: BoxFit.cover,
)

// Load image from local assets
Image.asset('assets/images/logo.png')

// Load image from local file
Image.file(File('path/to/image.png'))

// Image with loading state
Image.network(
  'https://example.com/image.png',
  loadingBuilder: (context, child, loadingProgress) {
    if (loadingProgress == null) return child;
    return Center(
      child: CircularProgressIndicator(
        value: loadingProgress.expectedTotalBytes != null
            ? loadingProgress.cumulativeBytesLoaded /
                loadingProgress.expectedTotalBytes!
            : null,
      ),
    );
  },
)

// Image with error handling
Image.network(
  'https://example.com/image.png',
  errorBuilder: (context, error, stackTrace) {
    return const Icon(Icons.error, size: 50);
  },
)

Local Resource Management

Configure the asset folder in pubspec.yaml:

flutter:
  assets:
    - assets/images/
    - assets/data.json

Example: Using Local Resources

// Use local image
class AssetImageExample extends StatelessWidget {
  const AssetImageExample({super.key});

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        // Load using Image.asset
        const Image(
          image: AssetImage('assets/images/logo.png'),
          width: 100,
        ),
        // Shorthand form
        const Image.asset('assets/images/icon.png', width: 50),
        const SizedBox(height: 20),
        // Use image fit
        Container(
          width: 200,
          height: 100,
          decoration: BoxDecoration(
            image: const DecorationImage(
              image: AssetImage('assets/images/bg.jpg'),
              fit: BoxFit.cover,
            ),
            border: Border.all(color: Colors.grey),
          ),
        ),
      ],
    );
  }
}

BoxFit Image Fitting

ValueDescription
fillStretch to fill (may distort)
containScale proportionally, maximize to fit
coverScale proportionally, cover completely
fitWidthScale proportionally, fill width
fitHeightScale proportionally, fill height
noneCenter display at original size
scaleDowncontain and not exceed the original size

CachedNetworkImage - Image Caching

Use the cached_network_image package to implement image caching.

Add dependency

dependencies:
  cached_network_image: ^3.0.0

Example: CachedNetworkImage

import 'package:cached_network_image/cached_network_image.dart';

class CachedImageExample extends StatelessWidget {
  const CachedImageExample({super.key});

  @override
  Widget build(BuildContext context) {
    return CachedNetworkImage(
      imageUrl: 'https://example.com/image.png',
      // Display while loading
      placeholder: (context, url) => const CircularProgressIndicator(),
      // Show error
      errorWidget: (context, url, error) => const Icon(Icons.error),
      // Image fit
      fit: BoxFit.cover,
      // Width and height
      width: 200,
      height: 200,
      // Circular image
      imageBuilder: (context, imageProvider) => CircleAvatar(
        backgroundImage: imageProvider,
      ),
    );
  }
}

For network images, it is recommended to use CachedNetworkImage, which can automatically cache images and improve loading performance.

other extensions