Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.9k views
in Technique[技术] by (71.8m points)

dart - flutter return future list in a var to use outside the loop

Hello I'm trying to recuperate the list value of a database. i can but what i want is to export the result in a var so i can use in all my code just by calling "print(myList);"

this is my code :

  static const URL =
  'https://xxxhost/employee_actions3.php';

  static Future<List<Employee>> getEmployees() async {

  try {
  final response = await http.post(Uri.parse(
    URL,
  ));
  print("getEmployees >> Response:: ${response.body}");
    if (response.statusCode == 200) {
       List<Employee> list = parsePhotos(response.body);
    
    
      return list;
    
  } else {
      throw <Employee>[];
  }
  } catch (e) {
    return <Employee>[];
  }
 }

and my classe Employee

 class Employee {
 String id;
 String firstName;
 String lastName;

 Employee({required this.id, required this.firstName, required  this.lastName});

 factory Employee.fromJson(Map<String, dynamic> json) {
   return Employee(
     id: json['id'] as String,
     firstName: json['lat'] as String,
     lastName: json['lng'] as String,
   );
 }
 }

can i have help please ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There are two ways to access async data in most modern languages, including dart, they are:

1. By providing a callback then

2. By using the function in an async context and awaiting the result

I've wrapped the code above in a class called API so the examples below are easier to follow,

class API {
  static const URL = 'https://xxxhost/employee_actions3.php';

  static Future<List<Employee>> getEmployees() async {
    try {
      final response = await http.post(Uri.parse(URL));
      print("getEmployees >> Response:: ${response.body}");
      if (response.statusCode == 200) {
        List<Employee> list = parsePhotos(response.body);
        return list;
      } else {
        throw("${response.statusCode} Failed to parse photos");
      }
    } catch (e) {
        throw e;
    }
  }
}

Method 1: Providing a callback to .then, this method will allow you to work with async actions in a synchronous context, but be aware it will not halt the execution flow.

void main() {
  API.getEmployees().then((resp) => print(resp)).catchError(e) => print(e);
}

Method 2: Async/Await, this method will allow you to access the data inline, that is var x = await myAsyncFunc() remember the await keyword requires the function to be called within an async context. And the await keyword will halt the execution flow till the future completes.

void main() async {
  try {
    final list = await API.getEmployees();
    print(list);
  } catch (e) {
    print(e);
  }
}

Using either one of the two methods outlined above will allow you to access the data of the list later on.

Additional Reading:

Async programming in dart

Futures and error handling


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...