3

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;
    });
  });
}
2

2 Answers 2

3

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';
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.