【发布时间】:2019-11-28 05:21:32
【问题描述】:
作为 Flutter 的新手,我注意到它提供了很多可供选择的小部件。但我的问题是:我们可以自己做吗?例如,我可以自己制作尚未提供的按钮吗?
【问题讨论】:
作为 Flutter 的新手,我注意到它提供了很多可供选择的小部件。但我的问题是:我们可以自己做吗?例如,我可以自己制作尚未提供的按钮吗?
【问题讨论】:
是的,您可以创建自己的小部件。例如,如上所述,您可以使用如下代码创建自定义按钮。
您在
OutlineButton构造函数中看到的属性使用红色背景颜色、32 像素的圆形边框半径和文本构建按钮。里面还有一个onPressed函数,当你按下按钮时执行;在下面的示例中,按下按钮后,您将语句I pressed it打印到控制台。
Widget _buildButton(BuildContext context){
return OutlineButton(
onPressed: (){
print('I pressed it');
},
color: Colors.red,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(32.0)),
child: Text('CUSTOM BUTTON'),
);
}
您还可以将按钮包装在 ButtonTheme 小部件中,该小部件为您提供多种功能,其中之一就是根据您需要的尺寸缩放按钮。
Widget _buildButton(BuildContext context){
return ButtonTheme(
height: 100,
minWidth: 100,
child: OutlineButton(
onPressed: (){},
color: Colors.red,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(32.0)),
child: Text('CUSTOM BUTTON'),
),
);
}
【讨论】:
【讨论】:
是的,您可以在 Flutter 中创建自定义小部件。以下代码将自定义按钮创建为:
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
class CustomButton extends StatelessWidget {
CustomButton({@required this.onPressed});
final GestureTapCallback onPressed;
@override
Widget build(BuildContext context) {
return RawMaterialButton(
fillColor: Colors.green,
splashColor: Colors.greenAccent,
child: Padding(
padding: EdgeInsets.all(10.0),
child: Row(
mainAxisSize: MainAxisSize.min,
children: const <Widget>[
Icon(
Icons.face,
color: Colors.amber,
),
SizedBox(
width: 10.0,
),
Text(
"Tap Me",
maxLines: 1,
style: TextStyle(color: Colors.white),
),
],
),
),
onPressed: onPressed,
shape: const StadiumBorder(),
);
}
}
您可以像这样使用自定义按钮:
class _CustomWidgetDemoState extends State<CustomWidgetDemo> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Text("here is a custom button in FLutter"),
CustomButton(
onPressed: () {
print("Tapped Me");
},
)
],
),
),
);
}
}
【讨论】: