Flutter Center使用方法
二话不说直接上代码
直接把要居中的控件放在Center内即可
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Text('Hello World!')
)// This trailing comma makes auto-formatting nicer for build methods.
);
}
}
就是这么简单,没了
啥,还想多唠叨点,行
看源码可知Center是继承Align,只是隐藏了alignment参数,而Align中alignment参数的默认值是Alignment.center,所以就实现了居中
class Center extends Align {
/// Creates a widget that centers its child.
const Center({ Key key, double widthFactor, double heightFactor, Widget child })
: super(key: key, widthFactor: widthFactor, heightFactor: heightFactor, child: child);
}
我们可以模仿以上代码自己实现一个TopRight的控件,让子控件显示在右上角
class TopRight extends Align {
const TopRight({ Key key, double widthFactor, double heightFactor, Widget child })
: super(key: key, alignment: Alignment.topRight, widthFactor: widthFactor, heightFactor: heightFactor, child: child);
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: TopRight(
child: Text('Hello World!')
)// This trailing comma makes auto-formatting nicer for build methods.
);
}
}