Search code examples
flutterdarttextwidget

How to change text in Flutter (Dart)?


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.


Solution

  • 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";
    
                    });
                  },),
                ],),
              )
          ),
        );
      }
    }