Reputation: 91
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?
Upvotes: 1
Views: 12950
Reputation: 114
Yes you can create custom widgets in flutter. The following code creates custom button as:
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(),
);
}
}
You can use the CustomButton like this:
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");
},
)
],
),
),
);
}
}
Upvotes: 2
Reputation: 120
Yes, you can create your own widget even with animation using Flare
See this tutorial:
Upvotes: 0
Reputation: 1053
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.
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'),
);
}
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'),
),
);
}
Upvotes: 3