3

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());
}

3 Answers 3

8

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;
}
Sign up to request clarification or add additional context in comments.

Comments

1

This how you can change it

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

Comments

0

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

1 Comment

Thank you I will look at setState functionality

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.