要求使用flutter實現(xiàn)如圖textfiled功能
初識flutter歡迎交流肌幽。
image.png
image.png
使用方法:
JJText(
fieldCallBack: (v) {
print("Callback ${v}");
},
isRightBtn: true,
rightIcon: Image.asset('images/login/密碼可見.png'),
icon: Image.asset(
'images/login/手機.png',
fit: BoxFit.cover,
),
height: 100,
text: "用戶名",
onRightBtnClick: () {
print("點我了");
},
),
以下代碼為組建:
import 'package:flutter/material.dart';
typedef void JJTextFieldCallBack(String content);
class JJText extends StatefulWidget {
final String text;
final bool password;
// 是否有更多按鈕
final bool isRightBtn;
// 是否顯示取消按鈕
bool isShowClean;
final Object onChanged;
// 更多按鈕點擊
final Object onRightBtnClick;
final int maxLines;
final double height;
// 左側(cè)按鈕圖標
final Widget icon;
// 右側(cè)更多按鈕圖標
final Widget rightIcon;
final JJTextFieldCallBack fieldCallBack;
JJText({
Key key,
this.text = "輸入內(nèi)容",
this.password = false,
this.isShowClean = false,
this.onChanged,
this.onRightBtnClick,
this.maxLines = 1,
this.height = 68,
this.icon,
this.rightIcon,
this.isRightBtn = false,
this.fieldCallBack,
}) : super(key: key);
@override
_JJTextaState createState() => _JJTextaState();
}
class _JJTextaState extends State<JJText> {
FocusNode _focusNode = new FocusNode();
TextEditingController controller = TextEditingController();
@override
void initState() {
super.initState();
_focusNode.addListener(_focusNodeListener);
}
Future<Null> _focusNodeListener() async {
if (_focusNode.hasFocus) {
setState(() {
widget.isShowClean = true;
});
} else {
setState(() {
widget.isShowClean = false;
});
}
}
@override
Widget build(BuildContext context) {
return Container(
child: Container(
child: TextField(
focusNode: _focusNode,
controller: controller,
maxLines: widget.maxLines,
obscureText: widget.password,
decoration: InputDecoration(
icon: widget.icon,
fillColor: Colors.green,
suffixIcon: Container(
child: Row(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
widget.isShowClean
? IconButton(
icon: Image.asset('images/login/清除.png'),
onPressed: onCancel,
)
: Text(""),
widget.isRightBtn
? IconButton(
icon: widget.rightIcon,
onPressed: widget.onRightBtnClick,
)
: Text(""),
],
),
),
hintText: widget.text,
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(30),
borderSide: BorderSide.none)),
onChanged: (v) {
widget.fieldCallBack(v);
// if(v.length == 0){
// print("00000000");
// }
setState(() {
widget.isShowClean = v.isNotEmpty;
});
},
onSubmitted: (v) {
widget.fieldCallBack(v);
setState(() {
widget.isShowClean = false;
});
},
),
decoration: BoxDecoration(
border:
Border(bottom: BorderSide(width: 1, color: Colors.black12))),
),
);
}
onCancel() {
// 保證在組件build的第一幀時才去觸發(fā)取消清空內(nèi)
WidgetsBinding.instance.addPostFrameCallback((_) => controller.clear());
setState(() {
widget.isShowClean = false;
});
}
}