How To Change Button Text Dynamically In Flutter App

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

We can easily update the Button Text using State in flutter. State is used to update widgets properties in real time and display changes on screen.

How To Change Button Text Dynamically In Flutter App

Change Button Text Dynamically

Complete Code FOr Change Button 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.deepPurple,
                title: Text('Change Button Above Text Dynamically')
            ),
            body: Center(
                child: CustomButton()
            )
        )
    );
  }
}

class CustomButton extends StatefulWidget {
  CustomButtonState createState() => CustomButtonState();
}

class CustomButtonState extends State<CustomButton> {
  String buttonText = 'Old Text';
  updateButtonText(){
    setState(() {
      buttonText = 'New Text';
    });
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              RaisedButton(
                onPressed: ()=> print('Clicked'),
                color: Colors.orange,
                textColor: Colors.white,
                padding: EdgeInsets.fromLTRB(10, 10, 10, 10),
                child: Text('$buttonText'),
              ),
              RaisedButton(
                onPressed: updateButtonText,
                color: Colors.deepPurple,
                textColor: Colors.white,
                padding: EdgeInsets.fromLTRB(10, 10, 10, 10),
                child: Text('Change Button Above Text'),
              ),

            ],
          ),
        ));
  }
}

 

Related Post