Pasting the following into dartPad.dev gives the error for the assignment classtwoInstance.fieldOne = arg;

Error: A value of type 'bool' can't be assigned to a variable of type 'bool'

Casting to a bool also gives an 'unnecessary cast' message

How do I assign the bool argument arg to fieldOne?

class ClassOne {
     Function<T>(T) setFunction;

     ClassOne({this.setFunction});
}

class ClassTwo {
    bool fieldOne;
}

testFunction<T>(T value){
    ClassTwo classtwoInstance = ClassTwo();
    ClassOne classOneInstance = ClassOne(setFunction: <bool>(bool arg) {
    classtwoInstance.fieldOne = arg; // Error A value of type 'bool' can't be assigned to a variable of type 'bool'
       return null;
    });

   return classOneInstance;
}

void main() {

ClassOne classWithFunction = testFunction<bool>(true);
   classWithFunction.setFunction(true);
}


Solution 1: Omatt

Since you're using a generic type on your Function<T>(T) setFunction, the compiler gets confused when it's set to as bool in testFunction(). What you can do here is change the data type to generic and then cast arg with bool when setting to cassTwoInstance.fieldOne

Here's the updated code that you can try on dartpad.dev

class ClassOne {
  Function<T>(T) setFunction;

  ClassOne({required this.setFunction});
}

class ClassTwo {
  bool? fieldOne;
}

testFunction<T>(T value) {
  ClassTwo cassTwoInstance = ClassTwo();
  ClassOne classOneInstance = ClassOne(setFunction: <T>(T arg) {
    cassTwoInstance.fieldOne = arg as bool; 
    print('ClassTwo fieldOne: ${cassTwoInstance.fieldOne}');
    return null;
  });

  return classOneInstance;
}

void main() {
  ClassOne classWithFunction = testFunction<bool>(false);
  classWithFunction.setFunction(false);
}