Change Text Widget Text Dynamically on Button Click in Flutter Dart

Text widget text can be called dynamically via String variable. Sometimes flutter app developer wants to update the Text on certain event or button onPress event. We could use State update method to Change Text Widget Text Dynamically on Button Click in Flutter Android iOS mobile app. So let’s get started 🙂 .

Contents in this project Change Text Widget Text on Button Click Dynamically in Flutter:

1. Import material.dart package in your app’s main.dart file.

2. Create void main runApp() method and call our main Root class MyApp here.

3. Create our main MyApp class extends with State less widget. In this class we would call the UpdateText() class in body section of Scaffold widget.

4. Create a class named as UpdateText extends StatefulWidget. In this class we would make the createState() method with our child widget class and pass the child widget in which we would make the Text widget will pass here.

5. Create a class named as UpdateTextState extends with State.

6. Create a String variable named as textHolder and assign some random default text to it. We would use this variable for showing text.

7. Create a function named as changeText(). In this method we would update the String variable textHolder text using State method. We would call this function on button onPress event.

8. Create a Text widget and 1 Raised Button widget in Widget build area of UpdateTextState class. We would call the function on button click event to update text.

9. Complete source code for main.dart file:

Screenshot:

Change Text Widget Text Dynamically on Button Click in Flutter

Leave a Reply

Your email address will not be published. Required fields are marked *