I have a multi page app with common sliders between the pages. So if foo has a default of 5, and on page one the user sets foo to 3, then when they select page two foo should have the value of 3.
Here is a MWE
import streamlit as st
if "foo" not in st.session_state:
st.session_state.foo =5
st.session_state.foo = st.sidebar.slider("foo",min_value=0, max_value=10, step=1,value=st.session_state.foo)
There’s a trick to make this work for a multipage app, which is
Use key to automatically sync the widget’s current value with session state.
Put these lines at the top of your page, before you do any other streamlit calls:
for k, v in st.session_state.items():
st.session_state[k] = v
These lines effectively tell streamlit that all of your session state values have been set manually, so they should be persisted even if the widget temporarily disappears off the page (e.g. when you switch pages).
e.g.
import streamlit as st
for k, v in st.session_state.items():
st.session_state[k] = v
st.write("Page 1")
foo = st.slider("foo", min_value=0, max_value=10, step=1, key="slider")
st.write(foo)
import streamlit as st
for k, v in st.session_state.items():
st.session_state[k] = v
st.write("Page 2")
foo = st.slider("foo", min_value=0, max_value=10, step=1, key="slider")
st.write(foo)