How To Change Text Dynamically On click Of Button In Flutter

admin_img Posted By Bajarangi soft , Posted On 08-10-2020

Text widget text can be called dynamically via String variable. Sometimes flutter app developer wants to update the Text on certain event or button onPressed event.

How To Change Text Dynamically On click Of Button In Flutter

Change Text Dynamically OnClick Of Button 

Complete Code FOr Change Text Dynamically In Flutter
Main.dart

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
        home: Scaffold(
            appBar: AppBar(
              centerTitle: true,
                backgroundColor: Colors.indigo,
                title: Text('Change Text Dynamically on Button Click')
            ),
            body: Center(
                child: ChangeText()
            )
        )
    );
  }
}

class ChangeText extends StatefulWidget {

  ChangeTextState createState() => ChangeTextState();

}

class ChangeTextState extends State {

  String textHolder = 'Old Text';

  changeText() {

    setState(() {
      textHolder = 'New Text';
    });

  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
             children: <Widget>[
              Container(
                  padding: EdgeInsets.fromLTRB(20, 20, 20, 20),
                  child: Text('$textHolder',
                      style: TextStyle(fontSize: 21))),

              RaisedButton(
                onPressed: () => changeText(),
                child: Text('Change Text Widget Text Dynamically'),
                textColor: Colors.white,
                color: Colors.red,
                padding: EdgeInsets.fromLTRB(10, 10, 10, 10),
              ),

            ]))
    );
  }
}

Related Post