0

I'm new to Flutter! I want to change the content of "Text" on click and Button "change Text" see the following code:

void main() {
  runApp(MaterialApp(home: MyHomePage()));
}
class MyHomePage extends StatelessWidget {
  const MyHomePage({
    Key? key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        appBar: AppBar(
          backgroundColor: Colors.blue,
          title: Center(
              child: Text("App demo",
                  style: TextStyle(color: Colors.yellow, fontSize: 40))),
        ),
        body:Center(
          child: Column(children: [
            Text("Hello word !", key: Key("textKey")),
            TextButton(child: Text("change Text"), onPressed: (){
              /* **I want to change "Hello word!" to "Text has changed"** */
              debugPrint("Change");
            },),
          ],),
        )
      ),
    );
  }
}

Please show me how to do it? enter image description here thanks, everyone.

1

1 Answer 1

0

You need to extend with a stateful widget if you want to change the text. In stateless, it can't rebuild, so you must go with the stateful widget or state management like(bloc, provider, getx etc)

import 'package:flutter/material.dart';
void main() {
  runApp(MaterialApp(home: MyHomePage()));
}
class MyHomePage extends StatefulWidget {
  const MyHomePage({
    Key key,
  }) : super(key: key);

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  String helloWorld = "Hello word !";
  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
          appBar: AppBar(
            backgroundColor: Colors.blue,
            title: Center(
                child: Text("App demo",
                    style: TextStyle(color: Colors.yellow, fontSize: 40))),
          ),
          body:Center(
            child: Column(children: [
              Text("$helloWorld", key: Key("textKey")),
              TextButton(child: Text("change Text"), onPressed: (){
                /* **I want to change "Hello word!" to "Text has changed"** */
                debugPrint("Change");
                setState(() {
                  helloWorld = "Change text";

                });
              },),
            ],),
          )
      ),
    );
  }
}
Sign up to request clarification or add additional context in comments.

4 Comments

please mak it as answer, and also try to type english, Happy coding!
the current way solved my problem, but i want to ask more can we use "Find Widgets" to make this request?
you can write testing using find widgets

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.