Skip to content

Instantly share code, notes, and snippets.

@callmephil
Created November 11, 2024 10:37
Show Gist options
  • Save callmephil/7053a280e996f31360b29853dd02e26c to your computer and use it in GitHub Desktop.
Save callmephil/7053a280e996f31360b29853dd02e26c to your computer and use it in GitHub Desktop.
Modifial List Example
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class Item {
const Item({required this.id, required this.name, required this.likeCount});
final String id;
final String name;
final int likeCount;
Item copyWith({int? likeCount}) {
return Item(
id: id,
name: name,
likeCount: likeCount ?? this.likeCount,
);
}
}
class MyApp extends StatefulWidget {
const MyApp({super.key});
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
List<Item> items = List.generate(
1000,
(i) => Item(id: '$i', name: 'Item $i', likeCount: 0),
);
void onLike(String id) {
setState(() {
items = items.map((item) {
if (item.id == id) {
return item.copyWith(likeCount: item.likeCount + 1);
}
return item;
}).toList();
});
}
void addItem() {
final listLength = items.length;
setState(() {
items.add(
Item(
id: '${listLength + 1}',
name: 'Item ${listLength - 1}',
likeCount: 0),
);
});
}
void removeItem(String id) {
setState(() {
items.removeWhere((item) => item.id == id);
});
}
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
appBar: AppBar(
title: const Text('Item List with Likes'),
),
body: ListView.builder(
itemCount: items.length,
itemBuilder: (context, index) {
final item = items[index];
return ListTile(
title: Text(item.name),
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: [
Text('${item.likeCount}'),
IconButton(
icon: const Icon(Icons.thumb_up),
onPressed: () => onLike(item.id),
),
IconButton(
icon: const Icon(Icons.delete),
onPressed: () => removeItem(item.id),
),
],
),
);
},
),
floatingActionButton: FloatingActionButton(
onPressed: addItem,
child: const Icon(Icons.add),
),
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment