【Flutter】画像を表示する方法

Flutter

今回は、Flutter アプリで画像を表示する方法を2種類紹介します。

ネットにある画像を表示

以下の形式の Widget を配置することで、ネット上の画像を表示できます。

Image.network('画像のURL')

(使用例)

Image.network('https://flutter.github.io/assets-for-api-docs/assets/widgets/owl-2.jpg')

ローカル(アプリ内)の画像を表示

プロジェクトに「images」のようなわかりやすい名前のフォルダを作成して、そのフォルダに表示したい画像を置きます。

画像用フォルダの作成と画像ファイルの格納

pubspec.yaml の assets: の部分のコメントアウトを外して、アプリ内に持つ画像を指定します。

# The following section is specific to Flutter.
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.png  # sample.pngのみ指定
    - images/            # imagesフォルダに入っている全ての画像を指定したい場合はこちら

以下のような Widget を配置すると、画像が表示されます。

Image.asset('images/sample.png')

まとめ

今回は、Flutter アプリで画像を表示する方法を紹介しました!

  • ネット上の画像を表示 → Image.network
  • アプリ内の画像を表示 → Image.asset

以上で、【Flutter】画像を表示する方法 は終わりです。

参考

コメント

タイトルとURLをコピーしました