简体   繁体   中英

Flutter: Return list of Strings using single string in a specific format

I need to upload array of string to firestore. I need to return list of Strings using single string as input.

If the input is 'Firestore'. I should return list like this: [f,fi,fir,firs,first,firsto,firstor,firestore]

If the input is 'Google Cloud'. I should return list like this: [g, go, goo, goo, goog, googl, google, c, cl, clo, clou, cloud]

For having [g, go, goo, goo, goog, googl, google, c, cl, clo, clou, cloud] as result

use this:

  String test = 'Google Cloud';
  List<String> chars = [];

  for (var word in test.split(" ")) {
    for (var i = 0; i <= word.length; i++) {
      if (word.substring(0, i).isNotEmpty) {
        chars.add(word.substring(0, i));
      }
    }
  }

  print(chars);

it's a good practice to share what you have already done. Here is a simple way of achieving what you want (excluding white spaces):

  String test = 'firestore';
  List<String> chars = [];

  for (var i = 0; i <= test.length; i++) {
    if (test.substring(0, i).isNotEmpty) {
      chars.add(test.substring(0, i));
    }
  }
  print(chars);

The above prints [f, fi, fir, fire, fires, firest, firesto, firestor, firestore]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM