From ee38d5671e0d6b8d0e1d3708a37b43a65682329f Mon Sep 17 00:00:00 2001 From: xengineering Date: Mon, 5 Jan 2026 14:48:50 +0100 Subject: Move state to data.dart The UI should not store the application logic state. --- lib/ui.dart | 74 ++++++++++++++----------------------------------------------- 1 file changed, 17 insertions(+), 57 deletions(-) (limited to 'lib/ui.dart') diff --git a/lib/ui.dart b/lib/ui.dart index 5397044..d4618cf 100644 --- a/lib/ui.dart +++ b/lib/ui.dart @@ -1,6 +1,5 @@ -import 'dart:async'; - import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; import 'data.dart'; @@ -15,69 +14,30 @@ class UI extends StatelessWidget { } } -class ContactList extends StatefulWidget { +class ContactList extends StatelessWidget { const ContactList({super.key}); - @override - State createState() => _ContactListState(); -} - -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), - ]; - - _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) { return Scaffold( appBar: AppBar(title: const Text("Contacts")), - body: ListView.builder( - itemCount: contacts.length, - itemBuilder: (BuildContext context, int index) { - final Contact contact = contacts[index]; - return ContactTile(contact: contact); + body: Consumer( + builder: (BuildContext context, AppState state, Widget? child) { + return ListView.builder( + itemCount: state.contacts.length, + itemBuilder: (BuildContext context, int index) { + final Contact contact = state.contacts[index]; + return ListTile( + leading: Icon( + contact.isOpen ? Icons.meeting_room : Icons.door_front_door, + color: contact.isOpen ? Colors.red : Colors.green, + ), + title: Text(contact.address), + ); + }, + ); }, ), ); } } - -class ContactTile extends StatelessWidget { - final Contact contact; - - const ContactTile({super.key, required this.contact}); - - @override - Widget build(BuildContext context) { - return ListTile( - leading: Icon( - contact.isOpen ? Icons.meeting_room : Icons.door_front_door, - color: contact.isOpen ? Colors.red : Colors.green, - ), - title: Text(contact.address), - ); - } -} -- cgit v1.2.3-70-g09d2