Flutter
onTap callback
Handle taps with InkWell onTap and give feedback.
onTap and ScaffoldMessenger
The onTap callback of InkWell runs your code when a tap happens. Usually, to give the user feedback, you call ScaffoldMessenger.of(context).showSnackBar(...). The SnackBar shows a brief message at the bottom of the screen and requires context, so it is used inside the callback.
InkWell(
onTap: () {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Hello')),
);
},
child: Text('Tap'),
)
ScaffoldMessenger and context
ScaffoldMessenger manages messages such as SnackBars across the app. The expression ScaffoldMessenger.of(context) accesses the nearest ScaffoldMessenger in the widget tree, so context must be used inside the callback. The SnackBar widget carries the message to be shown.
Exercise Show a SnackBar with InkWell
Write a function showMessage that prints Message shown. In main call showMessage. In the onTap of the InkWell, both call showMessage and show a SnackBar via ScaffoldMessenger.of(context).showSnackBar.
Show example solution
import 'package:flutter/material.dart';
void mesajGoster() {
print('Mesaj gosterildi');
}
void main() {
mesajGoster();
runApp(const Uygulama());
}
class Uygulama extends StatelessWidget {
const Uygulama({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: Material(
child: InkWell(
onTap: () {
mesajGoster();
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Merhaba')),
);
},
child: Container(
width: 100,
height: 100,
color: Colors.purple,
),
),
),
),
),
);
}
}
Test yourself
-
Which expression is used to show a SnackBar on screen?
- print(...)
- runApp(...)
- ScaffoldMessenger.of(context).showSnackBar(...)
- Material(...)
Show answer
ScaffoldMessenger.of(context).showSnackBar(...) — The showSnackBar method of the object accessed via ScaffoldMessenger.of(context) shows the SnackBar on screen.
-
Access ScaffoldMessenger
InkWell(
onTap: () {
____.of(context).showSnackBar(
SnackBar(content: Text('Merhaba')),
);
},
child: Text('Dokun'),
)
Show answer
InkWell(
onTap: () {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Merhaba')),
);
},
child: Text('Dokun'),
)
-
Feedback parts
- onTap
- InkWell's tap callback
- ScaffoldMessenger
- Provides access to SnackBar
- showSnackBar
- Shows the SnackBar on screen
- SnackBar
- Message appearing at the bottom
Next lesson: Summary - InkWell