Home > Mobile >  Having problem in comparing String with a List element
Having problem in comparing String with a List element

Time:01-23

I am trying to run an if-else condition that displays certain Icons based on the given conditions. I am trying to see if a particular quizId,i.e. a string is present inside the list to fulfill the condition. For some reason, the condition doesn't seem to work even though the element is present inside the list.

I have tried manually comparing the quizId with a particular String, which worked out fine. But as soon as I bring the list into the condition, it stops working. I have found both the quizId and List element data types which is String yet they still can't be compared.

This is the piece of Code :

class QuizBadge extends StatelessWidget {
  const QuizBadge({super.key, required this.topic, required this.quizId});

  final Topic topic;
  final String quizId;

  @override
  Widget build(BuildContext context) {
    Report report = Provider.of<Report>(context);
    List completed = report.topics.values.toList();

    List a = completed.expand((element) => element).toList();
    print(a[1]);

    if (a[1] == "flutter-basics") {
      return const Icon(FontAwesomeIcons.checkDouble, color: Colors.green);
    } else {
      return const Icon(FontAwesomeIcons.solidCircle, color: Colors.grey);
    }
  }
}

Any help would be appreciated. Thank You.

CodePudding user response:

This is occurring because the elements in your list are not strings. Consider checking the type returned by report.topics.values.toList() (I can't tell because you didn't include this) and/or explicitly declare the lists you expect to be strings as List<String>, for example:

    List<String> a = completed.expand((element) => element).toList();

You will see an error on that line if you declare it this way, and the error will offer a clue.

In general, I prefer to avoid using generics without specifying an explicit type, because the default is dynamic, and you don't get the benefit of static type checking. You can also maintain explicit typing by using var/final declarations, such as:

    var a = completed.expand((element) => element).toList();

CodePudding user response:

You want to use .equals(), not ==. == tests the reference is equal, that they're the same memory location. .equals() tests that the strings have the same characters.

  • Related