RN Lez 28: Platform e ColorScheme
Docs: Platform Specific Code, Appearance, useColorScheme
Obiettivi
Section titled “Obiettivi”- Rilevare la piattaforma (Android/iOS)
- Scrivere codice specifico per piattaforma
- Implementare tema chiaro/scuro
1. Platform.OS
Section titled “1. Platform.OS”import { Platform, StyleSheet } from 'react-native';
const styles = StyleSheet.create({ altezza: { height: Platform.OS === 'ios' ? 200 : 100, },});Valori di Platform.OS
Section titled “Valori di Platform.OS”Platform.OS // 'ios' | 'android' | 'web' | 'windows' | 'macos'2. Platform.select
Section titled “2. Platform.select”import { Platform } from 'react-native';
const styles = StyleSheet.create({ container: { ...Platform.select({ ios: { backgroundColor: 'red', shadowColor: '#000', }, android: { backgroundColor: 'green', elevation: 5, }, default: { backgroundColor: 'blue', }, }), },});3. Platform-specific file extensions
Section titled “3. Platform-specific file extensions”Crea file separati per piattaforma:
Card.ios.tsx ← iOSCard.android.tsx ← Androidimport Card from './Card'; // carica automaticamente il file giusto!4. useColorScheme — tema sistema
Section titled “4. useColorScheme — tema sistema”import { useColorScheme } from 'react-native';import { useState, useEffect } from 'react';
export default function App() { const scheme = useColorScheme(); // 'light' | 'dark' | null const isDark = scheme === 'dark';
const colors = { background: isDark ? '#1a1a2e' : '#f5f5f5', text: isDark ? '#eee' : '#333', card: isDark ? '#16213e' : 'white', };
return ( <View style={{ flex: 1, backgroundColor: colors.background }}> <Text style={{ color: colors.text }}> Il tema è {isDark ? '🌙 scuro' : '☀️ chiaro'} </Text> </View> );}5. Dark Mode con persistenza
Section titled “5. Dark Mode con persistenza”const [darkMode, setDarkMode] = useState(false);const scheme = useColorScheme();
// Usa preferenza sistema di defaultuseEffect(() => { if (scheme === 'dark') setDarkMode(true);}, [scheme]);
const theme = { bg: darkMode ? '#1a1a2e' : '#f5f5f5', text: darkMode ? '#eee' : '#333', card: darkMode ? '#16213e' : 'white', primary: '#3498db',};6. Tabella riassuntiva
Section titled “6. Tabella riassuntiva”| API | Codice | Uso |
|---|---|---|
| Platform.OS | Platform.OS === 'ios' | Rilevare piattaforma |
| Platform.select | Platform.select({ ios: ..., android: ... }) | Valori per piattaforma |
| useColorScheme | const s = useColorScheme() | Rilevare tema sistema |
7. Esercizio
Section titled “7. Esercizio”🎯 “App con tema dinamico”
Section titled “🎯 “App con tema dinamico””Crea un’app che:
- Usa
useColorScheme()per rilevare tema sistema - Ha un toggle manuale per forzare chiaro/scuro
- Salva la preferenza in AsyncStorage
- Applica tema a: sfondo, testo, card, header
- Mostra icone diverse per tema (☀️/🌙)