7. Develop a “Stopwatch” application using Flutter.
Step to Run
- Open your Flutter project in VS Code.
- Open
lib/main.dart. - Delete the existing code.
- Paste the program code given below.
- Save the file.
- Run the program using
flutter runcmd
PROGRAM:
import 'dart:async';
import 'package:flutter/material.dart';
void main() {
runApp(const StopwatchApp());
}
class StopwatchApp extends StatelessWidget {
const StopwatchApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Lab Program 7',
debugShowCheckedModeBanner: false,
home: const StopwatchScreen(),
);
}
}
class StopwatchScreen extends StatefulWidget {
const StopwatchScreen({super.key});
@override
State<StopwatchScreen> createState() => _StopwatchScreenState();
}
class _StopwatchScreenState extends State<StopwatchScreen> {
int seconds = 0;
Timer? timer;
bool isRunning = false;
void startStopwatch() {
if (!isRunning) {
timer = Timer.periodic(const Duration(seconds: 1), (timer) {
setState(() {
seconds++;
});
});
setState(() {
isRunning = true;
});
}
}
void stopStopwatch() {
timer?.cancel();
setState(() {
isRunning = false;
});
}
void resetStopwatch() {
timer?.cancel();
setState(() {
seconds = 0;
isRunning = false;
});
}
String formatTime(int totalSeconds) {
int minutes = totalSeconds ~/ 60;
int remainingSeconds = totalSeconds % 60;
String minutesText = minutes.toString().padLeft(2, '0');
String secondsText = remainingSeconds.toString().padLeft(2, '0');
return '$minutesText:$secondsText';
}
@override
void dispose() {
timer?.cancel();
super.dispose();
}
Widget stopwatchButton({
required String text,
required Color color,
required VoidCallback onPressed,
}) {
return ElevatedButton(
onPressed: onPressed,
style: ElevatedButton.styleFrom(
backgroundColor: color,
foregroundColor: Colors.white,
padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 14),
),
child: Text(
text,
style: const TextStyle(fontSize: 18),
),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Program 7: Stopwatch'),
centerTitle: true,
backgroundColor: Colors.blue,
foregroundColor: Colors.white,
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Icon(
Icons.timer,
size: 90,
color: Colors.blue,
),
const SizedBox(height: 30),
Text(
formatTime(seconds),
style: const TextStyle(
fontSize: 60,
fontWeight: FontWeight.bold,
color: Colors.blue,
),
),
const SizedBox(height: 40),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
stopwatchButton(
text: 'Start',
color: Colors.green,
onPressed: startStopwatch,
),
const SizedBox(width: 12),
stopwatchButton(
text: 'Stop',
color: Colors.orange,
onPressed: stopStopwatch,
),
const SizedBox(width: 12),
stopwatchButton(
text: 'Reset',
color: Colors.red,
onPressed: resetStopwatch,
),
],
),
],
),
),
);
}
}OUTPUT:

