[Flutter/Dart]画像取得待ちの間は異なる表示方法とする
やりたいこと
画像を表示するWidgetがある
画像はリモートのストレージから取得する
取得するまでは時間がかかるので、その間は待機中である旨を伝える表示としたい。 よくあるのはぐるぐる
解決策
FutureBuildrで表示を切り替えましょう。
FutureBuilder<ImageProvider>(
future: getImage(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return CircularProgressIndicator();
}
if ((snapshot.hasError) || (!snapshot.hasData)){
//Error handling
}
return Container(
width: 100,
height: 100,
decoration: BoxDecoration(
borderRadius: const
BorderRadius.all(Radius.circular(10)),
image: DecorationImage(
fit: BoxFit.contain,
image: snapshot.data!
),
)
);
}
)
Future<ImageProvider> getImage()async{
//method to get image from remote storage
}
異なる画像ソースで処理を共通化
上記では画像のソースとしてリモートストレージを考えたが、ローカルファイルの場合もあるし、assetにある画像ファイルの場合もある。これらの異なるソースに対して処理を共通化するにはどうしたらいいでしょうか。
以下のようなポリモーフィックなクラスを作りましょう。
抽象クラスImageSourceクラスを作る
ImageSourceクラスにFuture<ImageProvider> getImage()を定義
ImageSourceクラスを継承した具象クラスLocalImage、RemoteImageを定義し、getImageの実装を各々追加
画像表示Widgetは、ImageSourceのインスタンスを引数にとり、getImage()を呼んでImageProviderを取得
abstract class ImageSource{
String path; //画像パス
Future<ImageProvider> getImage(); //画像取得
}
//ローカルストレージのファイル
class LocalImage extends ImageSource{
@override
Future<ImageProvider> getImage()async{
return FileImage(File(path));
}
}
//リモートストレージのファイル
class RemoteImage extends ImageSource{
@override
Future<ImageProvider> getImage()async{
String _downloadPath = await _downLoadFile(); //ファイルダウンロード処理
return NetworkImage(_downloadPath);
}
}
Widget ImageWidget(ImageSource imgSrc){
return FutureBuilder<ImageProvider>(
future: imgSrc.getImage(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return CircularProgressIndicator();
}
if ((snapshot.hasError) || (!snapshot.hasData)){
//Error handling
}
return Container(
width: 100,
height: 100,
decoration: BoxDecoration(
borderRadius: const
BorderRadius.all(Radius.circular(10)),
image: DecorationImage(
fit: BoxFit.contain,
image: snapshot.data!
),
)
);
}
)
}
LocalImageの場合、getImage()をasyncにする必要はないですが、RemoteImageと都合を合わせるためにasyncにしています。
(ぐるぐるがほとんど表示されずに画像が表示されるだけです)
最新記事
すべて表示現象 あるアイコンは長押し時に所定の動作を実行します これを実現するために、GestureDetectorのonLongPressに処理を登録していました しかしいざビルドしてみると、アイコンが表示されたタイミングで処理が実行されてしまいました 以下が該当部分のソースコードです。 さあ、どこが間違っているでしょう? return GestureDetector( child: Containe
前提 以下のようなケースを考えます。 アイテムの一覧がある ある1つのアイテムの詳細を表示するページがある 詳細ページではそのアイテムの削除ができる 削除したら他のページ(一覧ページなど)に戻る これはアプリではよくあるパターンだと思います。 課題 reduxパターンを用いている、より具体的にはProviderで状態を管理している場合、以下のような構成になっているのではないでしょうか? アプリ全体
やりたいこと Reduxで状態管理をする。状態はAppStateとする。 アプリ開始時にリモートのデータベースからデータの取得を開始 データを取得 取得中は待機マークを表示 取得したデータからAppStateを作成 作成したAppStateを元にUIを描画 方法 3、4、5を実現するためには、「取得完了」のフラグをAppStateに追加しましょう(※1)。 ビューはこのフラグを見て表示を切り替えま