Home > front end >  Flutter null or emptylist
Flutter null or emptylist

Time:06-02

it's just a small question about dart/flutter code. I saw this code today :

     Future<List<String>?> getAtSignListFromKeychain() async {
    var atsignMap = await _getAtSignMap();
    if (atsignMap.isEmpty) {
      // no atsigns found in biometric storage
      // read entries from flutter keychain
      // for mobile platforms only
      if (Platform.isAndroid || Platform.isIOS) {
        atsignMap = await checkForValuesInFlutterKeychain();
        if (atsignMap.isEmpty) {
          return null;
        }
      } else {
        return null;
      }
    }
    var atsigns = atsignMap.keys.toList();
    _logger.info('Retrieved atsigns $atsigns from Keychain');
    return atsigns;
  }

I don't understand interest of returning null with List? . Isn't better to write this code ?:

     Future<List<String>> getAtSignListFromKeychain() async {
    var atsignMap = await _getAtSignMap();
    if (atsignMap.isEmpty) {
      // no atsigns found in biometric storage
      // read entries from flutter keychain
      // for mobile platforms only
      if (Platform.isAndroid || Platform.isIOS) {
        atsignMap = await checkForValuesInFlutterKeychain();
        if (atsignMap.isEmpty) {
          return atsignMap;
        }
      } else {
        return List.empty();
      }
    }
    var atsigns = atsignMap.keys.toList();
    _logger.info('Retrieved atsigns $atsigns from Keychain');
    return atsigns;
  }

Or I'm missing something ? Thank you !

CodePudding user response:

First of all, there are always different solutions for different problems. I believe it is better to return a null value for some cases instead of creating an empty list in the memory and returning that. Either way, you have to check the returning value, handle errors, etc. So instead of checking if the list is empty or not, you can use just the ?? operator.

And in some cases, the list you expect with the items in it may be empty. If you return an empty list by default in such cases, you would not know if the list that you expected is really empty or is there a problem.

  • Related