Open In App

Flutter – Change Text When Button Pressed

Last Updated : 05 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, you will see how you can change the text in Flutter on a single screen after clicking the button. Let’s start so you first start your vs code or android studio and you just delete the whole code and paste the code which we have given in below and run it then you can get the solution. A sample video is given below to get an idea about what we are going to do in this article.

Approach

Simply we create a stateful widget and in the stateful widget, we take the MyHomePage Name as you can see in the code. Now we return the scaffold just because we need the AppBar if you don’t need the app bar then you can return some things other like the material app or you can directly return the column. We created a function in the stateful widget which you can see in the code, first function is called when we tap on the Button. And also created the list of text which is called by the text widget while it changing.

After the AppBar we simply return the column in the body section and took the two widgets, first one is the text and the second one is the button. In the text widget, we took some font sized and called the list of text which I created upper side, and fetch the list text by adding dots and indexing. In flutter by default indexing is zero. In the button, we simply called our function which we created in the stateful widget state. while we tap on the button then the indexing changes and we fetch the text through the index so the text also changes with the help of a set state which we use in onbuttonclicked function which you can see in the code.

Code

Dart




// ignore_for_file: prefer_const_constructors
 
import 'package:flutter/material.dart';
 
void main() {
  runApp(const MyApp());
}
 
class MyApp extends StatelessWidget {
  const MyApp({super.key});
 
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Geeks For Geeks',
      theme: ThemeData(
        // this is the primary color. which automatically
        // used by the appbar and elevated button
        primarySwatch: Colors.green, 
      ),
      home: MyHomePage(),
    );
  }
}
 
class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key});
 
  @override
  State<MyHomePage> createState() => _MyHomePageState();
}
 
class _MyHomePageState extends State<MyHomePage> {
  // this is the indexing if we not give
  // it than also it start form the 0 indexing.
  var currentindex = 0;                
 
  void buttonClicked() {
    setState(() {      
      // setstate using for the rerender the screen
      // if we not use than it not show the sceond text
      currentindex = currentindex + 1;
    });
    // this is the output when you tap on the button but
    // it showing you in console not on screen
    print("button one");         
  }
 
  @override
  Widget build(BuildContext context) {
    var questions = [
      // list of text which the text get form here
      "Priyanshu is a developer",                           
      "You can also become the gfg developer",
    ];
 
    return Scaffold(
      appBar: AppBar(
        // this is app bar text
        title: Text("Geeks For Geeks"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment
              .center,
          // for vertical centere and padding for the horizontal center
          // crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Text(
              // questions.elementAt(1),
              questions[
                  currentindex],
              // here index and text come form the upper list
              // of question and indexing start form the 0
              style: TextStyle(fontSize: 30),
            ),
            SizedBox(
              // this is use for giving the spacing
              // between the text and the button
              height:
                  40,
            ),
            ElevatedButton(
              onPressed: buttonClicked,
              child: Text(
                  "Press Here"),
              // this is the button text and we use the elevated
              // button and it take the primary color but
              // we can change the elevated button colors.
            ),
          ],
        ),
      ),
    );
  }
}


Output:



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads