How to delete any child Widget from a Flex container

114 Views Asked by At

I am trying to delete a child widget from a Flex container on a click event, but I can't find any methods to do so. The child widget is also a Flex container.

I have tried searching Druid examples and docs and can't seem to find anything relevant for this use case.

1

There are 1 best solutions below

0
On BEST ANSWER

I have managed to find a way although a bit hacky but still works, answer is based on this post from [email protected] where he explains how to escape Rust privacy rules: https://users.rust-lang.org/t/is-private-really-private/7826/15

Note this is all done on Rust 1.56.1 and Druid 0.7.0.

First you declare a struct same as Flex but with exposed children Vector:

use druid::{ WidgetPod };
use druid::widget::{*};

//Same as original but has to be copy/pasted because it is private in its 
own crate
pub struct ChildWidget<T> {
    widget: WidgetPod<T, Box<dyn Widget<T>>>,
    params: FlexParams,
}

//Struct with exposed children field
pub struct ClearableFlex<T> {
    direction: Axis,
    cross_alignment: CrossAxisAlignment,
    main_alignment: MainAxisAlignment,
    fill_major_axis: bool,
    pub children: Vec<ChildWidget<T>>, //key part - this is made public
}

impl<T> ClearableFlex<T>
{
    //Method that clears vector containing children
    pub fn clear(& mut self)
    {
        self.children.clear();
    }
}

And then in one of your event or command methods where you have mutable reference to container you use Rust unsafe operations(transmute):

fn load_products_list(container: &mut Flex<AppState>, data: &mut AppState) {

    //Hacky way to clear children, we use container2 if we need to add children again
    let container2 : &mut Flex<AppState>;
    unsafe {
        let clearable_flex : &mut ClearableFlex<AppState> =     std::mem::transmute( container );
        clearable_flex.clear();
        container2 = std::mem::transmute( clearable_flex );
    }
...
}