Uncategorized

Display User Name in Flutter App Bar

In this tutorial we will display username of the user retrieved from PHP API in the app bar of the flutter application.

Step 1: Create a method to Fetch User Data From SharedPreferences in the Home Screen

Create the variable String userEmail = '';

 
// Method to retrieve user info from SharedPreferences
  Future<void> _getUserInfo() async {
    try {
      SharedPreferences prefs = await SharedPreferences.getInstance();
      String email = prefs.getString('email') ?? ''; // Get user email
      setState(() {
        userEmail = email;
        // Here you can retrieve and set other user information as needed
        print('===================');
        print(userEmail);
        print('===================');
      });
    } catch (error) {
      print('Error retrieving user info: $error');
    }
  }

Step 2: Call _getUserInfo() in the HomeScreen on Page Load

  @override
  void initState() {
    super.initState();
    fetchProductDataImages();
    _getUserInfo();
  }

Step 3: Display User Name in The App Bar

appBar: AppBar(
        backgroundColor: Colors.pink,
        title: Row(
          children: [
            Text('Hi $userEmail'),
            Text('Logout')
          ],
        ),
      ),

Step 4: Make Changes in PHP API to get User Name And User Id

// Verify user's password
        if ($user) {
            $response['success'] = true;
            $response['message'] = "Login successful.";
            $response['user_name'] = $user['user_name'];
            $response['user_id'] = $user['id'];
            // You can include additional data like user ID, name, etc. in the response if needed.
        }

Step 5: Store The User Name in Shared Preference in The Login Screen

 Future<void> _saveCredentials(String userName, int userId) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setString('email', _emailController.text);
    await prefs.setString('password', _passwordController.text);
    await prefs.setString('userName', userName);
    await prefs.setInt('userId', userId);
  }

Step 6: Call _saveCredentials Function in The Login Screen & Pass Necessary Values From The API

Future<void> _loginUser() async {
    String apiUrl = 'https://aboutassam.in/flutter_app/api/login.php';
    try {
      var response = await http.post(Uri.parse(apiUrl), body: {
        'user_email': _emailController.text,
        'user_password': _passwordController.text,
      });

      var responseData = json.decode(response.body);
      if (responseData['success']) {
        _saveCredentials(responseData['user_name'], responseData['user_id']);
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => Home(),
          ),
        );
        // Handle navigation or any other action
        print('Login successful');
      } else {
        // Login failed, show error message
        print('Login failed: ${responseData['message']}');
      }
    } catch (e) {
      print('Error logging in: $e');
    }
  }

// Use await _saveCredentials(responseData['user_name'], responseData['user_id']); if your code Does Not Work

Now replace email with username 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *