Another really important part of Flutter development is user interaction. You know, that thing that makes your app... interactive?
Here we'll talk about buttons and how to make any widget "touchable".
Let's start with the most basic interaction widget of all: buttons. A button can have many forms, Android users are ore used to very rounded widgets with ripple effect, iOS users instead use more often flat buttons without borders or rounded rectangles with text-changing colors on touch. You can find all buttons Flutter can render here. Let's see a little example with two "weird" buttons: DropdownButton and IconButton.
DropdownButton is a component which renders a simple underlined button which on click shows a dropdown with a list of strings. You'll need to create a list of DropdownMenuItems
starting from your input. Clicking on an item triggers the onChanged
function.
List<String> _listOfItems = List();
_listOfItems.add("One");
_listOfItems.add("Two");
_listOfItems.add("Three");
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Container(
child: DropdownButton(
hint: Text("Tap Here"),
items: _listOfItems.map((item) {
return DropdownMenuItem(
child: new Text(
item,
),
value: item,
);
}).toList(),
icon: Icon(
Icons.arrow_drop_down,
color: Colors.red,
),
onChanged: (value) {
//Do something
},
),
)
);
This code shows this simple button:
IconButton just represents a tappable icon, you can easily use it as "home" icon for the toolbar:
appBar: AppBar(
backgroundColor: Colors.red,
leading: IconButton(
icon: Icon(Icons.home),
onPressed: () {
//Do something
},
color: Colors.white,
),
),
Shows this AppBar:
You can choose any icon in the Icons
package or create your own with the Icon widget.
A great thing about Flutter is to add touchable capability on pretty much any widget really easily. We already saw how to do a list on a previous article (check it out here), now we'll see how to add interaction to those items.
We'll use GestureDetector
which is a simple class that has a lot of parameters but we'll just need two of them: onTap
and child
. Very easily child is the widget that we want to add touch implementation, onTap is the function that the action will trigger:
return GestureDetector(
onTap: () {
final snackBar = SnackBar(content: Text("Tap!"));
Scaffold.of(context).showSnackBar(snackBar);
},
child: Row(
//My widget
);
)
Here's the result:
Those were just some examples on UI interaction, the great thing about Flutter is the extreme personalization of any component and the urge to create custom ones. So go out and create great widgets developers! The future is yours!!
Top comments (0)