my_timezone 0.1.0
my_timezone: ^0.1.0 copied to clipboard
A Flutter plugin for local IANA time zone details, available identifiers, and change events on Android, iOS, macOS, and web.
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:my_timezone/my_timezone.dart';
void main() => runApp(const MyApp());
class MyApp extends StatefulWidget {
const MyApp({super.key});
@override
State<MyApp> createState() => MyAppState();
}
class MyAppState extends State<MyApp> {
TimezoneInfo? _timezoneInfo;
List<String> _availableTimezones = <String>[];
StreamSubscription<TimezoneInfo>? _timezoneSubscription;
@override
void initState() {
super.initState();
_timezoneSubscription = MyTimezone.onTimezoneChanged.listen(
_updateTimezone,
onError: (Object error) {
debugPrint('Could not observe timezone changes: $error');
},
);
_initData();
}
@override
void dispose() {
_timezoneSubscription?.cancel();
super.dispose();
}
Future<void> _initData() async {
try {
_timezoneInfo = await MyTimezone.getLocalTimezoneInfo();
} on PlatformException catch (error) {
debugPrint('Could not get the local timezone: $error');
}
try {
_availableTimezones = await MyTimezone.getAvailableTimezones();
_availableTimezones.sort();
} on PlatformException catch (error) {
debugPrint('Could not get available timezones: $error');
}
if (mounted) {
setState(() {});
}
}
void _updateTimezone(TimezoneInfo timezoneInfo) {
if (!mounted) return;
setState(() => _timezoneInfo = timezoneInfo);
}
@override
Widget build(BuildContext context) {
final timezoneInfo = _timezoneInfo;
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('Local timezone app')),
body: Column(
children: <Widget>[
Text(
'Local timezone: ${timezoneInfo?.identifier ?? 'Unknown'}\n'
'Name: ${timezoneInfo?.localizedName ?? 'Unavailable'}\n'
'Abbreviation: ${timezoneInfo?.abbreviation ?? 'Unavailable'}\n'
'UTC offset: ${timezoneInfo?.utcOffset ?? 'Unavailable'}\n'
'DST active: '
'${timezoneInfo?.isDaylightSavingTime ?? 'Unavailable'}\n',
),
const Text('Available timezones:'),
Expanded(
child: ListView.builder(
itemCount: _availableTimezones.length,
itemBuilder: (_, index) => Text(_availableTimezones[index]),
),
),
],
),
),
);
}
}