Last active
August 28, 2024 16:40
-
-
Save kumamotone/4b5e9c5ec705541662555c650ad469d5 to your computer and use it in GitHub Desktop.
Flutterアプリで低解像度の画像を表示し、ユーザーが画像を拡大したときに高解像度の画像をバックグラウンドで読み込み、読み込みが完了したら高解像度画像に置き換える仕組みの実装 https://chatgpt.com/share/c0e64dcf-8c6f-462c-b967-b1159cb99d18
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:flutter/material.dart'; | |
void main() { | |
runApp(const MyApp()); | |
} | |
class MyApp extends StatelessWidget { | |
const MyApp({super.key}); | |
@override | |
Widget build(BuildContext context) { | |
return MaterialApp( | |
title: 'High-Res Image Test', | |
theme: ThemeData( | |
primarySwatch: Colors.blue, | |
), | |
home: const ImageViewerScreen(), | |
); | |
} | |
} | |
class ImageViewerScreen extends StatefulWidget { | |
const ImageViewerScreen({super.key}); | |
@override | |
ImageViewerScreenState createState() => ImageViewerScreenState(); | |
} | |
class ImageViewerScreenState extends State<ImageViewerScreen> { | |
// Lorem Picsum のIDを使ったURL | |
String _currentImageUrl = | |
'https://picsum.photos/id/237/100/100'; // 低解像度の画像URL | |
bool _isHighResLoaded = false; | |
@override | |
Widget build(BuildContext context) { | |
return Scaffold( | |
appBar: AppBar( | |
title: const Text('High-Res Image Test'), | |
), | |
body: Center( | |
child: InteractiveViewer( | |
onInteractionStart: (details) { | |
if (!_isHighResLoaded) { | |
_loadHighResImage(); | |
} | |
}, | |
child: AspectRatio( | |
aspectRatio: 1.0, // アスペクト比を固定 | |
child: Image.network( | |
_currentImageUrl, | |
fit: BoxFit.cover, | |
), | |
), | |
), | |
), | |
); | |
} | |
void _loadHighResImage() async { | |
const highResImageUrl = | |
'https://picsum.photos/id/237/1300/1300'; // 高解像度の画像URL | |
final highResImage = Image.network(highResImageUrl); | |
// 高解像度画像をキャッシュにロード | |
await precacheImage(highResImage.image, context); | |
// 読み込み完了後に画像を置換 | |
setState(() { | |
_currentImageUrl = highResImageUrl; | |
_isHighResLoaded = true; | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment