proper way to get widget height in SafeArea

后端 未结 4 1981
轮回少年
轮回少年 2021-02-07 02:01

I\'m trying to get the height of widget but it prints the same values

I/flutter (19253): full height: 976.0
I/flutter (19253): safe height: 976.0


        
相关标签:
4条回答
  • 2021-02-07 02:17

    Flutter 1.7.4

    Add this at top level of Widget...and you can get exact SafeArea height.

    final availableHeight = MediaQuery.of(context).size.height -
        AppBar().preferredSize.height -
        MediaQuery.of(context).padding.top -
        MediaQuery.of(context).padding.bottom;
    
    0 讨论(0)
  • 2021-02-07 02:28

    You can always use LayoutBuilder for such cases.

    child: SafeArea(
            child: new LayoutBuilder(
                builder: (BuildContext context, BoxConstraints constraints) {
                  // constraints variable has the size info
                  return Container();
                }
            ),
          ),
    

    for more info: https://www.youtube.com/watch?v=IYDVcriKjsw

    0 讨论(0)
  • 2021-02-07 02:34

    I know that there is right answer, but maybe someone is looking for safe area height, not height of safe area widget child, but only safe area top padding:

    var safePadding = MediaQuery.of(context).padding.top;
    
    0 讨论(0)
  • 2021-02-07 02:39

    to get the size of the SafeArea, you need to encapsulate inside a LayoutBuilder , and use constraints.maxHeight

    look at your own example modified:

    I/flutter (20405): full Screen height: 683.4285714285714
    I/flutter (20405): Screen height: 683.4285714285714
    I/flutter (20405): Real safe height: 659.4285714285714

    class _MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          debugShowCheckedModeBanner: false,
          home: Scaffold(body: _Body()),
        );
      }
    }
    
    class _Body extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        print('full Screen height: ${MediaQuery.of(context).size.height}');
        return Container(
          constraints: BoxConstraints.expand(),
          decoration: BoxDecoration(color: Colors.red),
          child: SafeArea(
            child: _SafeHeightWidget(),
          ),
        );
      }
    }
    
    class _SafeHeightWidget extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return LayoutBuilder(
          builder: (context, constraints) {
            print('Screen height: ${MediaQuery.of(context).size.height}');
            print('Real safe height: ${constraints.maxHeight}');
            return Container(
              color: Colors.lightBlue,
            );
          },
        );
      }
    }
    
    0 讨论(0)
提交回复
热议问题