Home > Software engineering >  Im getting this error I cant resolve in flutter
Im getting this error I cant resolve in flutter

Time:10-21

Future<String> task2() async {
  Duration three = const Duration(seconds: 3);
  String result;

  await Future.delayed(three, () {
    result = 'task 2 data';
  });
  return result;
}

The non nullable local variable 'result' must be assigned before it can be used.

now if i assign it a value on initiation or add a null check, the function just returns that value and not the intended value task 2 data

Can someone identify the problem and help me resolve it.

CodePudding user response:

You need call then like this:

await Future.delayed(Duration(seconds: 2)).then((_) {
      result = 'task 2 data';
});

or whenComplete:

await Future.delayed(Duration(seconds: 2)).whenComplete(() => result = 'task 2 data');

CodePudding user response:

You need add "?" with String because it Future type String and also use setState function

Future<String?> task2() async {
Duration three = const Duration(seconds: 3);
String? result;
await Future.delayed(three, () {
  setState(() {
    result = 'task 2 data';
  });
});
return result;

}

  • Related