How to detect orientation change in layout in Flutter?

后端 未结 6 1373
天命终不由人
天命终不由人 2020-12-09 07:56

How to find out Orientation is portrait or landscape in Flutter

if(portrait){
  return ListView.builder()
}else{
  return GridView.count()
}
相关标签:
6条回答
  • In order to determine the Orientation of the screen, we can use the OrientationBuilder Widget. The OrientationBuilder will determine the current Orientation and rebuild when the Orientation changes.

    new OrientationBuilder(
      builder: (context, orientation) {
        return new GridView.count(
          // Create a grid with 2 columns in portrait mode, or 3 columns in
          // landscape mode.
          crossAxisCount: orientation == Orientation.portrait ? 2 : 3,
        );
      },
    );
    

    you can find the complete example here: https://flutter.io/cookbook/design/orientation/

    0 讨论(0)
  • 2020-12-09 08:00

    it's quite easy

    if (MediaQuery.of(context).orientation == Orientation.portrait){
        // is portrait
    }else{
    // is landscape
    }
    
    0 讨论(0)
  • 2020-12-09 08:10

    You can use MediaQuery to check orientation:

    var isPortrait = MediaQuery.of(context).orientation == Orientation.portrait
    
    0 讨论(0)
  • 2020-12-09 08:10

    For completeness sake, I would like to add another way to detect orientation in Flutter. Two ways to detect have been mentioned in the answers already. They are

    1. Media Query
    2. Orientation Builder

    There is a third way which I came across when learning Flutter from Responsive Design video (skip to minute 2:34) by Google Engineers. It's called Layout Builder. Here is short snippet:

    return Padding(
        padding: _padding,
        child: LayoutBuilder(
            builder: (BuildContext context, BoxConstraints constraints) {
                if(constraints.maxHeight > constraints.maxWidth) {
                    return _getPortraitLayout();
                }
                else {
                    return _getLandscapeLayout();
                }
            },
        ),
    );
    
    0 讨论(0)
  • 2020-12-09 08:11
    @override
    Widget build(BuildContext context) {
      return Scaffold(
        body: OrientationBuilder(builder: (_, orientation) {
          if (orientation == Orientation.portrait)
            return _buildPortraitLayout(); // if orientation is portrait, show your portrait layout
          else
            return _buildLandscapeLayout(); // else show the landscape one
        }),
      );
    }
    
    0 讨论(0)
  • 2020-12-09 08:22
    OrientationBuilder(
    
    
     builder: (context, orientation) {
          return orientation == Orientation.portrait
              ? SafeArea(
              child: Scaffold(
                  body: PortraitMode(context)
              )
          )
              : LandscapeMode(context);
    
        }
    );
    
    0 讨论(0)
提交回复
热议问题