如需转载,请注明出处: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) ); }
传入必要的参数就能够了!再看下效果图
以上!有任何疑问欢迎留言!