面试题答案
一键面试关键类和方法
Scaffold
类:Flutter 中构建页面结构的基础类,其中的appBar
属性用于设置导航栏。Platform
类:用于检测当前运行的平台是 iOS 还是 Android。AppBar
类:用于定义导航栏的外观,其属性如backgroundColor
用于设置背景颜色,title
用于设置标题,titleTextStyle
用于设置标题字体样式等。
代码示例
import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart';
class PlatformSpecificAppBar extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: getPlatformSpecificAppBar(context),
body: Center(
child: Text('Content'),
),
);
}
AppBar getPlatformSpecificAppBar(BuildContext context) {
if (defaultTargetPlatform == TargetPlatform.iOS) {
return AppBar(
backgroundColor: Colors.white,
title: Text(
'iOS App',
style: TextStyle(color: Colors.black),
),
);
} else {
return AppBar(
backgroundColor: Colors.blue,
title: Text(
'Android App',
style: TextStyle(color: Colors.white),
),
);
}
}
}
在上述代码中,getPlatformSpecificAppBar
方法通过 defaultTargetPlatform
判断当前平台。如果是 iOS 平台,设置导航栏背景色为白色,标题颜色为黑色;如果是 Android 平台,设置导航栏背景色为蓝色,标题颜色为白色。Scaffold
的 appBar
属性调用这个方法来设置平台特定的导航栏样式。