简体   繁体   中英

Flutter setState from a different Screen

Activity1

static String mValue = "0";

change(){
  setState((){
    Activity1.mValue = "1";
 });
}

Activity2

Text(Activity1.mValue)

This is the simplest form of my code. I want to change the static value present in Activity1 and that change should be reflected in Activity2

What Works so far

// Activity2
setState((){
  Activity1.mValue = "1";
})
Text(Activity1.mValue);

What I want to achieve is change the value from Activity1 and have it reflected in Activity2. They are 2 different classes and are not Root and Child. Anyway to achieve this?

In Flutter we don't change the state of one widget from another widget directly, as Flutter is a declarative framework.

Take a look at state management approaches section in Flutter docs, and especially Lifting state up section.

The main idea is that you lift your state in the widget that is above both Activity1 and Activity2 , change it there (eg using callbacks) and then propagate the state down the tree.

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