This tutorial follows the previous tutorial. We use the close function in window module to close the window. This is also done by returning the Task obtained by the close function.
Similar to the resize function, the close function needs an ID of the window we are going to close. To do that, the window module has a get_latest function. This function also returns a task that needs to be resolved to the Id of the latest window. In our case, since we have a single window, it will always return the Id of the main window. Once the close function is called, the window will be closed, and, because it's the only window, the application will exit.
use iced::{
Task,
widget::{button, row},
window,
};
fn main() -> iced::Result {
iced::run("My App", MyApp::update, MyApp::view)
}
#[derive(Debug, Clone)]
enum Message {
CloseWindow,
}
#[derive(Default)]
struct MyApp;
impl MyApp {
fn close(id: window::Id) -> Task<Message> {
window::close(id)
}
fn update(&mut self, message: Message) -> Task<Message> {
match message {
Message::CloseWindow => window::get_latest().and_then(Self::close),
}
}
fn view(&self) -> iced::Element<Message> {
row![button("Close window").on_press(Message::CloseWindow),].into()
}
}➡️ Next: Events
📘 Back: Table of contents
