Flutter Study

【Dart】异步函数

2022-06-03  本文已影响0人  Merbng

异步函数

then

import 'package:http/http.dart' as http;
import 'dart:convert';
Future getIPAddress() {
  final urls = 'https://httpbin.org/ip';
  return http.get(urls).then((response) {
    // print(response.body);
    String ip=jsonDecode(response.body)['origin'];
    return ip;
  });
}
  void main(){
    getIPAddress()
        .then((ip) => print('$ip'))
        .catchError((error)=>print(error));
  }

async

import 'package:http/http.dart' as http;
import 'dart:convert';

Future getIPAddress() async {
  final urls = 'https://httpbin.org/ip';
  final response = await http.get(urls);
  String ip = jsonDecode(response.body)['origin'];
  return ip;
}

void main() async {
  try {
    final ip = await getIPAddress();
    print(ip);
  } catch (error) {
    print(error);
  }
}

上一篇 下一篇

猜你喜欢

热点阅读