作為一個(gè)習(xí)慣用 html + css 的前端開(kāi)發(fā),學(xué)習(xí) flutter 的過(guò)程有點(diǎn)痛苦。flutter 寫(xiě)頁(yè)面怎么就這么難。遇到一個(gè)莫名其妙的問(wèn)題,應(yīng)該后面還會(huì)遇到,所以文章命名《莫名其妙的 flutter》系列。
直接說(shuō)問(wèn)題,我想做一個(gè)固定在頁(yè)面底部的懸浮按鈕。作為前端,fixed 搞定。好了,現(xiàn)在開(kāi)始用 flutter。
用 vs 創(chuàng)建一個(gè)新項(xiàng)目,直接 stack 嵌套一個(gè) positioned,嵌套一個(gè) FlatButton。不得不吐槽 flutter 嵌套確實(shí)太深。然后給一個(gè)簡(jiǎn)單的背景色,看看效果。
@override
Widget build(BuildContext context) {
final size = MediaQuery.of(context).size;
return Scaffold(
body: Stack(
alignment: Alignment.topCenter,
children: <Widget>[
...
Positioned(
left: 0,
bottom: 0,
child: FlatButton(
onPressed: () => {},
child: Container(
width: size.width,
height: 50,
alignment: Alignment.center,
decoration: BoxDecoration(color: Colors.pink),
child: Text(
"按鈕",
style: TextStyle(color: Colors.white, fontSize: 22),
),
),
),
)
],
),
);
}

細(xì)心的我,一下子就發(fā)現(xiàn)了,按鈕左邊沒(méi)有對(duì)齊啊。怎么回事,第一次用絕對(duì)定位,肯定是絕對(duì)定位不熟,哪里沒(méi)寫(xiě)對(duì)。找了很久,沒(méi)有解決。那試試 Container 偽裝成一個(gè)按鈕呢。看看效果:
...
Positioned(
left: 0,
bottom: 0,
child: GestureDetector(
onTap: () => {},
child: Container(
width: size.width,
height: 50,
alignment: Alignment.center,
decoration: BoxDecoration(color: Colors.pink),
child: Text(
"按鈕",
style: TextStyle(color: Colors.white, fontSize: 22),
),
),
),
)
...

果然就這么好了,這才明白是 FlatButton 的原因。一頓思考,看看文檔是不是哪里用錯(cuò)了??吹?a target="_blank">文檔才發(fā)現(xiàn),原來(lái)是 padding。FlatButton默認(rèn) padding 為 8。破案了。

padding 設(shè)為 0 ,看看效果。
...
Positioned(
left: 0,
bottom: 100,
child: FlatButton(
padding: EdgeInsets.all(0),
onPressed: () => {},
child: Container(
width: size.width,
height: 50,
alignment: Alignment.center,
decoration: BoxDecoration(color: Colors.pink),
child: Text(
"按鈕:padding 0",
style: TextStyle(color: Colors.white, fontSize: 22),
),
),
),
),
Positioned(
left: 0,
bottom: 0,
child: FlatButton(
onPressed: () => {},
child: Container(
width: size.width,
height: 50,
alignment: Alignment.center,
decoration: BoxDecoration(color: Colors.pink),
child: Text(
"按鈕",
style: TextStyle(color: Colors.white, fontSize: 22),
),
),
),
)
...

一個(gè)很簡(jiǎn)單的問(wèn)題,分享出來(lái),希望對(duì)你有幫助。