Skip to content

RN Lez 28: Platform e ColorScheme

Docs: Platform Specific Code, Appearance, useColorScheme

  • Rilevare la piattaforma (Android/iOS)
  • Scrivere codice specifico per piattaforma
  • Implementare tema chiaro/scuro

import { Platform, StyleSheet } from 'react-native';
const styles = StyleSheet.create({
altezza: {
height: Platform.OS === 'ios' ? 200 : 100,
},
});
Platform.OS // 'ios' | 'android' | 'web' | 'windows' | 'macos'

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',
},
}),
},
});

Crea file separati per piattaforma:

Card.ios.tsx ← iOS
Card.android.tsx ← Android
import Card from './Card'; // carica automaticamente il file giusto!

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>
);
}

const [darkMode, setDarkMode] = useState(false);
const scheme = useColorScheme();
// Usa preferenza sistema di default
useEffect(() => {
if (scheme === 'dark') setDarkMode(true);
}, [scheme]);
const theme = {
bg: darkMode ? '#1a1a2e' : '#f5f5f5',
text: darkMode ? '#eee' : '#333',
card: darkMode ? '#16213e' : 'white',
primary: '#3498db',
};

APICodiceUso
Platform.OSPlatform.OS === 'ios'Rilevare piattaforma
Platform.selectPlatform.select({ ios: ..., android: ... })Valori per piattaforma
useColorSchemeconst s = useColorScheme()Rilevare tema sistema

Crea un’app che:

  1. Usa useColorScheme() per rilevare tema sistema
  2. Ha un toggle manuale per forzare chiaro/scuro
  3. Salva la preferenza in AsyncStorage
  4. Applica tema a: sfondo, testo, card, header
  5. Mostra icone diverse per tema (☀️/🌙)