import 'package:flutter/material.dart';
class DynamicListScreen extends StatefulWidget {
@override
State<DynamicListScreen> createState() => _DynamicListScreenState();
}
class _DynamicListScreenState extends State<DynamicListScreen> {
final List<String> items = ['Item 1', 'Item 2', 'Item 3'];
void _addItem() {
setState(() {
items.add('Item ${items.length + 1}');
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Dynamic List Screen'),
actions: [
IconButton(
icon: Icon(Icons.add),
onPressed: _addItem,
tooltip: 'Add Item',
),
],
),
body: ListView.builder(
itemCount: items.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(items[index]),
);
},
),
);
}
}
This solution uses a StatefulWidget to keep track of the list of items. The list starts with three items.
The _addItem method adds a new item with the next number to the list and calls setState to tell Flutter to update the screen.
The list is displayed using ListView.builder, which efficiently creates list tiles for each item in the list.
When the '+' button in the app bar is tapped, the list grows and the new item appears immediately. This shows how lists can display dynamic data that changes over time.