Ad
How Can I Get Center Offsets Of A Screen In Flutter?
I am using a stack to pan a text using offset and positioned widget. I want to get the offset of the center. I tried
offset = Offset(screenWidth/2, screenHeight/2);
But this is not working, is there any other way possible to get the center coordinates/offset?
Ad
Answer
As @pskink commented use LayoutBuilder as a parent
; and @Jared Anderton answers is quite ok, but it will calculate the Scaffold
body, without considering other property like appBar
. Also @Hrvoje Čukman answer meet your requirement.
Another thing can be done just using Stack(alignment: Alignment.center,
it will align unaligned children.
The parent widget be LayoutBuilder
.
Widget build(BuildContext context) {
return LayoutBuilder(
builder: (context, constraints) {
Offset centerOffset =
Offset(constraints.maxWidth / 2, constraints.maxHeight / 2);
return Scaffold(
Another option is getting windowSize
from dart:ui
.
final Size windowSize = MediaQueryData.fromWindow(window).size;
late Offset screenOffset =
Offset(windowSize.width / 2, windowSize.height / 2);
class CenterOffset extends StatelessWidget {
const CenterOffset({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
final Size windowSize = MediaQueryData.fromWindow(window).size;
late Offset screenOffset =
Offset(windowSize.width / 2, windowSize.height / 2);
return LayoutBuilder(
builder: (context, constraints) {
Offset centerOffset =
Offset(constraints.maxWidth / 2, constraints.maxHeight / 2);
return Scaffold(
appBar: AppBar(),
body: LayoutBuilder(
builder: (context, chConstraints) {
Offset bodyBasedCenter = Offset(
chConstraints.maxWidth / 2, chConstraints.maxHeight / 2);
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text("window based center $screenOffset"),
Text("Parent based center $centerOffset"),
Text("body based center $bodyBasedCenter"),
],
),
);
},
));
},
);
}
}
Ad
source: stackoverflow.com
Related Questions
- → How do you create a 12 or 24 mnemonics code for multiple cryptocurrencies (ETH, BTC and so on..)
- → Flutter: input text field don't work properly in a simple example..... where am I wrong?
- → Can I customize the code formatting of Dart code in Atom?
- → Is it possible to develop iOS apps with Flutter on a Linux virtual machine?
- → Display SnackBar in Flutter
- → JSON ObjectMapper in Flutter
- → Material flutter app source code
- → TabBarSelection No such method error
- → How do I set the animation color of a LinearProgressIndicator?
- → Add different routes/screens to Flutter app
- → Is there a way to get the size of an existing widget?
- → How to share a file using flutter
- → Is there an easy way to find particular text built from RichText in a Flutter test?
Ad