Sure! Let's enhance your Flutter web application to make it more modern, user-friendly, and visually appealing. Below are the key improvements we'll implement:
-
Modern Color Scheme and Typography:
- Use a more refined color palette with subtle gradients.
- Utilize modern fonts and consistent typography.
-
Responsive Layout:
- Ensure the app looks great on various screen sizes.
- Use
LayoutBuilder to adjust the layout based on available space.
-
Enhanced Navigation and Controls:
- Replace the simple toggle button with a more intuitive interface.
- Use icons to represent actions clearly.
-
Improved Cards and List Items:
- Add shadows, rounded corners, and better spacing.
- Incorporate animations for interactions.
-
Animations and Transitions:
- Implement smooth transitions between views.
- Use animated widgets for a dynamic feel.
-
Clean and Minimal UI:
- Remove redundant buttons and elements.
- Focus on essential functionalities with a clean layout.
Below is the revamped main.dart with these enhancements:
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:table_calendar/table_calendar.dart';
import 'package:flutter/services.dart' show rootBundle;
const String dataFilePath = 'lib/data.json';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Facility Hours',
debugShowCheckedModeBanner: false,
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(
seedColor: Colors.teal,
primary: Colors.teal,
secondary: Colors.blue.shade300,
background: Colors.teal.shade50,
surface: Colors.white,
onPrimary: Colors.white,
onSecondary: Colors.white,
onBackground: Colors.black87,
onSurface: Colors.black87,
),
useMaterial3: true,
fontFamily: 'Inter',
),
home: const DateInfoPage(),
);
}
}
class DateInfoPage extends StatefulWidget {
const DateInfoPage({super.key});
@override
State createState() => _DateInfoPageState();
}
class _DateInfoPageState extends State<DateInfoPage>
with SingleTickerProviderStateMixin {
List<dynamic> _data = [];
DateTime _selectedDay = DateTime.now();
DateTime _focusedDay = DateTime.now();
CalendarFormat _calendarFormat = CalendarFormat.month;
String _selectedFacility = 'Gym';
List<String> _facilities = [];
bool _showCalendar = true;
late AnimationController _animationController;
late Animation<double> _fadeAnimation;
@override
void initState() {
super.initState();
_loadData();
_animationController = AnimationController(
duration: const Duration(milliseconds: 500),
vsync: this,
);
_fadeAnimation =
CurvedAnimation(parent: _animationController, curve: Curves.easeIn);
}
@override
void dispose() {
_animationController.dispose();
super.dispose();
}
Future<void> _loadData() async {
try {
String jsonString = await rootBundle.loadString(dataFilePath);
final List<dynamic> jsonData = json.decode(jsonString);
setState(() {
_data = jsonData;
_facilities = _data
.map((event) => event['facilityname'] as String)
.toSet()
.toList();
if (!_facilities.contains(_selectedFacility)) {
_selectedFacility =
_facilities.isNotEmpty ? _facilities[0] : 'Gym';
}
});
} catch (e) {
print('Error loading data: $e');
setState(() {
_data = [];
_facilities = ['Gym'];
_selectedFacility = 'Gym';
});
}
}
List<dynamic> _getEventsForDay(DateTime day) {
return _data.where((event) {
final eventStart = DateTime.parse(event['start']).toUtc();
final dayUtc = DateTime.utc(day.year, day.month, day.day);
return isSameDay(eventStart, dayUtc) &&
event['facilityname'] == _selectedFacility;
}).toList();
}
String _formatTime(String dateTimeString) {
final dateTime = DateTime.parse(dateTimeString);
return DateFormat('h:mm a').format(dateTime);
}
String _calculateDuration(String start, String end) {
final startTime = DateTime.parse(start);
final endTime = DateTime.parse(end);
final duration = endTime.difference(startTime);
final hours = duration.inHours;
final minutes = duration.inMinutes % 60;
return '${hours}h ${minutes}m';
}
void _showEventDetails(dynamic event) {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text('${event['title']} Details'),
content: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Text(
'Date: ${DateFormat('yyyy-MM-dd').format(DateTime.parse(event['start']))}'),
Text('Facility: ${event['facilityname']}'),
Text('Start: ${_formatTime(event['start'])}'),
Text('End: ${_formatTime(event['end'])}'),
Text(
'Duration: ${_calculateDuration(event['start'], event['end'])}'),
if (event['description'] != null &&
event['description'].isNotEmpty)
Text('Description: ${event['description']}'),
],
),
actions: [
TextButton(
child: const Text('Close'),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
},
);
}
Widget _buildCalendar() {
return FadeTransition(
opacity: _fadeAnimation,
child: TableCalendar(
firstDay: DateTime.utc(2024, 1, 1),
lastDay: DateTime.utc(2024, 12, 31),
focusedDay: _focusedDay,
selectedDayPredicate: (day) => isSameDay(_selectedDay, day),
calendarFormat: _calendarFormat,
availableCalendarFormats: const {
CalendarFormat.month: 'Month',
CalendarFormat.twoWeeks: '2 Weeks',
CalendarFormat.week: 'Week',
},
eventLoader: _getEventsForDay,
onDaySelected: (selectedDay, focusedDay) {
setState(() {
_selectedDay = selectedDay;
_focusedDay = focusedDay;
});
},
onFormatChanged: (format) {
setState(() {
_calendarFormat = format;
});
},
onPageChanged: (focusedDay) {
_focusedDay = focusedDay;
},
headerStyle: HeaderStyle(
formatButtonVisible: false,
titleCentered: true,
leftChevronIcon: const Icon(Icons.chevron_left),
rightChevronIcon: const Icon(Icons.chevron_right),
titleTextStyle: TextStyle(
color: Theme.of(context).colorScheme.primary,
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
calendarStyle: CalendarStyle(
todayDecoration: BoxDecoration(
color:
Theme.of(context).colorScheme.secondary.withOpacity(0.5),
shape: BoxShape.circle,
),
selectedDecoration: BoxDecoration(
color: Theme.of(context).colorScheme.primary,
shape: BoxShape.circle,
),
weekendTextStyle: const TextStyle(color: Colors.black),
markerDecoration: BoxDecoration(
shape: BoxShape.circle,
color: Theme.of(context).colorScheme.secondary,
),
),
calendarBuilders: CalendarBuilders(
markerBuilder: (context, date, events) {
if (events.isNotEmpty) {
return Positioned(
bottom: 1,
child: Container(
decoration: BoxDecoration(
shape: BoxShape.circle,
color: Theme.of(context).colorScheme.secondary,
),
width: 6.0,
height: 6.0,
),
);
}
return null;
},
),
),
);
}
Widget _buildTileList() {
final selectedMonth = _selectedDay.month;
final eventsForMonth = _data.where((event) {
final eventDate = DateTime.parse(event['start']);
return eventDate.month == selectedMonth &&
event['facilityname'] == _selectedFacility;
}).toList();
if (eventsForMonth.isEmpty) {
return const Center(
child: Text(
'No events scheduled for this month.',
style: TextStyle(fontSize: 16),
));
}
return ListView.builder(
padding: const EdgeInsets.symmetric(vertical: 8.0),
itemCount: eventsForMonth.length,
itemBuilder: (context, index) {
final event = eventsForMonth[index];
return Padding(
padding:
const EdgeInsets.symmetric(horizontal: 16.0, vertical: 6.0),
child: Card(
elevation: 3,
shape:
RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
child: ListTile(
leading: Icon(
Icons.event_note,
color: Theme.of(context).colorScheme.primary,
size: 30,
),
title: Text(
'${_formatTime(event['start'])} - ${_formatTime(event['end'])}',
style: TextStyle(
fontWeight: FontWeight.w600,
color: Theme.of(context).colorScheme.primary,
),
),
subtitle: Text(
'${event['title']} at ${event['facilityname']}',
style: TextStyle(
color: Theme.of(context).colorScheme.secondary,
),
),
trailing: const Icon(Icons.arrow_forward_ios, size: 16),
onTap: () => _showEventDetails(event),
),
),
);
},
);
}
void _toggleView() {
setState(() {
_showCalendar = !_showCalendar;
if (_showCalendar) {
_animationController.reverse();
} else {
_animationController.forward();
}
});
}
@override
Widget build(BuildContext context) {
final isLargeScreen = MediaQuery.of(context).size.width > 800;
return Scaffold(
appBar: AppBar(
title: Text('${_selectedFacility} Hours'),
centerTitle: true,
backgroundColor: Theme.of(context).colorScheme.primary,
foregroundColor: Colors.white,
actions: [
Padding(
padding: const EdgeInsets.symmetric(horizontal: 12.0),
child: DropdownButtonHideUnderline(
child: DropdownButton<String>(
value: _selectedFacility,
icon: const Icon(Icons.arrow_drop_down, color: Colors.white),
dropdownColor: Theme.of(context).colorScheme.primary,
style: const TextStyle(color: Colors.white),
onChanged: (String? newValue) {
if (newValue != null) {
setState(() {
_selectedFacility = newValue;
});
}
},
items: _facilities
.map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value,
style: const TextStyle(color: Colors.white)),
);
}).toList(),
),
),
),
],
),
body: Container(
padding: const EdgeInsets.all(16.0),
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [
Theme.of(context).colorScheme.background,
Colors.white,
],
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
),
),
child: isLargeScreen
? Row(
children: [
Expanded(
flex: 2,
child: Column(
children: [
_buildCalendar(),
const SizedBox(height: 16),
ElevatedButton.icon(
onPressed: _toggleView,
icon: Icon(
_showCalendar
? Icons.list_alt
: Icons.calendar_today,
),
label: Text(
_showCalendar ? 'Show List' : 'Show Calendar'),
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.symmetric(
horizontal: 20, vertical: 12),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8),
),
),
),
],
),
),
const SizedBox(width: 16),
Expanded(
flex: 3,
child: _showCalendar
? _buildEventListWithFade()
: _buildTileList(),
),
],
)
: Column(
children: [
_buildCalendar(),
const SizedBox(height: 16),
ElevatedButton.icon(
onPressed: _toggleView,
icon: Icon(
_showCalendar ? Icons.list_alt : Icons.calendar_today,
),
label:
Text(_showCalendar ? 'Show List' : 'Show Calendar'),
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.symmetric(
horizontal: 20, vertical: 12),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8),
),
),
),
const SizedBox(height: 16),
Expanded(
child: _showCalendar
? _buildEventListWithFade()
: _buildTileList(),
),
],
),
),
);
}
Widget _buildEventListWithFade() {
return FadeTransition(
opacity: _fadeAnimation,
child: _buildEventList(),
);
}
Widget _buildEventList() {
List<dynamic> eventsForSelectedDay = _getEventsForDay(_selectedDay);
if (eventsForSelectedDay.isEmpty) {
return const Center(
child: Text(
'No events scheduled for this day.',
style: TextStyle(fontSize: 16),
));
}
return ListView.builder(
padding: const EdgeInsets.symmetric(vertical: 8.0),
itemCount: eventsForSelectedDay.length,
itemBuilder: (context, index) {
final event = eventsForSelectedDay[index];
return Padding(
padding:
const EdgeInsets.symmetric(horizontal: 16.0, vertical: 6.0),
child: Card(
elevation: 3,
shape:
RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
child: ListTile(
leading: Icon(
Icons.event_note,
color: Theme.of(context).colorScheme.primary,
size: 30,
),
title: Text(
'${_formatTime(event['start'])} - ${_formatTime(event['end'])}',
style: TextStyle(
fontWeight: FontWeight.w600,
color: Theme.of(context).colorScheme.primary,
),
),
subtitle: Text(
'Duration: ${_calculateDuration(event['start'], event['end'])}',
style: TextStyle(
color: Theme.of(context).colorScheme.secondary,
),
),
trailing: const Icon(Icons.arrow_forward_ios, size: 16),
onTap: () => _showEventDetails(event),
),
),
);
},
);
}
}
Key Enhancements Explained
-
Modern Color Scheme and Typography:
- ColorScheme: Expanded to include
surface, onPrimary, onSecondary, etc., for better theming consistency.
- Font Family: Using 'Inter' for a clean and modern look.
-
Responsive Layout:
- Utilized
MediaQuery to adjust layout based on screen width. For larger screens, the calendar and event list are displayed side by side. For smaller screens, they are stacked vertically.
-
Enhanced Navigation and Controls:
- Dropdown Button: Styled dropdown with icons and better alignment in the AppBar.
- Toggle Button: Replaced simple
ElevatedButton with ElevatedButton.icon for better visual cues using icons.
-
Improved Cards and List Items:
- Card Styling: Added rounded corners and elevation for better depth.
- Icons: Included relevant icons (
Icons.event_note, Icons.arrow_forward_ios) to make actions more intuitive.
- List Tiles: Enhanced with better text styles and spacing.
-
Animations and Transitions:
- FadeTransition: Added fade-in animations when switching views to make transitions smoother.
- AnimationController: Manages the animation state when toggling views.
-
Clean and Minimal UI:
- Removed redundant UI elements and focused on essential functionalities.
- Ensured consistent padding and margins for a balanced layout.
-
Interactivity Enhancements:
- Calendar Format Change: Allowed users to switch between different calendar formats (month, 2 weeks, week).
- Event Markers: Styled event markers with subtle circles at the bottom of dates with events.
Additional Recommendations
-
Lazy Loading:
- For larger datasets, consider implementing lazy loading or pagination to enhance performance.
-
Dark Mode Support:
- Implement a toggle for dark mode to improve user experience in different lighting conditions.
-
Accessibility:
- Ensure that all interactive elements are accessible via keyboard and screen readers.
- Use appropriate contrast ratios for text and background colors.
-
Tooltips and Help Icons:
- Add tooltips or help icons to assist users in understanding functionalities.
-
Testing Across Browsers:
- Test the web app across different browsers to ensure consistency and performance.
-
Data Caching:
- Implement caching strategies to reduce data loading times and improve responsiveness.
Final Touch: Adding Animations to Cards
To make the event cards more dynamic, you can add subtle animations when they appear. Here's how to modify the card builder to include slide-in animations:
Widget _buildTileList() {
final selectedMonth = _selectedDay.month;
final eventsForMonth = _data.where((event) {
final eventDate = DateTime.parse(event['start']);
return eventDate.month == selectedMonth &&
event['facilityname'] == _selectedFacility;
}).toList();
if (eventsForMonth.isEmpty) {
return const Center(
child: Text(
'No events scheduled for this month.',
style: TextStyle(fontSize: 16),
));
}
return ListView.builder(
padding: const EdgeInsets.symmetric(vertical: 8.0),
itemCount: eventsForMonth.length,
itemBuilder: (context, index) {
final event = eventsForMonth[index];
return TweenAnimationBuilder(
tween: Tween<Offset>(
begin: const Offset(1, 0), end: Offset.zero),
duration: const Duration(milliseconds: 500),
curve: Curves.easeOut,
builder: (context, Offset offset, child) {
return SlideTransition(
position: Tween<Offset>(
begin: Offset(offset.dx, offset.dy),
end: Offset.zero,
).animate(CurvedAnimation(
parent: _animationController,
curve: Curves.easeOut,
)),
child: child,
);
},
child: Padding(
padding:
const EdgeInsets.symmetric(horizontal: 16.0, vertical: 6.0),
child: Card(
elevation: 3,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12)),
child: ListTile(
leading: Icon(
Icons.event_note,
color: Theme.of(context).colorScheme.primary,
size: 30,
),
title: Text(
'${_formatTime(event['start'])} - ${_formatTime(event['end'])}',
style: TextStyle(
fontWeight: FontWeight.w600,
color: Theme.of(context).colorScheme.primary,
),
),
subtitle: Text(
'${event['title']} at ${event['facilityname']}',
style: TextStyle(
color: Theme.of(context).colorScheme.secondary,
),
),
trailing: const Icon(Icons.arrow_forward_ios, size: 16),
onTap: () => _showEventDetails(event),
),
),
),
);
},
);
}
Conclusion
These enhancements should make your Flutter web application more modern, intuitive, and visually appealing. Feel free to adjust the color schemes, icons, and animations to better fit your brand or personal preferences. If you have any specific design elements or functionalities you'd like to implement, let me know!