Meggy
Meggy

Reputation: 1671

Flutter/Dart- Method 'replaceAll' was called on null. How to check if String exists?

I've got a form with 3 textfields for the user to insert 3 tags. Before uploading to the server I need to clean them up with regex. The problem is, unless the user has filled in all three textfields Android Studio throws the following error;

E/flutter (13862): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: NoSuchMethodError: The method 'replaceAll' was called on null.
E/flutter (13862): Receiver: null
E/flutter (13862): Tried calling: replaceAll(RegExp: pattern=[# ] flags=, "") 

So how can I check the existence of each field before sending? Here's the code;

Future<String> uploadTags({String tag1, String tag2, String tag3,}) async {

  final serverurl = "http://example.com/example.php";
  
  final String cleantag1 = tag1.replaceAll(RegExp('[# ]'),'');
  final String cleantag2 = tag2.replaceAll(RegExp('[# ]'),'');
  final String cleantag3 = tag3.replaceAll(RegExp('[# ]'),'');

  var request = http.MultipartRequest('POST', Uri.parse(serverurl));
  
  request.fields['tag1'] = cleantag1;
  request.fields['tag2'] = cleantag2;
  request.fields['tag3'] = cleantag3;

  var multiPartFile = await http.MultipartFile.fromPath("audio", filepath, contentType: MediaType("audio", "mp4"));
  request.files.add(multiPartFile);
  request.send().then((result) async {
    http.Response.fromStream(result)
        .then((response) {
      if (response.statusCode == 200)
      {
        print('response.body '+response.body);
      }
      return response.body;
    });
  });
}

Upvotes: 3

Views: 1796

Answers (2)

farouk osama
farouk osama

Reputation: 2529

the tag1 or tag2 or tag3 parameter value is NULL,

To make sure, add breakpoint in this line

final String cleantag1 = tag1.replaceAll(RegExp('[# ]'),'');

and check parameters values

if this values not required you can use ? after variable like this :

final String cleantag1 = tag1?.replaceAll(RegExp('[# ]'),'');

and if you want to add a default value Write like this:

final String cleantag1 = tag1?.replaceAll(RegExp('[# ]'),'')??'defult_value';

Upvotes: 3

pedro pimont
pedro pimont

Reputation: 3084

Use one of the null aware operators of Dart.

.? ?? or ??= like:

  final String cleantag1 = tag1?.replaceAll(RegExp('[# ]'),'');
  final String cleantag2 = tag2?.replaceAll(RegExp('[# ]'),'');
  final String cleantag3 = tag3?.replaceAll(RegExp('[# ]'),'');

you can also use ?? to provide a default value if the exp is null

Upvotes: 2

Related Questions