Skip to content

Instantly share code, notes, and snippets.

@plastic041
Created November 21, 2022 07:21
Show Gist options
  • Save plastic041/046328f77bc4d69a012819af7eb8325f to your computer and use it in GitHub Desktop.
Save plastic041/046328f77bc4d69a012819af7eb8325f to your computer and use it in GitHub Desktop.
flutter pan to adjust opacity
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
final String title;
const MyHomePage({
Key? key,
required this.title,
}) : super(key: key);
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
double _opacity = 0.0;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Container(
width: 200,
height: 200,
color: Colors.yellow,
child: GestureDetector(
child: FittedBox(
child: Center(
child: Opacity(
opacity: _opacity,
child: const Text(
"hello",
style: TextStyle(
fontSize: 40,
),
),
),
),
),
onPanUpdate: (details) {
double x = details.localPosition.dx;
double normX = normalize(x, 0, 200);
setState(() {
_opacity = normX;
});
},
),
),
),
);
}
}
double normalize(double x, double min, double max) {
if (min == max) {
throw UnsupportedError("Cannot divide by zero");
}
double normalized = (x - min) / (max - min);
return normalized.clamp(0, 1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment