前言
收集一些Flutter开发的小技巧,提升开发效率。
获取触摸点的坐标
class MyStatefulWidget extends StatefulWidget {
const MyStatefulWidget({Key? key}) : super(key: key);
@override
State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
bool _lightIsOn = false;
@override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
alignment: FractionalOffset.center,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
GestureDetector(
onPanStart: onPanStart,
child: Container(
color: Colors.yellow.shade600,
padding: const EdgeInsets.all(8),
child: Text(_lightIsOn ? 'TURN LIGHT OFF' : 'TURN LIGHT ON'),
),
),
],
),
),
);
}
void onPanStart(DragStartDetails details) {
RenderBox box = context.findRenderObject();
Offset point = box.globalToLocal(details.globalPosition);
print(point);
}
}
获取触摸点的坐标
class PngHome extends StatefulWidget {
const PngHome({Key? key}) : super(key: key);
@override
State<PngHome> createState() => _PngHomeState();
}
class _PngHomeState extends State<PngHome> {
GlobalKey globalKey = GlobalKey();
Future<void> _capturePng() async {
final RenderRepaintBoundary boundary = globalKey.currentContext!.findRenderObject()! as RenderRepaintBoundary;
final ui.Image image = await boundary.toImage();
final ByteData? byteData = await image.toByteData(format: ui.ImageByteFormat.png);
final Uint8List pngBytes = byteData!.buffer.asUint8List();
print(pngBytes);
}
@override
Widget build(BuildContext context) {
return RepaintBoundary(
key: globalKey,
child: Center(
child: TextButton(
child: const Text('Hello World', textDirection: TextDirection.ltr),
onPressed: _capturePng,
),
),
);
}
}
|