LoginSignup
124
94

More than 3 years have passed since last update.

Flutterで画像を表示する方法【まとめ】

Last updated at Posted at 2019-04-06

2019年2月からFlutterの学習を始め、かなり将来性がありそうだと思ったので、学んだことを逐一記事に残していきたいと思っています。

Flutterとは? → https://speakerdeck.com/najeira/iosliang-dui-ying-falseapurikai-fa-2

今回は、
Flutterで画像を表示する方法について2種類の方法をメモします。
1. アプリ内(アセット)の画像を表示する
2. ネットから画像をダウンロードして表示させる

アプリ内(アセット)の画像を表示する

① 画像を配置する
pubspec.yamlを編集する
③ Image Widgetを配置する

画像を配置して、アプリに認識させる必要があります。
↓↓

① 画像を配置する


プロジェクト直下にimagesフォルダを作成して、表示したい画像をその中に入れます。

pubspec.yamlを編集する

pubspec.yaml
flutter:

  # The following line ensures that the Material Icons font is
  # included with your application, so that you can use the icons in
  # the material Icons class.
  uses-material-design: true

  # To add assets to your application, add an assets section, like this:
  # ↓この部分を追加する↓
  assets:
    - images/sample.jpg

flutterブロックの中にassets以下の内容を追加します。
imagesフォルダ内の全ファイルを取り込みたい場合は次のように記述します。

pubspec.yaml
flutter:

  # The following line ensures that the Material Icons font is
  # included with your application, so that you can use the icons in
  # the material Icons class.
  uses-material-design: true

  # To add assets to your application, add an assets section, like this:
  # ↓この部分を追加する↓
  assets:
    - images/

③ Image Widgetを配置する

main.dart
class _MyHomePageState extends State<MyHomePage> {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        // ここを追加
        child: Image.asset('images/sample.jpg'),
      ),
    );
  }
}

Image.asset(ファイル名) でWidgetとして追加できます。
assets/で指定した時も同様のパス指定をします。

ネットから画像をダウンロードして表示させる

① Image Widgetを配置する

コードを1行書くだけです。
↓↓

① Image Widgetを配置する

main.dart
class _MyHomePageState extends State<MyHomePage> {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Image.network('https://yu1204eng.work/images/sample.jpg'),
      ),
    );
  }
}

たったこれだけで表示してくれます...!

非常に簡単に画像を表示させることが出来ました。

<参考>
https://flutter.dev/docs/development/ui/assets-and-images
https://nzigen.com/flutter-reference/2018-04-16-image.html

124
94
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
124
94