Home > Net >  With or without async await I am getting this error on returning result
With or without async await I am getting this error on returning result

Time:08-26

**With or without async await I am getting this error on returning result on line 26. I am building a weather app but this is just a scratch file to test some things and concepts since I am learning from a Course called Flutter Beginner course. **

Error: The non-nullable local variable 'resolt' must be assigned before it can be used.

Code:

import 'dart:io';
 
void main() {
  performTasks();
}
 
void performTasks() async {
  task1();
  String newtask2Result = await task2();
  task3(newtask2Result);
}
 
void task1() {
  String result = 'task 1 data';
  print('Task 1 complete');
}
 
Future task2() async {
  Duration threeSeconds = Duration(seconds: 3);
  String resolt;
 
  await Future.delayed(threeSeconds, () {
    resolt = 'task 2 data';
    print('Task 2 complete');
  });
  return resolt;
}
 
void task3(String task2Data) {
  String result = 'task 3 data';
  print('Task 3 complete with $task2Data');
}

Picture: enter image description here

CodePudding user response:

In then task2() function, you are declaring a variable but not initializing it.

You can either initialize it with default value or make it of type late.

Example 1 - default value

Future task2() async {
  Duration threeSeconds = Duration(seconds: 3);
  String resolt = "";

  await Future.delayed(threeSeconds, () {
    resolt = 'task 2 data';
    print('Task 2 complete');
  });
  return resolt;
}

Example 2 - declaring as late

Future task2() async {
  Duration threeSeconds = Duration(seconds: 3);
  late String resolt;

  await Future.delayed(threeSeconds, () {
    resolt = 'task 2 data';
    print('Task 2 complete');
  });
  return resolt;
}

CodePudding user response:

Change your return type from Future to Future .

  • Related