Flutter 图片加载
warning:
这篇文章距离上次修改已过190天,其中的内容可能已经有所变动。
在Flutter中,你可以使用Image
小部件来加载并显示图片。如果你想从网络加载图片,可以使用Image.network
构造函数。如果你想从本地资源加载图片,可以使用Image.asset
构造函数。
以下是一个简单的例子,展示如何在Flutter中使用Image.network
来加载并显示一张网络图片:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('图片加载示例'),
),
body: Center(
child: Image.network(
'https://example.com/path/to/your/image.jpg', // 替换为实际的图片URL
fit: BoxFit.cover,
width: 200,
height: 200,
),
),
),
);
}
}
在这个例子中,Image.network
用于加载一个网络图片,并通过fit
、width
和height
属性来指定图片的适配方式和尺寸。请确保替换图片URL为有效的网络图片地址。
如果你想从本地资源加载图片,请确保将图片文件添加到你的pubspec.yaml
文件中,并使用Image.asset
来加载它:
flutter:
assets:
- assets/images/my_image.jpg
然后在代码中使用:
Image.asset('assets/images/my_image.jpg'),
请注意,本地图片的路径是相对于pubspec.yaml
文件的。
评论已关闭