Search code examples
flutterlistdartif-statement

why is the If statement is not working even if the condition is true? dart & flutter


why is the If (isNormal == true) statement is not working even if the condition is true

the code that I tried to do are as below

  _checkResult() {
    bool isNormal = false;
    isNormal = userAnswer.every((item) => normalList.contains(item));
    if (isNormal) {
      print("Normal");
    } else {
      print("Try Again");
    }
  }

I already tried to print both lists to check if both data are the same or not,

enter image description here

As you can see, both list are the same, but the result does not change. Please help


Solution

  • You can follow any of this

    bool withEvery(List<int> mainItems, List<int> subItems) {
        final result = subItems.every((element) => mainItems.contains(element));
        return result;
      }
    

    or

      bool containsItem(List<int> mainItems, List<int> subItems) {
        for (final i in subItems) {
          if (!mainItems.contains(i)) {
            return false;
          }
        }
        return true;
      }
    

    to get desire result.

    test case

      test("containsItem n check", () {
        final normalList = [1, 3, 2];
        final userAnswer = [1, 2, 3];
        final userAnswer1 = [2, 1, 3];
        final userAnswer2 = [2, 1, 0];
        final result = containsItem(normalList, userAnswer);
        expect(result, true);
        final result1 = containsItem(normalList, userAnswer1);
        expect(result1, true);
        final result2 = containsItem(normalList, userAnswer2);
        expect(result2, false);
      });
    
      test("withEvery ", () {
        final normalList = [1, 3, 2];
        final userAnswer = [1, 2, 3];
        final userAnswer1 = [2, 1, 3];
        final userAnswer2 = [2, 1, 0];
        final result = withEvery(normalList, userAnswer);
        expect(result, true);
        final result1 = withEvery(normalList, userAnswer1);
        expect(result1, true);
        final result2 = withEvery(normalList, userAnswer2);
        expect(result2, false);
      });
    

    And your methods also working fine

    enter image description here