为了自定义一个包含fallbackWidth或fallbackHeight属性的组件,可以使用PreferredSize来构建我们的组件。当组件遇到无限制的约束时,PreferredSize会从fallbackWidth或fallbackHeight属性中获取默认值,同时在父级约束不可用时将使用该默认值进行布局。
以下是一个示例代码:
class CustomPreferredSize extends StatelessWidget implements PreferredSizeWidget {
final double fallbackHeight;
final double fallbackWidth;
final Widget child;
CustomPreferredSize({
Key? key,
required this.child,
this.fallbackHeight = kToolbarHeight,
this.fallbackWidth = double.infinity,
}) : assert(child != null),
assert(fallbackHeight != null),
assert(fallbackWidth != null),
super(key: key);
@override
Widget build(BuildContext context) {
return ConstrainedBox(
constraints: BoxConstraints(
minHeight: fallbackHeight,
minWidth: fallbackWidth,
),
child: child,
);
}
@override
Size get preferredSize => Size(fallbackWidth, fallbackHeight);
}
在上面的示例中,CustomPreferredSize是我们自定义的组件类,它实现了PreferredSizeWidget接口。我们传入了fallbackHeight和fallbackWidth,用于在没有边界约束时提供默认值。我们还传入了一个child widget来作为CustomPreferredSize的内容。
在build方法中,我们使用ConstrainedBox进行布局,将fallbackWidth和fallbackHeight作为BoxConstraints的最小值来约束它的子元素。这将确保即使父级约束尺寸不可用时,子元素也将具有fallbackWidth和fallbackHeight的默认尺寸。
在preferredSize中,我们返回了fallbackWidth和fallbackHeight作为CustomPreferredSize的首选尺寸。
使用时,我们可以将CustomPreferredSize作为一个普通的widget来使用,就像任何其他的静态尺寸widget一样。如果没有任何约束,CustomPreferredSize将使用fallbackWidth和fallbackHeight来决定其尺寸。否则,它将使用约束大小进行布局。
例如:
Widget build(BuildContext context) {
return Scaffold(
appBar: CustomPreferredSize(
fallbackHeight: 80, //设置高为80像素
child: AppBar(
title: Text('CustomPreferredSize Widget'),
backgroundColor: Colors.red,
),
),
body: Container(
color: Colors.blue,
width: double.infinity,
height: double.infinity,
child: Center(
child: Text('Hello, World!', style: TextStyle(fontSize: 30)),
),
),
);
}