Adam Katz
Adam Katz

Reputation: 6962

How does one end a function in dart similar to in JS typing return

In Javascript when I want to end a function I usually write return, but in the dart, if I do that then the function asks for a return statement at the end of each branch which is messy.

Function createCategory(File image) {
    String title = _categoryTitle.value;
    if(image == null || title == null || title.length == 0) {
      return null;
    }
    CategoryModel newCategory = new CategoryModel();
    if(_categories.value == null) {
      _categories.sink.add([newCategory]);
    }
    return null;
  }

What is the correct way to do this in dart?

Upvotes: 0

Views: 30

Answers (2)

Hamed Rezaee
Hamed Rezaee

Reputation: 7222

you can do that like this:

void createCategory(File image) {
    String title = _categoryTitle.value;

    if (image != null && title.isNotEmpty && _categories.value == null) {
        _categories.sink.add([CategoryModel()]);
    }
}

Upvotes: 0

julemand101
julemand101

Reputation: 31219

I think your confusion comes from that your method is valid Dart code but does not really do what I guess you think. Your method has the following signature:

Function createCategory(File image) {

This means your method is named createCategory, takes one argument of the type File and returns a Function. Since you have marked the method to return a Function, then Dart will tell you it is a problem if you just return; since this is properly not what you wanted.

If your method is not going to return any value, then you want to mark this with the return type of void like:

void createCategory(File image) {
  String title = _categoryTitle.value;
  if (image == null || title == null || title.length == 0) {
    return;
  }
  CategoryModel newCategory = new CategoryModel();
  if (_categories.value == null) {
    _categories.sink.add([newCategory]);
  }
  return;
}

I should note, that the last return can be skipped since Dart will automatically add return; at the end of a function if it is missing.

Upvotes: 2

Related Questions