Created
December 28, 2023 02:45
-
-
Save pmatatias/fff47dc09b53e1ea94a3ed889ebba383 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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