Why is my view not updating correctly in Flet?

205 Views Asked by At

I'm new to Flet, and I'm practicing with a system to generate work shifts. Basically, my view has a button that triggers the function to generate shifts randomly. The logic works fine, in fact, my show_workers function correctly receives the data. However, when I create a Text element with the worker's name and try to add it to the controls list of my page_view element, nothing happens:

import flet
from flet import Text, UserControl, ElevatedButton
from .controller import Controller

class ShiftsView(UserControl):
    def __init__(self, page, controller):
        super().__init__()
        self.page = page
        self.controller = controller
        self._add_listeners()
  
    def _add_listeners(self):
        def run_shifts(workers):
            print(workers)
            self.show_workers(workers)
    
        self.controller.add_listener('WORKERS::RUN_SHIFTS', run_shifts)
    
    def build(self):
        self.page_view = Column(
            controls=[
                ElevatedButton("Generate shift", on_click=self.button_clicked),
            ]
        )
    
        return self.page_view
    
    def button_clicked(self, e):
        self.controller.get_shifts()
        self.page.update()
    
    def show_workers(self, workers):
        print("workers", workers)
        for w in workers:
            self.page_view.controls.append(Text(w[0]))
    
        self.page.update()

But, by doing it this way, my page updates with the Text element:


import flet
from flet import Text, UserControl, ElevatedButton
from .controller import Controller

class ShiftsView(UserControl):
    def __init__(self, page, controller):
        super().__init__()
        self.page = page
        self.controller = controller
        self._add_listeners()

    def _add_listeners(self):
        def run_shifts(workers):
            self.show_workers(workers)
    
        self.controller.add_listener('WORKERS::RUN_SHIFTS', run_shifts)
    
    def build(self):
        self.page_view = Column(
            controls=[
                ElevatedButton("Generate shift", on_click=self.button_clicked)
            ]
        )
        return self.page_view
    
    def button_clicked(self, e):
        self.controller.get_shifts()
    
    def show_workers(self, workers):
        print("workers", workers)
    
        for w in workers:
            self.page.add(Text(w[0]))
    
        self.page.update()

I want to do it in the first way because I want that every time the 'Generate Shift' button is clicked, the text of the previous workers disappears, and the new workers appear in their place. If anyone knows how to achieve this or how to solve my initial issue, I would greatly appreciate it. Thank you.

I expected my view self.page_view to update with the names of the workers, but it doesn't update. There's no error generated; it just doesn't update.

0

There are 0 best solutions below