2

The variable value is not refreshing in flutter(which I created outside the class). The following way I have added.So in button press am setting different value. So if I come back to that screen again it is not showing 1. May I know why it is happening?

int _currVal = 1;

class AskFragment extends StatefulWidget {
  static const String routeName = "//";
  static const
  int currState = -1;

  @override
  HomeScreenState createState() => HomeScreenState();
}
9
  • variables change state inside a StatefulWidget, if you want to change that value, use the method setState(). You're using a global variable that way and you won't get the updated value when changed. Commented Feb 18, 2020 at 16:35
  • @MarianoZorrilla yeah it is global value only. Am using an Alert dialog in that am setting the value. Am getting the value. But the problem is what ever I got the last value it is remains state. if I come back to the particular screen Commented Feb 18, 2020 at 16:40
  • 1
    initialize the value inside the class and update the value in setState((){}); :- read this document :- api.flutter.dev/flutter/widgets/StatefulWidget-class.html Commented Feb 18, 2020 at 17:12
  • @YogeshChawla done Commented Feb 18, 2020 at 17:16
  • is it working now ? @SunishaSindhu Commented Feb 19, 2020 at 4:32

1 Answer 1

5

To update the values, use Stateful Widget and initialise values inside that Widget only, for any updates in the values of variables mention that in setState((){}) method to notify the change in the values.

See this for documentation of stateful widgets

See this for documentation of setState((){}) method

setState(() { _myVariable = newValue });

Note:- Never initialise changing values in build method they will not get updated instead they will be reinitialised with same values again and again

Sign up to request clarification or add additional context in comments.

Comments

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.