Skip to content

Instantly share code, notes, and snippets.

@alexcmgit
Created August 8, 2022 05:57
Show Gist options
  • Save alexcmgit/ffa4ca0bda81e4978d698ae0a28f007a to your computer and use it in GitHub Desktop.
Save alexcmgit/ffa4ca0bda81e4978d698ae0a28f007a to your computer and use it in GitHub Desktop.
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
debugShowCheckedModeBanner: false,
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return const Scaffold(
body: Sample(),
);
}
}
class Sample extends StatefulWidget {
const Sample({Key? key}) : super(key: key);
@override
State<Sample> createState() => _SampleState();
}
class _SampleState extends State<Sample> {
Offset offset = Offset.zero;
static const _kObjectSize = Size.square(100);
double get screenWidth => MediaQuery.of(context).size.width;
double get screenHeight => MediaQuery.of(context).size.height;
@override
Widget build(BuildContext context) {
return Stack(
children: [
Positioned(
left: offset.dx,
top: offset.dy,
child: Container(
color: Colors.red,
width: _kObjectSize.width,
height: _kObjectSize.height,
),
),
Positioned.fill(
child: GestureDetector(
onPanUpdate: (details) {
double limitX = (offset.dx + details.delta.dx)
.clamp(0, screenWidth - _kObjectSize.width)
.toDouble();
double limitY = (offset.dy + details.delta.dy)
.clamp(0, screenHeight - _kObjectSize.height)
.toDouble();
offset = Offset(limitX, limitY);
setState(() {});
},
),
),
],
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment