Irbisa · Cheatsheet
Images, Video & Camera
Image pipeline, ImageCache, decode sizing, video_player, camera, audio, EXIF, thumbnails
How does Flutter choose between 1x, 2x and 3x versions of an image asset, and what goes wrong if you ship only one?
# pubspec.yaml: list the main file (or its folder); variants are found automaticallyflutter: assets: - assets/images/logo.png # On disk:…How do you display an SVG in Flutter, and why can't the
Imagewidget show it?import 'package:flutter_svg/flutter_svg.dart'; Widget emptyState() => SvgPicture.asset( 'assets/icons/empty_state.svg', // declared under flutter: assets: width: 160, colorFilter: const ColorFilter.mode(Colors.grey, BlendMode.srcIn),…How do you play an audio file in Flutter, and what must you do with the player when the screen closes?
class DingButton extends StatefulWidget { const DingButton({super.key}); @override State<DingButton> createState() => _DingButtonState();}…How does
Image.networkload and cache an image, and what roles doImageProvider,ImageStreamandImageCacheplay?A grid of full-resolution photos runs out of memory even though
imageCacheis capped at 100 MB. Why, and how do you fix it?class PhotoGrid extends StatelessWidget { const PhotoGrid({super.key, required this.urls}); final List<String> urls; @override Widget build(BuildContext context) {…This avatar is sharp on an old phone but blurry on a new one, and some photos look squashed. What is wrong with the code?
Widget avatar(String url) { return ClipOval( child: Image.network( url, width: 96, height: 96, fit: BoxFit.cover, cacheWidth: 96, cacheHeight: 96, ), );}You precache the hero image like this, yet the detail page still shows the placeholder first. Why?
Future<void> openDetails(BuildContext context, Product p) async { await precacheImage(NetworkImage(p.heroUrl), context); if (!context.mounted) return; Navigator.of(context).push(MaterialPageRoute( builder: (_) => Image.network( p.heroUrl, cacheWidth: 1080, loadingBuilder: (context, child, progress) => progress == null ? child : const HeroPlaceholder(), ), ));}What does
cached_network_imageadd overImage.network, and what do you still have to configure yourself?final feedCache = CacheManager( Config( 'feedImages', stalePeriod: const Duration(days: 7), // unused files are deleted after 7 days; freshness comes from Cache-Control maxNrOfCacheObjects: 2000, ),…Find the bug: after the user uploads a new avatar, the profile keeps showing the old photo until the app restarts.
class _ProfileHeaderState extends State<ProfileHeader> { late User _user = widget.user; Future<void> _changeAvatar(Uint8List cropped) async { // The server overwrites users/<id>/avatar.jpg and returns the updated user. final updated = await widget.api.uploadAvatar(_user.id, cropped); if (!mounted) return; setState(() => _user = updated); } @override Widget build(BuildContext context) => CircleAvatar( radius: 48, backgroundImage: NetworkImage(_user.avatarUrl), );}How do you let the user pick a photo or take one with
image_picker, and which permissions does it need on iOS and Android?final _picker = ImagePicker(); Future<XFile?> pickPhoto({required bool fromCamera}) { return _picker.pickImage( source: fromCamera ? ImageSource.camera : ImageSource.gallery, maxWidth: 2048, // resized natively, before Dart sees it…Photos uploaded from the phone show up rotated on the website. Why, and how do you fix it before upload?
Future<Uint8List> prepareForUpload(String path) async { final bytes = await FlutterImageCompress.compressWithFile( path, minWidth: 2048, // shrinks until the shorter side is 2048; never upscales minHeight: 2048, quality: 82,…Compressing a photo before upload freezes the UI for a second or two. Why doesn't
awaithelp, and how do you fix it?// wrong: runs on the UI isolate; no frames until it returns.Future<Uint8List> shrinkOnUiIsolate(Uint8List bytes) async { final decoded = img.decodeImage(bytes)!; return img.encodeJpg(img.copyResize(decoded, width: 2048), quality: 82);}…How do you play a video with
video_player, and what do you need to handle in the controller's lifecycle?class ClipPlayer extends StatefulWidget { const ClipPlayer({super.key, required this.url}); final Uri url; @override State<ClipPlayer> createState() => _ClipPlayerState();…This clip restarts from the beginning and memory grows every time the parent rebuilds. What is wrong with the widget?
class ClipView extends StatelessWidget { const ClipView({super.key, required this.url}); final Uri url; @override Widget build(BuildContext context) { final controller = VideoPlayerController.networkUrl(url) ..initialize() ..play(); return AspectRatio( aspectRatio: 16 / 9, child: VideoPlayer(controller), ); }}What does it take for audio to keep playing with the screen locked and show lock-screen controls, on iOS, Android and in Dart?
// Info.plist: UIBackgroundModes = [audio]// AndroidManifest.xml: FOREGROUND_SERVICE and FOREGROUND_SERVICE_MEDIA_PLAYBACK,// plus audio_service's service with foregroundServiceType="mediaPlayback".late final AudioHandler audioHandler; Future<void> main() async {…Find the bug: after the app comes back from the background, the camera preview stays black and the log shows a
CameraException.class _ScannerState extends State<Scanner> with WidgetsBindingObserver { late final _camera = CameraController(widget.camera, ResolutionPreset.medium) ..initialize().then((_) => mounted ? setState(() {}) : null); // initState: addObserver. dispose: removeObserver, _camera.dispose() // build: CameraPreview(_camera) @override void didChangeAppLifecycleState(AppLifecycleState state) { // free the camera for other apps if (state == AppLifecycleState.inactive) _camera.dispose(); if (state == AppLifecycleState.resumed) { _camera.initialize(); // take it back } }}Where should image resizing happen (on the client, in a CDN image service, or in the upload pipeline), and why?
Does
video_playercover adaptive streaming (HLS/DASH) and DRM, and what do you use when it doesn't?With the
cameraplugin, how do you analyse frames fromstartImageStreamwithout making the preview stutter?CameraController createController(CameraDescription camera) => CameraController( camera, ResolutionPreset.medium, // enough for detection, far less work per frame enableAudio: false, imageFormatGroup: Platform.isAndroid ? ImageFormatGroup.nv21 : ImageFormatGroup.bgra8888,…To show video or camera frames, when do you use a
Textureand when a platform view, and what does each cost per frame?How would you design offline downloads of video or podcast episodes: what to download, where to store it, and how to keep the storage bounded?