Orari con DateFormat
Fa parte della sezione Dati e rete del percorso Flutter di Coddy. Lezione 21 di 27.
Lo stesso DateTime contiene anche l’ora, e DateFormat la formatta con le proprie lettere:
final start = DateTime.parse('2026-11-03T18:30:00');
DateFormat('h:mm a').format(start) // 6:30 PM
DateFormat('HH:mm').format(start) // 18:30h indica l’ora su un orologio a 12 ore e H su un orologio a 24 ore, mm i minuti e a aggiunge AM o PM. Due lettere mantengono uno zero iniziale: HH scrive le 9 come 09.
Fai attenzione di nuovo alle maiuscole. mm minuscolo indica i minuti e MM maiuscolo il mese: h:MM a trasforma le 6:30 PM di novembre in 6:11 PM, perché novembre è il mese 11.
Sfida
FacileMostra quando inizia ogni evento: aggiungi a ogni ListTile un testo trailing con l’ora, in modo che il primo evento mostri 6:30 PM.
Provalo tu
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'api.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
debugShowCheckedModeBanner: false,
home: EventsScreen(),
);
}
}
class EventsScreen extends StatefulWidget {
const EventsScreen({super.key});
@override
State<EventsScreen> createState() => _EventsScreenState();
}
class _EventsScreenState extends State<EventsScreen> {
late Future<List<Event>> _events;
@override
void initState() {
super.initState();
_events = loadEvents();
}
Future<List<Event>> loadEvents() async {
final body = await fetch('/events');
final items = jsonDecode(body) as List<dynamic>;
return items.map((item) => Event.fromJson(item as Map<String, dynamic>)).toList();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Events')),
body: FutureBuilder<List<Event>>(
future: _events,
builder: (context, snapshot) {
if (snapshot.hasError) {
return Center(child: Text('Could not load: ${snapshot.error}'));
}
if (snapshot.hasData) {
final events = snapshot.data!;
return ListView.builder(
itemCount: events.length,
itemBuilder: (context, index) {
final event = events[index];
return ListTile(
title: Text(event.title),
subtitle: Text(DateFormat('EEE, MMM d').format(event.start)),
);
},
);
}
return const Center(child: CircularProgressIndicator());
},
),
);
}
}
class Event {
Event({required this.title, required this.start});
final String title;
final DateTime start;
factory Event.fromJson(Map<String, dynamic> json) {
return Event(
title: json['title'] as String,
start: DateTime.parse(json['start'] as String),
);
}
}
Questa lezione include un breve quiz. Inizia la lezione per rispondere e tenere traccia dei tuoi progressi.
Tutte le lezioni di Dati e rete
Esercitati da solo: Compilatore Flutter online