22
votes

How do I get the first character of a string in dart flutter.

For example,a string having a value "Hello World" should return only "H". I am fetching data from my firestore database. My code is:

searchByName(String searchField) {
  return Firestore.instance
      .collection('posts')
      .where('description',
      isEqualTo: searchField.substring(0, 1).toUpperCase())
      .getDocuments();
}

I want to get the first letter from the data that I recieve from 'description' field in above code.

4

4 Answers

51
votes

You can do this by getting the first element of the String (indicated by index 0):

'${mystring[0]}'

example:

  String mystring = 'Hello World';

  print('${mystring[0]}');

in this case you will get as an output:

H
34
votes

To get first character of string you should use method substring Example:

word.substring(0,1);
4
votes

For Perform Searching in Firebase Document Field This Will Work

void main() {
  String mystring = 'Hello World';
  String search = ''; 
  
  for (int i=0;i<=mystring.length;i++){
  search += mystring[i];
  print(search);
 } 
}

Output

H
He
Hel
Hell
Hello
Hello 
Hello W
Hello Wo
Hello Wor
Hello Worl
Hello World

For me this Works.

0
votes

Needed to get first n values rather than just one, and kept getting Value not in range: 10 error using substring, here's a helper function to cut a string down to the first x characters:

  //* Limits given string, adds '..' if necessary
  static String shortenName(String nameRaw, {int nameLimit = 10, bool addDots = false}) {
    //* Limiting val should not be gt input length (.substring range issue)
    final max = nameLimit < nameRaw.length ? nameLimit : nameRaw.length;
    //* Get short name
    final name = nameRaw.substring(0, max);
    //* Return with '..' if input string was sliced
    if (addDots && nameRaw.length > max) return name + '..'; 
    return name;
  }

Usage:

    return Helpers.shortenName('Sausage', nameLimit: 5);