Skip to content

Instantly share code, notes, and snippets.

@pmatatias
Created December 28, 2023 02:45
Show Gist options
  • Save pmatatias/fff47dc09b53e1ea94a3ed889ebba383 to your computer and use it in GitHub Desktop.
Save pmatatias/fff47dc09b53e1ea94a3ed889ebba383 to your computer and use it in GitHub Desktop.
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
@immutable
class UserProfile {
final String name;
final List<String> friends;
UserProfile(this.name, this.friends);
UserProfile addFriend(String friendId) {
return UserProfile(name, List.from(friends)..add(friendId));
}
UserProfile removeLastFriend() {
if (friends.isEmpty) return this;
return UserProfile(name, List.from(friends)..removeLast());
}
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: HomeScreen(),
);
}
}
class HomeScreen extends StatefulWidget {
@override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
UserProfile userProfile = UserProfile('John Doe', []);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Immutable State Demo')),
body: Column(
children: [
// Displaying friends
Expanded(
child: ListView.builder(
itemCount: userProfile.friends.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(userProfile.friends[index]),
);
},
),
),
// Button to add a friend
ElevatedButton(
child: Text('Add Friend'),
onPressed: () {
setState(() {
userProfile = userProfile.addFriend('Friend ${userProfile.friends.length + 1}');
});
},
),
// Button to remove the last friend using immutable operation
ElevatedButton(
child: Text('Remove Last Friend'),
onPressed: () {
setState(() {
userProfile = userProfile.removeLastFriend();
});
},
),
],
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment