Search⌘ K
AI Features

Solution: Handling Gestures

Explore how to manage user gestures in Flutter applications by implementing tap and long-press interactions. This lesson guides you through handling the FloatingActionButton press to navigate between screens and detecting long presses on list items to display contact information, enhancing app interactivity and user experience.

Challenge solutions

Great job on completing all the steps in the previous challenge! Feel free to compare your code solutions with the solutions below:

lib/contact_list_screen.dart
lib/new_contact_screen.dart
import 'package:flutter/material.dart';
import 'single_contact_screen.dart';
import 'new_contact_screen.dart';
class ContactListScreen extends StatefulWidget {
const ContactListScreen({
Key? key,
}) : super(key: key);
@override
State<ContactListScreen> createState() => _ContactListScreenState();
}
class _ContactListScreenState extends State<ContactListScreen> {
List<String> contacts = List<String>.generate(20, (i) => "Ivy Walobwa");
@override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.all(16.0),
child: Wrap(
direction: Axis.vertical,
children: [
Text(
"Contacts",
style: Theme.of(context)
.textTheme
.headline3!
.copyWith(color: Colors.black),
),
Text("20 Contacts",
style: Theme.of(context)
.textTheme
.bodyText2!
.copyWith(color: Colors.black54)),
],
),
),
Expanded(
child: ListView.separated(
itemCount: contacts.length,
itemBuilder: (context, index) => Dismissible(
key: UniqueKey(),
onDismissed: (DismissDirection direction){
setState(() {
contacts.removeAt(index);
});
},
child: ListTile(
onLongPress: (){
showContactInfo(context);
},
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const SingleContactScreen()),
);
},
leading: const CircleAvatar(
child: Text("IW"),
),
title: const Text(
"Ivy Walobwa",
),
trailing: const Icon(Icons.info_outline),
),
),
separatorBuilder: (BuildContext context, int index) =>
const Divider(
height: 1,
),
),
),
],
),
),
bottomNavigationBar: BottomNavigationBar(
currentIndex: 1,
items: const [
BottomNavigationBarItem(icon: Icon(Icons.call), label: "Phone"),
BottomNavigationBarItem(icon: Icon(Icons.person), label: "Contacts"),
BottomNavigationBarItem(
icon: Icon(Icons.star_border), label: "Favorites"),
],
),
floatingActionButton: FloatingActionButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const NewContactScreen()),
);
},
child: const Icon(Icons.add),
),
);
}
}
showContactInfo(BuildContext context) {
return showMenu(
context: context,
position: const RelativeRect.fromLTRB(100, 150, 30, 0),
items: const <PopupMenuItem>[
PopupMenuItem(
child: Text("info 1"),
),
PopupMenuItem(
child: Text("info 2"),
),
]);
}

Challenge 1: New screen navigation

First, we ...