skip to Main Content

I was trying to find the heights of individual widget in listview. Method I followed is as followed-

  1. Make a list of global keys and assign it to individual container widget.
  2. Then use this function function
  3. It is giving me error that currentContext is not defined Error

2

Answers


  1. You should use a GlobalKey and template it depending on the state it is holding if this is the case.

    // If you are holding a statefulWidget
    final myKey = GlobalKey<YourState>();
    
    // else
    final myKey = GlobalKey();
    ...
    RenderBox renderBox = myKey.currentContext.findRenderObject();
    

    You can also use the LayoutBuilder to wrap your child widget with and get their height.

    Login or Signup to reply.
  2. This is valid code calculateHeight() fill fix ur problem.

    
    
    class MyHomePage extends StatefulWidget {
      const MyHomePage({
        super.key,
      });
    
      @override
      State<MyHomePage> createState() => _MyHomePageState();
    }
    
    class _MyHomePageState extends State<MyHomePage> {
      final GlobalKey _key = GlobalKey<FormState>();
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
            body: Center(
          child: SizedBox(
            key: _key,
            width: 200,
            height: 200,
          ),
        ));
      }
    
      double calculateHeight() {
        final renderObject = _key.currentContext?.findRenderObject();
        if (renderObject == null) return 0;
        if (renderObject is! RenderBox) return 0;
        return renderObject.size.height;
      }
    }
    
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search