I want to add a function where when I press a button, text shows up somewhere on a screen.
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
static const String _title = 'App';
@override
Widget build(BuildContext context) {
return const MaterialApp(
title: _title,
home: MyStatelessWidget(),
);
}
}
class MyStatelessWidget extends StatelessWidget {
const MyStatelessWidget({super.key});
@override
Widget build(BuildContext context) {
return Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
TextButton(
style: TextButton.styleFrom(
textStyle: const TextStyle(fontSize: 20),
),
onPressed: () {},
child: const Text('Text Button'),
),
const SizedBox(height: 30),
OutlinedButton(
style: OutlinedButton.styleFrom(
textStyle: const TextStyle(fontSize: 20),
),
onPressed: () {},
child: const Text('Outlined Button'),
),
const SizedBox(height: 30),
ElevatedButton(
style: ElevatedButton.styleFrom(
textStyle: const TextStyle(fontSize: 20),
),
onPressed: () {},
child: const Text('Contained Button'),
),
const SizedBox(height: 30),
],
),
);
}
}
Thank you if you are able to help.
CodePudding user response:
call changeText
method in the button click
String _label = "Text";
int count = 0 ;
void changeText(){
setState(() {
_label = "Count $count" ;
});
}
ElevatedButton(
style: ElevatedButton.styleFrom(
textStyle: const TextStyle(fontSize: 20),
),
onPressed: () {
changeText() // this function
},
child: const Text('Contained Button'),
)
CodePudding user response:
Convert your StatelessWidget
to StatefulWidget
Then Initialize in the top a string value like below:
String test = '';
Then Above your elevated button or anywhere in your screen Initialize a text widget like below with the test value:
Text(test),
Then in one of your buttons setSate to change the value of the string test:
TextButton(
style: TextButton.styleFrom(
textStyle: const TextStyle(fontSize: 20),
),
onPressed: () {
setState(() {
test = 'hello wolrd';
});
},
child: const Text('Text Button'),
),