Чтобы отобразить виджет Flutter в зависимости от ориентации устройства, вы можете использовать различные методы. Вот несколько подходов, которые вы можете рассмотреть:
- MediaQuery: Flutter предоставляет класс MediaQuery, который позволяет получать информацию о свойствах экрана устройства. Вы можете использовать
MediaQuery.of(context).orientation
, чтобы получить текущую ориентацию устройства и условно отображать различные виджеты на основе результата.
import 'package:flutter/material.dart';
class MyWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
final orientation = MediaQuery.of(context).orientation;
return orientation == Orientation.portrait
? Container(
// Widget for portrait orientation
)
: Container(
// Widget for landscape orientation
);
}
}
<ол старт="2">
import 'package:flutter/material.dart';
class MyWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return OrientationBuilder(
builder: (context, orientation) {
return orientation == Orientation.portrait
? Container(
// Widget for portrait orientation
)
: Container(
// Widget for landscape orientation
);
},
);
}
}
- LayoutBuilder: виджет LayoutBuilder можно использовать для получения доступных ограничений ширины и высоты родительского виджета. На основе этих ограничений вы можете решить, как отображать виджет.
import 'package:flutter/material.dart';
class MyWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return LayoutBuilder(
builder: (context, constraints) {
if (constraints.maxWidth > constraints.maxHeight) {
return Container(
// Widget for landscape orientation
);
} else {
return Container(
// Widget for portrait orientation
);
}
},
);
}
}