Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

FLUTTER – Problem with List constructor and null safety mode

I would like to use this "Levenshtein" function to assess similarities between two strings (to check if user has committed a spelling mistake).

Since I work on null safe mode, it points out an error with the LIST constructor :

List<List<int>> d =  List.generate(sa + 1, (int i) =>  List(sb + 1));

What can I write to replace List(sb+1)); ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

int levenshtein(String a, String b) {
  a = a.toUpperCase();
  b = b.toUpperCase();
  int sa = a.length;
  int sb = b.length;
int i, j, cost, min1, min2, min3;
  int levenshtein;
// ignore: deprecated_member_use
List<List<int>> d =  List.generate(sa + 1, (int i) =>  List(sb + 1));
if (a.length == 0) {
    levenshtein = b.length;
    return (levenshtein);
  }
  if (b.length == 0) {
    levenshtein = a.length;
    return (levenshtein);
  }
for (i = 0; i <= sa; i++) d[i][0] = i;
for (j = 0; j <= sb; j++) d[0][j] = j;
for (i = 1; i <= a.length; i++)
    for (j = 1; j <= b.length; j++) {
      if (a[i - 1] == b[j - 1])
        cost = 0;
      else
        cost = 1;
min1 = (d[i - 1][j] + 1);
      min2 = (d[i][j - 1] + 1);
      min3 = (d[i - 1][j - 1] + cost);
      d[i][j] = min(min1, min(min2, min3));
    }
levenshtein = d[a.length][b.length];
  return (levenshtein);
}

>Solution :

You can use List.generate for the inner list as well.

List<List<int>> d =  List.generate(sa + 1, (int i) =>  List.generate(sb + 1, (int j) => 0));

Also, if they’re all going to be initialized to 0 you can just do this too:

List<List<int>> d = List.filled(sa + 1, List.filled(sb + 1, 0));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading