如需轉載,請註明出處:Flutter學習筆記(38)--自定義控件之組合控件html
在開始以前想先寫點其餘的,emm...就是今天在學習到自定義控件的時候,因爲自定義控件這塊一直是個人短板,不管是Android原生開發仍是Flutter,對我來講都是致命傷,心裏深處不知道爲何就是很抵觸...學着學着就忽然感受特煩躁,app
不知道本身如今學這些有什麼用,有什麼意義,工做中的項目也用不上,年前換工做的時候,去快手面過Flutter的崗位,很遺憾二面沒有經過,我本身也不死心,想好好準備準備再去試一下,也算是本身的一個小目標吧。ide
夢想老是要有的,萬一不當心實現了呢!隨便發幾句牢騷,平復下心情,革命還沒有成功,同志仍需努力!按照計劃一步一步來吧!佈局
----------------------------------------------------------正文-------------------------------------------------------------post
Flutter中的自定義控件其實和Android中的很相似,都有組合控件、自繪控件。學習
組合控件就是將通用的控件封裝起來,其內部由多個小控件組合起來實現的,好比說公用的title欄,其實和咱們平時寫頁面的時候沒什麼區別。ui
自繪控件就是繼承RenderObjectWidget,而後經過提供給咱們的Paint和Canves進行佈局和繪製。今天就寫一下組合控件實現的思路和具體作法。this
下面咱們寫一個例子,就是一個簡單的點贊,Container容器裏面有一個icon一個text,點擊icon,數字增長。url
import 'package:flutter/material.dart'; class CombinationWidget extends StatefulWidget { @required Color color; @required double width; @required double height; CombinationWidget(this.color, this.width, this.height); @override State<StatefulWidget> createState() { return _CombinationWidgetState(color, width, height); } } class _CombinationWidgetState extends State { Color _color; double _width; double _height; var _startCount = 0; _CombinationWidgetState(this._color, this._width, this._height); @override Widget build(BuildContext context) { return Center( child: ClipOval( child: Container( color: _color, width: _width, height: _height, child: Row( mainAxisSize: MainAxisSize.max, mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ IconButton( icon: Icon( Icons.thumb_up, color: Colors.white, ), onPressed: () { setState(() { _startCount += 1; }); }), Text( _startCount.toString(), style: TextStyle(fontSize: 25, color: Colors.red), ) ], ), ), ), ); } }
在使用的地方進行調用spa
@override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text(widget.title)), body: CombinationWidget(Colors.blue,200.0,200.0) ); }
傳入必要的參數就能夠了!再看下效果圖
以上!有任何疑問歡迎留言!