I'm new in Flutter, and recently I have encountered with a challange. I have the following files:
- main.dart
import 'package:chatgpt_chat/testpage.dart';
import 'package:flutter/material.dart';
void main() => runApp(const TestAPP());
class TestAPP extends StatelessWidget {
const TestAPP({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: TestScaffold(),
);
}
}
class TestScaffold extends StatefulWidget {
const TestScaffold({super.key});
@override
State<TestScaffold> createState() => _TestScaffoldState();
}
class _TestScaffoldState extends State<TestScaffold> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Timer Example'),
),
body: const Center(
child: TimerWidget(),
),
floatingActionButton: FloatingActionButton(onPressed: (){}),
);
}
}
- timerWidget.dart:
import 'dart:async';
import 'package:flutter/material.dart';
class TimerWidget extends StatefulWidget {
const TimerWidget({Key? key}) : super(key: key);
@override
State<TimerWidget> createState() => _TimerWidgetState();
}
class _TimerWidgetState extends State<TimerWidget> {
int _seconds = 0;
late Timer _timer;
@override
void initState() {
super.initState();
_startTimer();
}
void _startTimer() {
_timer = Timer.periodic(const Duration(seconds: 1), (timer) {
setState(() {
_seconds++;
});
});
}
void _stopTimer() {
_timer.cancel();
}
void _resetTimer() {
setState(() {
_seconds = 0;
});
}
@override
void dispose() {
_stopTimer();
super.dispose();
}
@override
Widget build(BuildContext context) {
String formattedTime = _formatTime(_seconds);
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
formattedTime,
style: const TextStyle(fontSize: 24),
),
const SizedBox(height: 16),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ElevatedButton(
onPressed: _stopTimer,
child: const Text('Stop'),
),
const SizedBox(width: 16),
ElevatedButton(
onPressed: _resetTimer,
child: const Text('Reset'),
),
],
),
],
);
}
String _formatTime(int seconds) {
int minutes = seconds ~/ 60;
int remainingSeconds = seconds % 60;
return '$minutes:${remainingSeconds.toString().padLeft(2, '0')}';
}
}
Could you please help me out by showing how I can call startTimer method from TimerWidget in FloatingActionButton? I have a problem in different program, and solving this particular problem will help me out. I really appreciate it if you provide your solutions.
I looked for similar posts, however they do not fully solve my problem. I just have to use startTimer method in floatingActionButton