by @kodeazy
flutter How to modify text after button click?
- With the help of
StatefulWidget
class we can modify text dynamically. - Every
StatefulWidget
hascreateState()
method which initializes the state. -
Below is the syntax.
class MyApp1 extends StatefulWidget { @override _MyState createState() => _MyState(); }
- With the help of
State.setState
we can modify the text on calling the function. -
Below is an example code of modifying the
text
after button clickimport 'package:flutter/material.dart'; void main() { runApp(MyApp1()); } class MyApp1 extends StatefulWidget { @override _MyState createState() => _MyState(); } class _MyState extends State<MyApp1> { var text = "Inital value"; void changeText() { setState(() { text = "Modified value"; }); } @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar(title: Text(text)), floatingActionButton: FloatingActionButton( onPressed: changeText, child: Icon(Icons.add), tooltip: "Click Here To change Text", ), )); } }