Flutter开发疑问:应给AppBar还是Container加圆角实现斜切样式?
斜切样式AppBar实现方案
要做出图里那种带斜切+圆角的AppBar,直接给AppBar配置自定义shape属性是最优解,没必要额外套Container(虽然用Container包裹内容再做裁剪也能实现,但AppBar本身的shape属性更适配导航栏的交互逻辑,不用自己重新布局返回键、标题这些元素)。
具体做法:
- 先写一个自定义的
ShapeBorder类,用来画出底部斜切+圆角的轮廓 - 把这个自定义形状赋值给AppBar的
shape属性就行
修改后的完整代码:
import 'package:flutter/material.dart'; import 'package:google_fonts/google_fonts.dart'; // 自定义AppBar形状,实现底部斜切+圆角效果 class CustomAppBarShape extends ContinuousRectangleBorder { @override Path getOuterPath(Rect rect, {TextDirection? textDirection}) { final path = Path(); // 左上角起点 path.moveTo(rect.left, rect.top); // 画到右上角 path.lineTo(rect.right, rect.top); // 右下角圆角过渡 path.arcToPoint( Offset(rect.right, rect.bottom - 20), radius: const Radius.circular(20), ); // 斜切到左下角位置 path.lineTo(rect.left + 40, rect.bottom); // 左下角圆角过渡 path.arcToPoint( Offset(rect.left, rect.bottom - 20), radius: const Radius.circular(20), clockwise: false, ); // 闭合路径回到起点 path.close(); return path; } } class SignUpPage extends StatelessWidget { const SignUpPage({super.key}); @override Widget build(BuildContext context) { return Scaffold( appBar: PreferredSize( preferredSize: const Size.fromHeight(150), child: AppBar( elevation: 0, leading: IconButton( icon: const Icon(Icons.arrow_back), color: Colors.black, onPressed: () {}, ), actions: [ TextButton( onPressed: () {}, child: Text( 'Skip', style: GoogleFonts.halant( textStyle: const TextStyle( fontSize: 16, fontWeight: FontWeight.w600, color: Colors.black, ), ), ), ), ], backgroundColor: Colors.amber, title: Text( 'Sign up', style: GoogleFonts.halant( textStyle: const TextStyle( fontSize: 32, fontWeight: FontWeight.w500, color: Colors.black, ), ), ), centerTitle: true, // 应用自定义形状 shape: CustomAppBarShape(), ), ), body: const Center(child: Text('Sign Up Content')), ); } }
小提示:
- 要是想调整斜切的角度、圆角大小,直接改
CustomAppBarShape里的坐标数值就行 - 如果你非要用Container实现,也可以把AppBar的子元素(返回键、标题、按钮)放到Container里,给Container加
clipBehavior: Clip.antiAlias和自定义CustomClipper,但这样得自己手动布局导航栏元素,不如用AppBar的shape属性省心
内容的提问来源于stack exchange,提问作者Joey
相关产品推荐
相关产品推荐

