Home > database >  The final variable 'transaction' can't be read because it's potentially unassign
The final variable 'transaction' can't be read because it's potentially unassign

Time:08-22

I'm getting some problems when handling errors using try and catch. When I try to return the transaction, I get the error:

The final variable 'transaction' can't be read because it's potentially unassigned at this point.

Future<Transaction> _send(Transaction transactionCreated, String password, BuildContext context) async {
  final Transaction transaction;

  try {
    transaction = await _transactionWebClient.save(transactionCreated, password);
    _showSucessfulMessage(transaction, context);
    Navigator.pop(context);
  } on TimeoutException catch (e) {
    _showFailureMessage(context, message: e.message.toString());
  } on HttpException catch (e) {
    _showFailureMessage(context, message: e.message);
  } on Exception catch (e) {
    _showFailureMessage(context);
  } finally {
    setState(() {
      _sending = false;
    });
  }
  return transaction;
}

I've tried using the return inside the try and inside the finally, but it also doesn't work

CodePudding user response:

Change

Future<Transaction>

to

Future<Transaction?>

and change

final Transaction transaction;

to

Transaction? transaction;

Then the caller of the method _send() obviously have to handle a value that can be null.

CodePudding user response:

First, let's see why we got this linting error. "The final variable 'transaction' can't be read because it's potentially unassigned at this point".

You want to return "Future<Transaction>" from this async method. Here you declare a variable "final Transaction transaction;". First, you have to assign it a transaction object which you are doing in the try block. But if you see in the code that if you got an error in the try block control will go to the catch block. Here you may or may not be able to get the transaction object. So in the end, you are returning the transaction, as I told you till here maybe we got the transaction object assigned to the transaction variable or maybe not.

So what's the solution?

Solution 1:

Change the return type of method from

Future<Transaction>

to

Future<Transaction?>

Declare the local variable as

final Transaction? transaction;

Solution 2: You can throw an exception to the calling method as follows:

Future<Transaction> _send(...) async {
final Transaction transaction;

try {
transaction =
  await _transactionWebClient.save(transactionCreated, password);
_showSucessfulMessage(transaction, context);
return transaction;
} catch (e) {
throw Exception('your message');
}
  • Related