rustrust-iced

Store iced Element of Text in my Apps struct


I have a function which matches against an enum with Strings and makes text elements with a color corresponding to the enum. I want to store those Texts in a field of MyApp.

(Edit) The previous example was full of syntax errors and it was missing a few important functions, the new example gives the error message described at the bottom but the solution pirate suggested is way better.

specifying the lifetime removed the first error.

New example

fn main() -> iced::Result {
    iced::run("", MyApp::update, MyApp::view)
}

use iced::{
    widget::{text, text::Text},
    Color, Element,
};

#[derive(Default, Debug)]
struct MyApp<'a> {
    texts: Vec<Text<'a>>,
}

enum TextType {
    A(String),
    B(String),
}

enum Message {}

impl<'a> MyApp<'a> {
    fn view(&self) -> Element<Message> {
        todo!()
    }

    fn update(&mut self, message: Message) {
        todo!()
    }

    fn color_text(&mut self, texts: Vec<TextType>) {
        let mut collor_text = Vec::new();

        for text in texts {
            match text {
                TextType::A(txt) => collor_text.push(text!("{}", txt).color(Color::WHITE)),
                TextType::B(txt) => collor_text.push(text!("{}", txt).color(Color::BLACK)),
            }
        }

        self.texts = collor_text;
    }
}

(Old example) Something like this:

use iced::{Color, widget::{text, Text}}

struct MyApp {
    texts: Vec<Text>
}

enum TextType {
    A(String),
    B(String)
}

fn color_text(&mut self, texts: Vec<TextType>) {
    let mut collor_text = Vec::new();

    for text in texts {
        match text {
            A(text) => collor_text.push(text(text).color(Color::WHITE)),
            B(text) => collor_text.push(text(text).color(Color::BLACK))
        }
    }

    self.texts = collor_text;
}

If I try it with Vec<Text> the compiler tells me expected named lifetime parameter. When I try to use a lifetime like 'a the compiler says
iced::advanced::widget::Text<'static, Theme, iced_renderer::fallback::Renderer<iced_wgpu::Renderer, iced_tiny_skia::Renderer>>` cannot be formatted using `{:?}` because it doesn't implement `Debug

Is there a way to declare the type or a better solution?


Solution

  • Widgets are not meant to be stored as struct Member. Instead you should store it's underlying data. Example, you can store both texts and their colors as Vec<(String, Color)>, then use that underlying data to create Widgets in fn view()

    you might be able to store it as struct memeber, if you supply all the generics and lifetime like Message, Theme, Renderer and more But not worth the hassle.