乐闻世界logo
搜索文章和话题

How to add image in Flutter

1个答案

1

Adding images in Flutter can be done in two primary ways: loading images from the web and loading images from local files. I'll walk through the implementation steps for both methods and provide corresponding example code.

1. Loading Images from the Web

When displaying images from the web, use the Image.network constructor in Flutter. This approach is intuitive and simple to implement. Here's an example implementation:

dart
import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { Widget build(BuildContext context) { return MaterialApp( title: 'Network Image Example', home: Scaffold( appBar: AppBar( title: Text('Loading Network Image'), ), body: Center( // Use Image.network to load network image child: Image.network('https://www.example.com/images/image.jpg'), ), ), ); } }

In this example, we build a basic Flutter application featuring a centered Image.network widget that loads and displays the image using the provided URL.

2. Loading Images from Local Files

To load images from the device's local storage, use the Image.asset method. First, specify the resource file path in the pubspec.yaml file of your Flutter project:

yaml
flutter: assets: - assets/images/local_image.jpg

Then, use Image.asset in your code to reference and display this local image:

dart
import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { Widget build(BuildContext context) { return MaterialApp( title: 'Local Image Example', home: Scaffold( appBar: AppBar( title: Text('Loading Local Image'), ), body: Center( // Use Image.asset to load local image child: Image.asset('assets/images/local_image.jpg'), ), ), ); } }

This example demonstrates how to load and display a local image file in a Flutter application.

With these two approaches, you can flexibly use web images or local images in your Flutter application as needed. These methods also support further customization, such as setting image scaling and fitting modes.

2024年7月1日 12:17 回复

你的答案