Flutter에서 로컬 이미지를 표시하기 위해서는 이미지를 저정할 폴더가 필요하다.
pubspec.yaml
파일에서 해당 부분을 찾아 주석을 해제하고 수정해준다. 폴더 이름은 assets
이라고 정했다.
# To add assets to your application, add an assets section, like this:
assets:
- assets/bunny.gif
- assets/profile.png
- assets/ #이렇게 폴더를 지정해도된다.
화면에 표시하기위해 main.dart
를 수정한다.
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
debugShowCheckedModeBanner: false,
home: Home(),
);
}
}
class Home extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Image'),
),
body: Center(
child: Image(image: AssetImage('assets/profile.png')),
),
);
}
}
이미지를 표시하기 위해 Image 위젯을 사용하며, 로컬 이미지를 사용할 때에는 AssetImage 위젯을 사용하여, 표시하고자 하는 로컬 이미지를 지정한다.
Image(image: AssetImage('assets/profile.png'))
Image(
image: AssetImage('assets/profile.png'),
width: 200,
height: 100,
fit: BoxFit.fill,
)
Image 위젯의 다양한 옵션을 사용하여 이미지를 표시할 수 있다.
다음과 같이도 사용할 수 있다.
Image.asset(
'assets/profile.png',
width: 200,
height: 100,
fit: BoxFit.fill,
)