Skip to content

Instantly share code, notes, and snippets.

@Rahiche
Created October 31, 2024 13:39
Show Gist options
  • Save Rahiche/5ef9b7f49e26a1a0cc889568c1937308 to your computer and use it in GitHub Desktop.
Save Rahiche/5ef9b7f49e26a1a0cc889568c1937308 to your computer and use it in GitHub Desktop.
import 'dart:async';
import 'dart:ui' as ui;
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: 'Selective Focus',
theme: ThemeData.dark(
useMaterial3: true,
),
home: const SelectiveFocus(),
);
}
}
class SelectiveFocus extends StatefulWidget {
const SelectiveFocus({super.key});
@override
State<SelectiveFocus> createState() => _SelectiveFocusState();
}
class _SelectiveFocusState extends State<SelectiveFocus> {
@override
Widget build(BuildContext context) {
return SelectiveFocusImage();
}
}
class SelectiveFocusImage extends StatefulWidget {
const SelectiveFocusImage({super.key});
@override
State<SelectiveFocusImage> createState() => _SelectiveFocusImageState();
}
class _SelectiveFocusImageState extends State<SelectiveFocusImage> {
ui.Image? _image;
static const imageUrl = 'https://i.imgur.com/PVxynOu.png';
@override
void initState() {
super.initState();
_loadImage();
}
Future<void> _loadImage() async {
try {
final completer = Completer<ui.Image>();
final imageStream =
const NetworkImage(imageUrl).resolve(ImageConfiguration.empty);
imageStream.addListener(ImageStreamListener(
(info, _) => completer.complete(info.image),
onError: (error, _) => completer.completeError(error),
));
_image = await completer.future;
setState(() {});
} catch (e) {
debugPrint('Error loading image: $e');
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Selective Focus Image')),
body: Center(
child: Container(
child: _image == null
? const CircularProgressIndicator()
: CustomPaint(
size: Size(
_image!.width.toDouble(),
_image!.height.toDouble(),
),
painter: InteractiveImagePainter(
image: _image!,
),
),
),
),
);
}
}
class InteractiveImagePainter extends CustomPainter {
final ui.Image image;
const InteractiveImagePainter({required this.image});
@override
void paint(Canvas canvas, Size size) {
canvas.drawImage(image, Offset.zero, Paint());
}
@override
bool shouldRepaint(InteractiveImagePainter oldDelegate) =>
image != oldDelegate.image;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment