FLutter自定义dialog并可传回调函数
自定义dialog代码:
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
class addLabelPageDialog extends StatefulWidget {
final confirmCallback;
const addLabelPageDialog(
{
Key key,
this.confirmCallback
}) : super(key: key);
@override
State<StatefulWidget> createState() {
return _addLabelPageDialog();
}
}
class _addLabelPageDialog extends State<addLabelPageDialog>{
final controller = TextEditingController();
String inputValuue = "";
@override
Widget build(BuildContext context) {
return GestureDetector(
child: Material(//遮罩层
type: MaterialType.transparency, //透明类型
//透明度
child: new Center(
child: Container(
width: 400,
height: 300,
decoration: BoxDecoration(
color: Colors.white,
shape: BoxShape.rectangle,
//可以设置角度,BoxShape.circle直接圆形
borderRadius: BorderRadius.all(Radius.circular(15.0)),
),
child: Column(
children: <Widget>[
Container(
width: 400,
height: 60,
alignment: Alignment.center,
decoration: BoxDecoration(
color: Colors.red,
shape: BoxShape.rectangle,
//可以设置角度,BoxShape.circle直接圆形
borderRadius: BorderRadius.only(
topLeft: Radius.circular(15.0),
topRight: Radius.circular(15.0)),
),
child: Text(
"新建标签",
style: TextStyle(
color: Colors.white,
fontSize: 30,
),
),
),
Container(
padding: new EdgeInsets.all(30),
color: Colors.white,
child: Container(
padding: new EdgeInsets.all(10),
decoration: BoxDecoration(
color: Color(0xFFFFCDD2),
border: Border.all(color: Colors.red, width: 1.0),
borderRadius: BorderRadius.circular(5.0),
),
child: TextFormField(
style: TextStyle(fontSize: 20,),
textAlign: TextAlign.center,
controller: controller,
onFieldSubmitted: (val) {
print("============键盘按回车完成=============" + val);
inputValuue = val;
},
decoration: InputDecoration(
hintText: '内容',
border: UnderlineInputBorder(
borderSide: BorderSide.none)),
)),
),
Container(
padding: new EdgeInsets.only(top: 30),
child: GestureDetector(
child: Container(
width: 100,
height: 50,
alignment: Alignment.center,
decoration: BoxDecoration(
color: Colors.red,
borderRadius: BorderRadius.circular(10.0),
),
child: Text("确定", style: TextStyle(fontSize: 25,color: Colors.white),),
),
onTap: (){
//通过回调函数回传新建的标签内容
widget.confirmCallback(inputValuue);
Navigator.of(context).pop();
},
),
),
],
)),
),
),
onTap: () {
print("关闭dialog");
Navigator.pop(context); //关闭对话框
},
);
}
}
调用方式:
onTap: () {//点击事件触发
print("添加标签");
return showDialog<Null>(
context: context, //BuildContext对象
barrierDismissible: false,
builder: (BuildContext context) {
return addLabelPageDialog(confirmCallback: confirmCallback);
});
},
//回调函数,接收新建的标签内容
void confirmCallback(value){
if(value == null || value == ""){
return;
}
if(labelList.contains(value)){
Fluttertoast.showToast(msg: "已添加,请勿重复添加",gravity: ToastGravity.CENTER);
}
print("添加的标签内容::::" + value);
setState(() {
labelList.add(value);
});
}
so easy!!!加油Flutter开发者们!!!祝一路顺风!!!!!!!!!!!!!!!!!!