From 9a0997c3a75f9201db2cdbeb4163c3bfc2a8b06d Mon Sep 17 00:00:00 2001 From: xengineering Date: Sat, 3 Jan 2026 11:28:04 +0100 Subject: Make one contact toggle with timer This demonstrates that the state of the contacts in the UI can be changed at runtime. --- lib/main.dart | 37 +++++++++++++++++++++++++++++-------- 1 file changed, 29 insertions(+), 8 deletions(-) (limited to 'lib') diff --git a/lib/main.dart b/lib/main.dart index db8fcd2..b4cae3a 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -1,3 +1,5 @@ +import 'dart:async'; + import 'package:flutter/material.dart'; void main() { @@ -17,9 +19,9 @@ class MainApp extends StatelessWidget { class Contact { final String address; - final bool isOpen; + bool isOpen; - const Contact({required this.address, required this.isOpen}); + Contact({required this.address, required this.isOpen}); } class ContactList extends StatefulWidget { @@ -30,13 +32,32 @@ class ContactList extends StatefulWidget { } class _ContactListState extends State { + late final List contacts; + Timer? _timer; + + @override + void initState() { + super.initState(); + + contacts = [ + Contact(address: "Living Room Window", isOpen: false), + Contact(address: "Front Door", isOpen: true), + Contact(address: "Back Door", isOpen: false), + Contact(address: "Garage Window", isOpen: true), + ]; - final List contacts = const [ - Contact(address: "Living Room Window", isOpen: false), - Contact(address: "Front Door", isOpen: true), - Contact(address: "Back Door", isOpen: false), - Contact(address: "Garage Window", isOpen: true), - ]; + _timer = Timer.periodic(const Duration(seconds: 1), (_) { + setState(() { + contacts[0].isOpen = !contacts[0].isOpen; + }); + }); + } + + @override + void dispose() { + _timer?.cancel(); + super.dispose(); + } @override Widget build(BuildContext context) { -- cgit v1.2.3-70-g09d2