egui Persistence: Save & Restore Settings with serde | Rust GUI Ep 23
Video: egui Persistence: Save & Restore Settings with serde | Rust GUI Ep 23 by Taught by Celeste AI - AI Coding Coach
Watch full page →egui Persistence: Save & Restore Settings with serde | Rust GUI Ep 23
Learn how to build a Rust GUI app with egui that saves user settings across restarts using serialization and persistent storage. This tutorial covers deriving serializable app state, loading and saving data with eframe’s persistence API, and implementing a dark/light theme toggle alongside sliders and checkboxes for user preferences.
Code
use eframe::{egui, epi};
use serde::{Deserialize, Serialize};
// Derive Serialize and Deserialize for app state persistence
#[derive(Serialize, Deserialize, Debug)]
struct MyApp {
username: String,
dark_mode: bool,
volume: f32,
notifications_enabled: bool,
}
impl Default for MyApp {
fn default() -> Self {
Self {
username: "User".to_owned(),
dark_mode: false,
volume: 0.5,
notifications_enabled: true,
}
}
}
impl MyApp {
// Load saved state or default if none found
fn new(cc: &eframe::CreationContext<'_>) -> Self {
if let Some(storage) = cc.storage {
if let Some(app) = eframe::get_value(storage, eframe::APP_KEY) {
return app;
}
}
Default::default()
}
}
impl epi::App for MyApp {
fn name(&self) -> &str {
"egui Persistence Example"
}
// Save app state to storage on exit or as needed
fn save(&mut self, storage: &mut dyn epi::Storage) {
eframe::set_value(storage, eframe::APP_KEY, self);
}
fn update(&mut self, ctx: &egui::Context, _frame: &epi::Frame) {
// Toggle dark/light theme
if self.dark_mode {
ctx.set_visuals(egui::Visuals::dark());
} else {
ctx.set_visuals(egui::Visuals::light());
}
egui::CentralPanel::default().show(ctx, |ui| {
ui.heading("Settings");
egui::Grid::new("settings_grid").show(ui, |ui| {
ui.label("Username:");
ui.text_edit_singleline(&mut self.username);
ui.end_row();
ui.label("Enable Notifications:");
ui.checkbox(&mut self.notifications_enabled, "");
ui.end_row();
ui.label("Volume:");
ui.add(egui::Slider::new(&mut self.volume, 0.0..=1.0));
ui.end_row();
ui.label("Dark Mode:");
ui.checkbox(&mut self.dark_mode, "");
ui.end_row();
});
if ui.button("Reset to Defaults").clicked() {
*self = Default::default();
}
});
}
}
Key Points
- Derive Serialize and Deserialize on your app state struct to enable saving and loading with serde.
- Use eframe::get_value() in the new() constructor to load saved settings from persistent storage.
- Implement the save() method to store the current app state using eframe::set_value() and a consistent storage key.
- Toggle themes dynamically by setting ctx.set_visuals() based on a boolean flag in your state.
- Use egui widgets like sliders, checkboxes, and grids to build interactive settings UI with reset-to-default functionality.