Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.1k 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 Reply

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...