convert
及io
包
import 'package:flutter/material.dart';
import 'dart:convert';
import 'dart:io';
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
void getWeatherData() async {
try {
HttpClient httpClient = new HttpClient();
HttpClientRequest request = await httpClient.getUrl(Uri.parse("http://t.weather.sojson.com/api/weather/city/101030100"));
HttpClientResponse response=await request.close();
var result=await response.transform(utf8.decoder).join();
print(result);
httpClient.close();
} catch (e) {
print('請求失敗!');
}
}
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'httpClient 請求範例',
home: new Scaffold(
appBar: new AppBar(
title: new Text('httpClient 請求範例'),
),
body: new Center(
child: new RaisedButton(
child: new Text('取得天氣數據'),
onPressed: getWeatherData,
),
),
),
);
}
}
執行結果可以從編輯器下方的「偵錯主控台」觀看(並不會呈現在主機上)