I am writing an app which deals with both cryptos and stocks. Because they share many common characteristics such as symbol, price, name etc, I created a base class 'instrument' then subclasses for stock and crypto. I have a generic 'manager' class for both, as loading, saving etc are again very similar. However, there are some functions, such as fetching a current price, that need to be implemented differently, so I have extended my generic manager class and I am trying to override the relevant function, i.e. fetchCurrentPrice() in the example below. Dart complains that
'CryptoManager.fetchCurrentPrice' ('Future Function(Crypto)') isn't a valid override of 'Manager.fetchCurrentPrice' ('Future Function(Instrument)').
I don't understand this, as I have defined as type in the manager, and Crypto extends Instrument, so I am fulfilling this criterion. Any idea where I am going wrong?
abstract class Instrument {
String name = 'Instrument';
double currentPrice = 0.0;
Instrument(this.name);
}
class Crypto extends Instrument {
Crypto(super.name);
String contractAddress = '0xBCCFF3FF6...';
}
abstract class Manager<T extends Instrument> {
List<T> instruments = [];
Future<double> fetchCurrentPrice(T instrument) async {
print('Fetching price for generic instrument');
return 12.80;
}
}
class CryptoManager extends Manager {
// this is causing the issue
@override
Future<double> fetchCurrentPrice(Crypto instrument) async {
print('Fetching price for crypto');
return 12.80;
}
}
void main(List<String> args) {
CryptoManager cryptoManager = CryptoManager();
var btcCrypto = Crypto('BTC');
cryptoManager.fetchCurrentPrice(btcCrypto);
}
CodePudding user response:
Your class CryptoManager
needs to extend Manager<Crypto>
, not just "some Manager, kinda".
class CryptoManager extends Manager<Crypto>