skip to Main Content

I am trying to call an post Api in flutter to store data in MongoDb but I am getting an exception. This is the code.

  Future<void> postData() async {
    final url = Uri.parse('http://10.0.2.2:3000/data');

    final data = {
      'username': user!.displayName,
      'email': user!.email,
      'uid': user!.uid,
    };
    final jsonData = jsonEncode(data);

    final response = await http.post(url, body: jsonData, headers: {
      'Content-Type': 'application/json',
    });

    if (response.statusCode == 200) {
      print('Post request successful');
      print(response.body);
    } else {
      print('Error: ${response.statusCode}');
    }
  } 

This is the error I am getting.

E/flutter ( 9199): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: Null check operator used on a null value

2

Answers


  1. Try this :

        Future<void> postData() async {
            final url = Uri.parse('http://10.0.2.2:3000/data');
        
            if(user != null){
             final data = {
               'username': user!.displayName,
               'email': user!.email,
               'uid': user!.uid,
             };
            }
            else{
             final data = {
               'username': "",
               'email': "",
               'uid': "",
             };
            } 
            final jsonData = jsonEncode(data);
        
            final response = await http.post(url, body: jsonData, headers: {
              'Content-Type': 'application/json',
            });
        
            if (response.statusCode == 200) {
              print('Post request successful');
              print(response.body);
            } else {
              print('Error: ${response.statusCode}');
            }
          } 
    
    Login or Signup to reply.
  2. User may be null.To fix the issues, you can try this.Since the user name , email ,uuid is string

    Future<void> postData() async {
        final url = Uri.parse('http://10.0.2.2:3000/data');
    
        final data = {
          'username': user?.displayName ?? "",
          'email': user?.email?? "",
          'uid': user?.uid ?? "",
        };
        final jsonData = jsonEncode(data);
    
        final response = await http.post(url, body: jsonData, headers: {
          'Content-Type': 'application/json',
        });
    
        if (response.statusCode == 200) {
          print('Post request successful');
          print(response.body);
        } else {
          print('Error: ${response.statusCode}');
        }
      } 
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search