Flutter 之基本控制元件
阿新 • • 發佈:2020-11-22
Flutter 中有很多 UI 控制元件,而文字、圖片和按鈕是 Flutter 中最基本的控制元件,構建檢視基本上都要使用到這三個基本控制元件
文字控制元件
文字是檢視系統中的常見控制元件,用於顯示一段特定樣式的字串,在 Flutter 中,文字展示是通過 Text 控制元件實現的
Text 支援的文字展示型別
- 單一樣式的文字 Text
- 混合樣式的富文字 Text.rich
單一樣式的文字 Text
- 控制整體文字佈局的引數:textAlign(文字對齊方式)、textDirection(文字排版方向)、maxLines(文字顯示最大行數)、overflow(文字截斷規則),等等。這些都是建構函式中的引數
- 控制文字展示樣式的引數:fontFamily(字型名稱)、fontSize(字型大小)、color(文字顏色)、shadows(文字陰影)、等等。這些都是建構函式中的引數 style 中的引數
混合樣式的富文字 Text.rich
- 把一段字串分為幾個片段來管理,給每個片段單獨設定樣式,使用 TextSpan 來實現
圖片
使用 Image 來載入不同形式、不同格式的圖片
- 載入本地資源圖片:Image.asset('images/logo.png');
- 載入本地(File 檔案)圖片:Image.file(File('/storage/test.png'));
- 載入網路圖片:Image.network('http://xxx/logo.png');
支援高階功能的圖片控制元件
- FadeInImage:提供了圖片佔位的功能,支援在圖片載入完成時淡入淡出的視覺效果;ImageCache 使用 LRU(Least Recently User:最近最少使用)演算法進行快取更新策略,並且預設最多儲存 1000 張圖片,最大快取限制為 100MB,當限定的空間已存滿資料時,把最久沒有被訪問到的圖片清除,圖片只快取在記憶體中
- CachedNetworkImage:不僅支援快取圖片到記憶體中,還支援快取到檔案系統中;載入過程佔位與載入錯誤佔位;自定義控制元件佔位
按鈕
通過按鈕,可以響應使用者的互動事件。Flutter 中提供了三個最基本的按鈕控制元件:FloatingActionButton、FlatButton、RaisedButton
- FloatingActionButton:圓形按鈕,一般出現在螢幕內容的前面
- FlatButton:扁平化的按鈕,預設透明背景
- RaisedButton:凸起的按鈕,預設帶有灰色背景
按鈕控制元件中的引數
- onPressed:設定點選回撥,如果 onPressed 引數為空,則按鈕處於禁用狀態,不響應使用者點選事件
- child:設定按鈕的內容,可以接收任意的 Widget
資源搜尋網站大全 http://www.szhdn.com 廣州VI設計公司https://www.houdianzi.com
以下為具體程式碼實現
void main() => runApp(MyBasiControl());
/**
* 經典控制元件
*/
class MyBasiControl extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: MyText(),
);
}
}
String content = '歡迎關注\nAndroid小白營\n在這裡我們可以一起成長\n';
class MyText extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Android小白營'),
),
body: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Text(
'以下為不同樣式的文字控制元件\n\n單一樣式文字 Text\n一:預設樣式\n' + content,
),
Text(
'二:自定義樣式:居中顯示,黑色背景,白色14號粗體字型\n' + content,
textAlign: TextAlign.center,
style: TextStyle(
color: Colors.white,
backgroundColor: Colors.black,
fontSize: 14,
fontWeight: FontWeight.bold,
),
),
Text.rich(TextSpan(children: [
TextSpan(
text: '\n富文字 Text.rich\n',
style: TextStyle(color: Colors.red, fontSize: 20)),
TextSpan(text: '歡迎關注\n'),
TextSpan(
text: 'Android小白營\n',
style: TextStyle(
color: Colors.blueAccent,
fontWeight: FontWeight.bold,
fontSize: 18)),
TextSpan(
text: '在這裡我們可以一起成長',
style: TextStyle(
backgroundColor: Colors.deepOrangeAccent,
color: Colors.cyanAccent,
fontSize: 16))
])),
FlatButton(
color: Colors.cyanAccent,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(18.0)),
onPressed: () {
Fluttertoast.showToast(msg: '測試點選事件');
},
colorBrightness: Brightness.light,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Icon(Icons.add_circle_outline),
Text('新增')
],
))
],
));
}
}