我们可以在Flutter中创建一个新的小部件吗?
我是Flutter的新手,我注意到它提供了许多小部件供您选择。但是我的问题是:我们可以自己制造吗?例如,我可以制作自己尚未提供的按钮吗?
being new to Flutter i've noticed that it offers a lot of widgets to choose from. But my question is : Can we make our own? foe example, Can I make my own kind of button that's not already offered?
是的,您可以创建自己的小部件。例如,如上所述,您可以使用以下代码创建自定义按钮。
Yes you can create your own widget. For example, as you stated above, you can create a custom button using code like the one below.
OutlineButton
构造函数以红色背景色,32px的圆形边框半径和文本构建按钮。这也是其中的onPressed
函数,当您按下按钮时会执行该函数;在下面的示例中,按下按钮后,您将打印到控制台的语句我按下了它
。
The properties that you see inside the
OutlineButton
constructor build the button with a red background color, a circular border-radius of 32px and a text. The is also aonPressed
function inside there that is executed when you press the button; in the example below after pressing the button you print to the console the statementI 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
小部件,该小部件可为您提供多种功能,其中之一是根据需要的大小缩放按钮。
You can also wrap your button inside a ButtonTheme
widget, which offers you multiple features, one of them is to scale the button with the sizes you need.
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'),
),
);
}