proper way to get widget height in SafeArea

后端 未结 4 1978
轮回少年
轮回少年 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: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,
            );
          },
        );
      }
    }
    

提交回复
热议问题