Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating Text Widget in Flutter

Tags:

flutter

dart

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());
}
like image 340
Alex Ali Avatar asked Apr 08 '26 05:04

Alex Ali


1 Answers

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;
}
like image 163
Nikhil Vadoliya Avatar answered Apr 10 '26 09:04

Nikhil Vadoliya



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!