Okay, let's make the image cards responsive. The key is to use Row with wrap=True and scroll=AUTO to allow the cards to flow and wrap onto new lines, and manage the size of the cards themselves.
We'll adjust the function to remove fixed width and height arguments and let the layout manage the sizing. The Image and Stack will expand to fill the constraints given by the Card or its parent.
import flet as ft
from pathlib import Path
import os # For dummy image creation
# --- Function to create the image card (Responsive Version) ---
def create_image_card(item_path: Path, on_card_click: callable = None) -> ft.Card:
"""
Creates a Flet Card displaying an image with its filename overlaid,
designed for responsive layouts.
Args:
item_path (Path): The path to the image file.
on_card_click (callable): Function to call when the card is clicked.
It will receive the event object 'e'.
Returns:
ft.Card: The configured Flet Card control.
"""
# --- Basic Check for File Existence ---
if not item_path.is_file():
# Return a simple error card if the path is invalid
return ft.Card(
content=ft.Container(
content=ft.Column([
ft.Icon(ft.Icons.BROKEN_IMAGE, color=ft.Colors.RED_ACCENT_700, size=30),
ft.Text("Not Found", size=10, color=ft.Colors.RED_ACCENT_700),
ft.Text(item_path.name, size=9, overflow=ft.TextOverflow.ELLIPSIS, max_lines=1),
], horizontal_alignment=ft.CrossAxisAlignment.CENTER, spacing=2),
alignment=ft.alignment.center,
padding=5,
width=140, # Fixed size for error card consistency
height=160,
on_click=on_card_click,
data=str(item_path) # Store path even for error state
),
elevation=1,
# Give error card a subtle red border maybe?
# border=ft.border.all(1, ft.colors.RED_ACCENT_700),
# border_radius=ft.border_radius.all(5)
)
# --- Image Widget ---
# Let the image expand to fill the Stack constraints
image_widget = ft.Image(
src=str(item_path),
fit=ft.ImageFit.COVER, # Cover the area, cropping if needed
error_content=ft.Icon(ft.Icons.BROKEN_IMAGE), # Fallback icon
expand=True # Make image fill the parent Stack
)
# --- Text Overlay ---
text_widget = ft.Text(
item_path.name,
size=11, # Slightly smaller font size
weight=ft.FontWeight.BOLD,
color=ft.Colors.WHITE,
text_align=ft.TextAlign.CENTER,
overflow=ft.TextOverflow.ELLIPSIS,
max_lines=1,
)
# Container for text + background, positioned at the bottom-center
text_overlay = ft.Container(
content=text_widget,
padding=ft.padding.symmetric(horizontal=5, vertical=2),
bgcolor=ft.colors.BLACK54, # Semi-transparent background
border_radius=ft.border_radius.all(4),
alignment=ft.alignment.center,
# Allow background to size horizontally, constrained by Stack
# Add margins for spacing from edges
margin=ft.margin.only(left=6, right=6, bottom=6),
)
# --- Stack for layering Image and Text ---
stack = ft.Stack(
[
image_widget,
# Container to position the text overlay within the Stack
ft.Container(
content=text_overlay,
alignment=ft.alignment.bottom_center, # Position overlay at the bottom
# No explicit width/height needed here, let Stack constraints handle it
)
],
# Define the size constraints for the Stack area
width=140, # Base width for the card content
height=160, # Base height for the card content
clip_behavior=ft.ClipBehavior.ANTI_ALIAS # Clip image to bounds if Card has radius
)
# --- The main Card ---
card = ft.Card(
content=ft.Container( # Container for click handling and potential padding/margins
content=stack,
on_click=on_card_click,
data=str(item_path), # Store path for the handler
# No fixed size here, let the Card define it
padding=0 # Ensure no extra padding from this container
),
elevation=2,
# --- Card Dimensions ---
# Define base dimensions for the card itself.
# The Row will arrange these. Use width/height or aspect_ratio.
width=150, # Slightly larger than stack content for visual spacing
height=175, # Slightly larger than stack content
# OR use aspect ratio if you prefer:
# aspect_ratio=150/175,
# width=150, # Set width and let aspect ratio define height
border_radius=ft.border_radius.all(8) # Nicer rounded corners
)
return card
# --- Example Usage ---
def main(page: ft.Page):
page.title = "Responsive Image Cards"
page.vertical_alignment = ft.MainAxisAlignment.START # Align content to the top
page.horizontal_alignment = ft.CrossAxisAlignment.CENTER
page.window_width = 400
page.window_height = 700
page.padding = 15
page.spacing = 20
# --- Create dummy image files for demonstration ---
image_dir = Path("./temp_image_assets")
image_dir.mkdir(exist_ok=True)
img_path1 = image_dir / "blue_square.png"
img_path2 = image_dir / "long_filename_image.jpg"
invalid_path = image_dir / "non_existent/missing.gif"
# Use Pillow if available to create simple images
try:
from PIL import Image, ImageDraw, ImageFont
if not img_path1.exists():
img = Image.new('RGB', (150, 150), color = 'skyblue')
img.save(img_path1)
if not img_path2.exists():
img = Image.new('RGB', (150, 150), color = 'lightcoral')
d = ImageDraw.Draw(img)
try:
# Try loading a font for the text
pil_font = ImageFont.truetype("arial.ttf", 15) # Common font
d.text((10, 65), "Long Name", fill=(255, 255, 255), font=pil_font)
except IOError:
d.text((10, 65), "Long Name", fill=(255, 255, 255)) # Fallback if font not found
img.save(img_path2)
print("Dummy images created successfully.")
except ImportError:
print("Pillow not found. Cannot create dummy images. Please ensure image files exist manually in ./temp_image_assets/")
except Exception as e:
print(f"Error creating dummy images: {e}")
# --- Click Handler ---
def handle_card_click(e):
path_clicked = Path(e.control.data) # Get path from the container's data
if path_clicked.is_file():
ft.tooltip.show_tooltip(f"Clicked: {path_clicked.name}")
print(f"Card clicked! Path: {path_clicked}")
# Example: Open image file using the default system application
# try:
# os.startfile(path_clicked) # Windows
# except AttributeError:
# import subprocess
# opener ="open" if sys.platform == "draw Darwin" else "xdg-open"
# subprocess.call([opener, str(path_clicked)])
else:
ft.tooltip.show_tooltip("Invalid card path clicked.")
print(f"Card clicked, but path is invalid: {path_clicked}")
# --- Create Card Instances ---
# Create a list of cards to demonstrate wrapping
image_files = [img_path1, img_path2, img_path1, img_path2, invalid_path, img_path1, img_path2, img_path1]
cards = [create_image_card(p, handle_card_click) for p in image_files]
# --- Layout ---
page.add(
ft.Column(
[
ft.Text("Gallery", size=24, weight=ft.FontWeight.BOLD),
# The Row handles horizontal layout, wrapping, and scrolling
ft.Row(
cards,
wrap=True, # Enable wrapping items to the next line
scroll=ft.ScrollMode.AUTO, # Add scrollbars if content overflows vertically
# Center the cards horizontally on each line
alignment=ft.MainAxisAlignment.CENTER,
# Align items within each line to the top
vertical_alignment=ft.CrossAxisAlignment.START,
expand=True # Allow the Row to take available width
),
],
expand=True, # Allow the Column to take available height
horizontal_alignment=ft.CrossAxisAlignment.CENTER # Center the Row within the Column
)
)
# Run the app
# Use ft.app() for standalone execution or integrate page.add() into an existing Flet app structure.
# Make sure Flet can find your images if they aren't in the script's directory.
# If images are in an 'assets' folder, run with: flet run your_script.py --assets-dir assets
# Or simply place them in the same directory as the script for this example.
ft.app(target=main)