Home > database >  FLUTTER - Problem with List constructor and null safety mode
FLUTTER - Problem with List constructor and null safety mode

Time:01-13

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)); ?

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);
}

CodePudding user response:

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));
  •  Tags:  
  • Related