1

Here I have a center Offset value that is where I need to position the widget, I have positioned the widget with the help of Positioned widget and moved the widget to the center with the help of FractionalTranslation widget, and moved it to the center offset.

But here some part widgets get rendered outside the canvas, so I want to ignore the rendering of the widget which is rendered outside the screen. If I get the size of the widget, I can be able to ignore the render, but I am struggling with getting widget height and width.

I have attached the code snippet below for reference.

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,
      ),
      home: const MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Stack(children: [
        Positioned(
          left: 20,
          top: 150,
            child: FractionalTranslation(translation: const Offset(-0.5, -0.5),child: Container(
          color: Colors.grey,
          child: const Text('Widget size'),
        )))
      ]),
    );
  }
}

Thanks.

yuva
  • 436
  • 4
  • 9
  • Always put such widgets inside row/column and use expanded for them, you can even use flexible so if they are about to go beyond screen limits, expanded will take care of them. Explore the expanded widget. – Tech Nerd Apr 26 '22 at 21:43

3 Answers3

0

Check this solution, a bit complicated but worth a try:

import 'package:flutter/material.dart';
import 'package:flutter/scheduler.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,
      ),
      home: const MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  double height = 0.0;
  double width = 0.0;
  final GlobalKey _globalKey = GlobalKey();

  @override
  void initState() {
    SchedulerBinding.instance!.addPostFrameCallback((timeStamp) {
      height = _globalKey.currentContext!.size!.height;
      width = _globalKey.currentContext!.size!.width;
      setState(() {});
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Stack(children: [
        Positioned(
            left: 20,
            top: 150,
            key: _globalKey,
            child: FractionalTranslation(
                translation: const Offset(-0.5, -0.5),
                child: Container(
                  color: Colors.grey,
                  child: Text("      $height $width"),//added spaces so you can see it
                )))
      ]),
    );
  }
}
Bymolda
  • 49
  • 6
  • Thanks for your response. I have tried this but the addPostFrameCallback is not working at the runtime. So can you please suggest any other way to get the widget size at run time. – yuva Apr 29 '22 at 03:55
  • It's working for me. You can check it in here [link](https://dartpad.dev/?id=fe9fd743a12fcc1639478b2ffe40fc2e) – Bymolda Apr 29 '22 at 09:37
  • Yes, it is working fine. But I want to find widget size without calling setState because it will cause the performance. E.g, if I have 5 widgets in the list and get the size of each widget it causes the performance of the application. Can you please help me to find the widget size without calling setState(). – yuva May 08 '22 at 08:33
-1
To get the screen width and height:

Screen width  : MediaQuery.of(context).size.width
Screen height : MediaQuery.of(context).size.height

To center the widget to the screen it is easy as below code.Center Widget do the trick

@override
  Widget build(BuildContext context) {
    return Scaffold(
      key: keyRed,
      appBar: AppBar(),
      body: Center(
        child: Container(
          color: Colors.grey,
          child: const Text('Widget size'),
        ),
      ),
    );
  }
harizh
  • 326
  • 1
  • 13
-1

I already have at least one problem with the way you centre a container. However, I have tried to get a handle on the size option of a widget. There are 02 approaches to this with Flutter.

  1. Use MediaQuery for a given context
  • final double ScreenWidth : MediaQuery.of(context).size.width
  • final double ScreenHeight : MediaQuery.of(context).size.height
  1. Use constraints parameter in a LayoutWidget. Here is the sample with the LayoutWidget. I hope these two approaches will help you.
    Scaffold(
      appBar: AppBar(),
      body: Stack(children: [
        Positioned(
            left: 20,
            top: 150,
            child: FractionalTranslation(
              translation: const Offset(-0.5, -0.5),
              child: LayoutBuilder(
                builder: (BuildContext context, BoxConstraints constraints) {
                  if (constraints.maxWidth < 600) {
                    return Container(
                      color: Colors.teal,
                      width: 150,
                      height: 150,
                      child: const Text('Widget size'),
                    );
                  } else {
                    return Container(
                      color: Colors.grey,
                      width: 350,
                      height: 350,
                      child: const Text('Widget size'),
                    );
                  }
                },
              ),
            ))
      ]),
    );
Drogbut
  • 37
  • 4