skip to Main Content

I’m trying to change the value of the text in the button whenever I press it, but it stays the same. Tried using Naviagation.push but I kept getting errors from it so I deleted it off.


class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key});

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

int myVariableNumber = 0;

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Hello World"),
        backgroundColor: Colors.black,
      ),
      backgroundColor: Colors.black,
      body: Scaffold(
        body: Container(
          alignment: Alignment.center,
          width: 300,
          height: 300,
          color: Colors.white,
          child: SizedBox(
            width: 140,
            height: 70,
            child: ElevatedButton(
              onPressed: () {
                myVariableNumber = myVariableNumber + 1;
                Navigator.push(context, -)
                
              },
              
              child: Text('Hello $myVariableNumber'),
            ),
          ),

        ),
      ),
    );
  }
}

Tried navigation.push and I expected it to refresh and change numbers, but it only gave me errors.

2

Answers


  1. To update value of this button, you need to rebuild your widget by calling setState method. And move your state into State subclass (in this case is _MyHomePageState).

    import 'package:flutter/material.dart';
    
    class MyHomePage extends StatefulWidget {
      const MyHomePage({super.key});
    
      @override
      State<MyHomePage> createState() => _MyHomePageState();
    }
    
    class _MyHomePageState extends State<MyHomePage> {
      int myVariableNumber = 0; // move your state here
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: const Text("Hello World"),
            backgroundColor: Colors.black,
          ),
          backgroundColor: Colors.black,
          // body: Scaffold( // remove this unnecessary Scaffold
          body: Container(
            alignment: Alignment.center,
            width: 300,
            height: 300,
            color: Colors.white,
            child: SizedBox(
              width: 140,
              height: 70,
              child: ElevatedButton(
                onPressed: () => setState(() { // this will update your widget with new myVariableNumber value
                  myVariableNumber = myVariableNumber + 1;
                }),
                child: Text('Hello $myVariableNumber'),
              ),
            ),
          ),
          // ),
        );
      }
    }
    
    Login or Signup to reply.
  2. Use setState() method for myVariableNumber.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search