In this tutorial, we’ll learn how to properly use Flutter textButton onPressed with the help of an easy Flutter example.
Introduction: Flutter TextButton OnPressed
As the name suggests, it’s used to trigger some actions after the text button is clicked by the user. We’ll be using a proper example to demonstrate how we can use it.
So let’s get right into its practical implementation.
Implementing Flutter TextButton OnPressed (Easy Example Code)
We first have to define a simple Flutter textButton widget. Then we will use its required onPressed constructor which takes a function. We can specify any action we want in the body of that function.
To demonstrate how it works, we’ll be using a Flutter snackbar widget inside that function’s body. So whenever the user clicks on the textButton, the snackbar widget will appear on the screen. See below code in which this theory is practically implemented.
TextButton( onPressed: () { ScaffoldMessenger.of(context).showSnackBar(SnackBar( content: Text('Text button is pressed'))); }, child: Text('Text button OnPressed'))
![How To Use Flutter TextButton OnPressed [Flutter Easy Guide] 3 flutter textbutton widget onpressed](https://letmeflutter.com/wp-content/uploads/2022/10/IMG_20221004_160444-300x88.jpg)
![How To Use Flutter TextButton OnPressed [Flutter Easy Guide] 4 flutter textbutton onpressed](https://letmeflutter.com/wp-content/uploads/2022/10/IMG_20221004_160457-300x88.jpg)
Flutter TextButton OnPressed Implementation Source Code
import 'package:flutter/material.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, home: Homepage(), ); } } class Homepage extends StatefulWidget { @override State<Homepage> createState() => _HomepageState(); } class _HomepageState extends State<Homepage> { @override Widget build(BuildContext context) { return SafeArea( child: Scaffold( body: Center( child: TextButton( onPressed: () { ScaffoldMessenger.of(context).showSnackBar(SnackBar( content: Text('Text button is pressed'))); }, child: Text('Text button OnPressed'))))); } }
Conclusion
To conclude this tutorial, now you’ve a detailed and in-depth practical knowledge of how to properly use Flutter textButton onPressed. I’d love to have your feedback on this post.
I’d also love to see you visit my other tutorials on Flutter app development and Python programming as well. Thank you for reading this post.