import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; import 'package:shared_preferences/shared_preferences.dart'; import '../../globals.dart'; class AddFriendPage extends StatefulWidget { @override _AddFriendPageState createState() => _AddFriendPageState(); } class _AddFriendPageState extends State { final TextEditingController _friendUidController = TextEditingController(); List _friends = []; bool _isLoading = false; final String _addFriendApiUrl = '$apiurl/add_friend'; final String _getFriendsApiUrl = '$apiurl/get_friends'; // Method to add a friend Future _addFriend(String friendUid) async { final prefs = await SharedPreferences.getInstance(); final String? token = prefs.getString('token'); if (token == null) { _showToast('No token found. Please login again.'); return; } final response = await http.post( Uri.parse(_addFriendApiUrl), headers: {'Content-Type': 'application/json'}, body: json.encode({ 'token': token, 'friend_uid': friendUid, }), ); if (response.statusCode == 200) { _showToast('Friend added successfully!'); _fetchFriends(); } else { _showToast('Failed to add friend.'); } } Future _fetchFriends() async { setState(() { _isLoading = true; }); final prefs = await SharedPreferences.getInstance(); final String? token = prefs.getString('token'); if (token == null) { _showToast('No token found. Please login again.'); setState(() { _isLoading = false; }); return; } final response = await http.post( Uri.parse(_getFriendsApiUrl), headers: {'Content-Type': 'application/json'}, body: json.encode({'token': token}), ); if (response.statusCode == 200) { final data = json.decode(response.body); setState(() { _friends = data['friends']; _isLoading = false; }); } else { _showToast('Failed to load friends.'); setState(() { _isLoading = false; }); } } void _showToast(String message) { ScaffoldMessenger.of(context).showSnackBar( SnackBar(content: Text(message)), ); } @override void initState() { super.initState(); _fetchFriends(); } @override Widget build(BuildContext context) { return Scaffold( body: Padding( padding: const EdgeInsets.all(16.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ TextField( controller: _friendUidController, decoration: InputDecoration( labelText: 'Enter Friend UID', border: OutlineInputBorder(), ), ), SizedBox(height: 16), // Add Friend Button ElevatedButton( onPressed: () { final friendUid = _friendUidController.text; if (friendUid.isNotEmpty) { _addFriend(friendUid); } else { _showToast('Please enter a friend UID.'); } }, child: Text('Add Friend'), ), SizedBox(height: 16), // Friends List (scrollable) _isLoading ? Center(child: CircularProgressIndicator()) : Expanded( child: ListView.builder( itemCount: _friends.length, itemBuilder: (context, index) { final friend = _friends[index]; return ListTile( title: Text(friend['name']), subtitle: Text('UID: ${friend['uid']}'), ); }, ), ), ], ), ), ); } }