Last active
January 9, 2024 16:33
-
-
Save pmatatias/a87bc52f1c766780270d7653e0428cee 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()); | |
} | |
class UserProfile { | |
String name; | |
List<String> friends; | |
UserProfile(this.name, this.friends); | |
void addFriend(String friendId) { | |
friends.add(friendId); | |
} | |
// Direct manipulation of friends list (intentional issue) | |
List<String> get mutableFriends => friends; | |
} | |
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('Mutable 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.addFriend('Friend ${userProfile.friends.length + 1}'); | |
}); | |
}, | |
), | |
// Button to directly manipulate friends list | |
ElevatedButton( | |
child: Text('Remove Last Friend (Direct Manipulation)'), | |
onPressed: () { | |
setState(() { | |
if (userProfile.mutableFriends.isNotEmpty) { | |
userProfile.mutableFriends.removeLast(); | |
} | |
}); | |
}, | |
), | |
], | |
), | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment