面试题答案
一键面试- 使用
OrientationBuilder
OrientationBuilder
可以根据设备的方向(横屏或竖屏)来构建不同的布局。- 示例代码如下:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Orientation Adaptation'),
),
body: OrientationBuilder(
builder: (context, orientation) {
if (orientation == Orientation.portrait) {
return Container(
color: Colors.blue,
width: double.infinity,
height: 200,
child: Center(
child: Text('Portrait Mode'),
),
);
} else {
return Container(
color: Colors.green,
width: 200,
height: double.infinity,
child: Center(
child: Text('Landscape Mode'),
),
);
}
},
),
),
);
}
}
- 使用
LayoutBuilder
LayoutBuilder
可以根据父容器的约束来调整布局。结合设备方向和平台信息,能更好地适配不同场景。- 示例:
import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Layout Adaptation'),
),
body: LayoutBuilder(
builder: (context, constraints) {
bool isLandscape = constraints.maxWidth > constraints.maxHeight;
double containerWidth;
double containerHeight;
if (defaultTargetPlatform == TargetPlatform.iOS) {
if (isLandscape) {
containerWidth = 300;
containerHeight = double.infinity;
} else {
containerWidth = double.infinity;
containerHeight = 300;
}
} else if (defaultTargetPlatform == TargetPlatform.android) {
if (isLandscape) {
containerWidth = 250;
containerHeight = double.infinity;
} else {
containerWidth = double.infinity;
containerHeight = 250;
}
}
return Container(
color: Colors.orange,
width: containerWidth,
height: containerHeight,
child: Center(
child: Text('Adaptive Layout'),
),
);
},
),
),
);
}
}
- 使用
MediaQuery
MediaQuery
可以获取设备的屏幕尺寸、方向等信息。通过判断方向来调整布局。- 示例:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
var orientation = MediaQuery.of(context).orientation;
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('MediaQuery Adaptation'),
),
body: (orientation == Orientation.portrait)?
Container(
color: Colors.purple,
width: double.infinity,
height: 150,
child: Center(
child: Text('Portrait with MediaQuery'),
),
) :
Container(
color: Colors.yellow,
width: 150,
height: double.infinity,
child: Center(
child: Text('Landscape with MediaQuery'),
),
)
),
);
}
}
通过以上几种方式,可以在Flutter应用中根据设备方向和平台差异,合理布局Container
等Widget,以适配iOS和Android不同设备方向下的显示需求。