How to manage state with StreamlitFlowState
masterStarting from version 1.5.0, Streamlit Flow uses a synchronized state management system. Instead of passing nodes and edges directly to the streamlit_flow function, you must wrap them in a StreamlitFlowState object.
CRITICAL: To prevent infinite re-renders and app hangs, you must store the StreamlitFlowState object in st.session_state. If you re-initialize the state on every run, the component will re-render infinitely because it synchronizes frontend changes back to the backend.
Correct Pattern:
- Check if the state exists in
st.session_state. - If not, initialize
StreamlitFlowState(nodes, edges)and save it tost.session_state. - Pass the session state object to
streamlit_flow. - Capture the return value of
streamlit_flowand update the session state to ensure UI interactions (like moving nodes) are reflected in Python.
import streamlit as st
from streamlit_flow import streamlit_flow
from streamlit_flow.elements import StreamlitFlowNode, StreamlitFlowEdge
from streamlit_flow.state import StreamlitFlowState
from uuid import uuid4
# 1. Initialize the state in session_state if it doesn't exist
if 'flow_state' not in st.session_state:
nodes = [...] # Your list of StreamlitFlowNode
edges = [...] # Your list of StreamlitFlowEdge
st.session_state.flow_state = StreamlitFlowState(nodes=nodes, edges=edges)
# 2. Example: Programmatically altering state
if st.button("Add node"):
new_node = StreamlitFlowNode(
id=str(f"st-flow-node_{uuid4()}"),
pos=(0, 0),
data={'content': f'Node {len(st.session_state.flow_state.nodes) + 1}'},
node_type='default',
source_position='right',
target_position='left'
)
st.session_state.flow_state.nodes.append(new_node)
st.rerun()
# 3. Render and capture updated state from UI interactions
st.session_state.flow_state = streamlit_flow('flow', st.session_state.flow_state)