简体   繁体   中英

Updating Text Widget in Flutter

I am new with Flutter and I face a problem as I want to update Text widget with the value passed from numbers() function.

The problem is the value inside Text does not change on the screen when I press on the button but it changes in the console.

class _HomeState extends State<Home> {


int n = 10;

  @override
  Widget build(BuildContext context) {
    return Scaffold(

  backgroundColor: Colors.deepPurpleAccent,
  body: Center(
    child: Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [

        Text(n.toString()),

        RaisedButton(
          onPressed: (){
            n += numbers();
            print(n.toString());
          },
        ),
      ],
    ),
  ),
);
  }
}
int numbers (){

  List<int> numbersList = List(1);

  numbersList[0] = 30;

  int n1 = numbersList[0];

  return n1;

  print(numbersList[0].toString());
}

If you want to update UI then you should be call setState((){}); method in flutter.This method available in StatefulWidget

You Should be implement below way

class _HomeState extends State<Home> {
  int n = 10;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.deepPurpleAccent,
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(n.toString()),
            RaisedButton(
              onPressed: () {
                setState(() {
                  n += numbers();
                });
              },
            ),
          ],
        ),
      ),
    );
  }
}

int numbers() {
  List<int> numbersList = List(1);

  numbersList[0] = 30;

  int n1 = numbersList[0];

  return n1;
}

This is expected since in flutter whenever you want to "refresh" screen you have to call setState() for the widget that you want to update. So what you do is, inside your onPressed function you do the following:

setState(){
   n += numbers();
}
print(n.toString());

You can read more about stateful widgets and setState here

This how you can change it

RaisedButton(
  onPressed: (){
     final newVal = numbers();
     setState((){
              n += newVal;
             });
   print(n.toString());
       },
     ),

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM