63

この記事は最終更新日から1年以上が経過しています。

@yu124choco

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

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

ユーザー登録して、Qiitaをもっと便利に使ってみませんか。
  1. あなたにマッチした記事をお届けします
    ユーザーやタグをフォローすることで、あなたが興味を持つ技術分野の情報をまとめてキャッチアップできます
  2. 便利な情報をあとで効率的に読み返せます
    気に入った記事を「ストック」することで、あとからすぐに検索できます
yu124choco

コメント

間違ってたらすみません。
以下の部分のコード、間違えてないでしょうか?

imagesフォルダ内の全ファイルを取り込みたい場合は次のように記述します。

コード中の「assets/」じゃなくて「images/」

0

編集リクエストがあるが、誤字のまま放置されているのでノイズになるので記事自体を削除してほしいですが、

  # ↓この部分を追加する↓
  assets:
    - assets/

  # ↓この部分を追加する↓
  assets:
    - images/
0
(編集済み)

@shinriyo images/ に修正しました。
ご指摘ありがとうございます。

imagesです。 by shinriyo 2020/08/26 11:03

1
あなたもコメントしてみませんか :)
ユーザー登録
すでにアカウントを持っている方はログイン