You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
structMyScreen{// État local à ce screeninput_text:String,selected_index:Option<usize>,show_details:bool,}implMyScreen{fnrender(&mutself,ui:&mut egui::Ui){// Utiliser l'état local directement
ui.text_edit_singleline(&mutself.input_text);if ui.button("Afficher détails").clicked(){self.show_details = !self.show_details;}}}
État global (partagé)
use std::sync::Arc;use arc_swap::ArcSwap;pubstructAppState{pubcurrent_user:Option<User>,pubsettings:Settings,pubdata:Vec<DataItem>,}pubstructApp{// État global partagéstate:Arc<ArcSwap<AppState>>,}implApp{fnrender(&mutself,ui:&mut egui::Ui){let state = self.state.load();// Lire l'état globalifletSome(user) = &state.current_user{
ui.label(format!("Utilisateur: {}", user.name));}}fnupdate_state(&self,new_state:AppState){self.state.store(Arc::new(new_state));}}
Patterns de state management
Pattern 1 : État dans la struct App
#[derive(Default)]structMyApp{// État de l'applicationcounter:i32,name:String,items:Vec<String>,}impl eframe::AppforMyApp{fnupdate(&mutself,ctx:&egui::Context,_frame:&mut eframe::Frame){// Accès direct à self
egui::CentralPanel::default().show(ctx, |ui| {
ui.label(format!("Counter: {}",self.counter));if ui.button("Increment").clicked(){self.counter += 1;}});}}
use std::sync::Arc;use arc_swap::ArcSwap;pubstructStore{state:Arc<ArcSwap<AppState>>,}implStore{pubfnnew() -> Self{Self{state:Arc::new(ArcSwap::from_pointee(AppState::default())),}}pubfnread(&self) -> Arc<AppState>{self.state.load_full()}pubfnupdate<F>(&self,f:F)whereF:FnOnce(&AppState) -> AppState,{self.state.rcu(|state| Arc::new(f(state)));}}pubstructApp{store:Store,}implApp{fnrender(&mutself,ctx:&egui::Context){let state = self.store.read();// Utiliser state pour l'affichage
egui::CentralPanel::default().show(ctx, |ui| {
ui.label(&state.current_message);});// Mettre à jour si nécessaireif some_condition {self.store.update(|state| {letmut new = state.clone();
new.current_message = "Nouveau message".to_string();
new
});}}}