Flutter, the UI toolkit from Google, provides a rich set of widgets to build beautiful and interactive user interfaces. In this blog post, we'll delve into the TextButton widget, a fundamental component for handling user interactions in Flutter applications.
TextButton Overview: The TextButton widget is part of the Flutter material library and is designed to create a clickable text element. It is a simple and effective way to capture user input, making it a versatile tool for creating buttons, links, or any clickable text-based elements in your app.
Attributes of TextButton Widget:
onPressed:
- The onPressed attribute is crucial for defining the action to be taken when the TextButton is pressed. It typically takes a callback function, allowing you to specify the behavior you want when the user interacts with the button.
Example:
TextButton(
onPressed: () {
// Your action here
},
child: Text('Click me'),
)
child:
- The child attribute is where you define the text or widget that appears inside the TextButton. It can be a simple text string or a more complex widget, giving you flexibility in the content you want to display.
Example:
TextButton(
onPressed: () {
// Your action here
},
child: Text('Click me'),
)
style:
- The style attribute allows you to customize the appearance of the TextButton. You can specify the text style, padding, and other visual properties.
Example:
TextButton(
onPressed: () {
// Your action here
},
child: Text('Click me'),
style: TextButton.styleFrom(
textStyle: TextStyle(color: Colors.blue),
padding: EdgeInsets.all(10),
),
)
onLongPress:
- Similar to onPressed, the onLongPress attribute lets you define a callback function for long-press interactions on the TextButton.
Example:
TextButton(
onLongPress: () {
// Your action here
},
child: Text('Long press me'),
)
here's a simple example:
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Merge Example'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('Welcome to Flutter!', style: TextStyle(fontSize: 20)),
SizedBox(height: 20),
MergeExampleWidget(),
],
),
),
),
);
}
}
class MergeExampleWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MergeSemantics(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(Icons.star, color: Colors.yellow, size: 30),
SizedBox(width: 10),
Text('Star', style: TextStyle(fontSize: 18)),
],
),
);
}
}
ย