Write a weather query demo.
Github address: github.com/koudle/GDG_…
1. Create a project
In Android Studio, File ->New ->New Flutter Project -> Flutter Application
After the project is created, there are three directories
Android: Directory for android projects
Ios: ios project directory
Lib: Directory of the Flutter project
We left the files under Android and ios untouched, and only changed the dart file under lib.
2. Run the Flutter project
- Connect the phone
- It is not recommended to use emulators because emulators may have problems rendering images with GPU.
- And then press
Run
Run the program on your phone.
3. Apply for the weather API interface
The registered address console.heweather.com/register
After the registration, then look at the API documentation at www.heweather.com/documents
Demo is here, get on the same day the weather API:www.heweather.com/documents/a…
The request URL is as follows:
https://free-api.heweather.com/s6/weather/now?location=, guangzhou & key = * * * * * *Copy the code
4. Interface writing
Dart contains the following code to display the interface:
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or press Run > Flutter Hot Reload in a Flutter IDE). Notice that the
// counter didn't reset back to zero; the application is not restarted.
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page')); }}Copy the code
So home is the UI that we’re going to display, and here we’re going to change MyHomePage to our own.
4.1 create WeatherWidget
Create the WeatherWidget in the lib directory with new -> Dart File
class WeatherWidget extends StatefulWidget{
@override
State<StatefulWidget> createState() {
// TODO: implement createState
return newWeatherState(); }}class WeatherState extends State<WeatherWidget>{
@override
Widget build(BuildContext context) {
// TODO: implement build
returnScaffold( ); }}Copy the code
After creation, change home to a WeatherWidget in main.dart as follows:
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: WeatherWidget(),
);
}
Copy the code
4.2 HotReload
In UI writing, we can use the Hot Reload feature of Flutter. When writing the layout of Flutter, press CTRL + S or CMD + S to see the changes of the interface in real time on the phone.
This function is very useful.
4.3 Adding Image Resources
Flutter can add different resources, such as images, text, configuration files, static data, etc.
To add assets, add assets to the flutter property of the pubspec.yaml file and specify the path to the asset. For example, to add a given image, write:
flutter:
assets:
- assets/my_icon.png
- assets/background.png
Copy the code
If you have too many resources to add, you can also add folders, for example:
flutter:
assets:
- assets/
Copy the code
In this demo, to add a background image, we create an images directory in the root directory of the project, place the background image in the images directory, and then in pubspec.yaml add:
flutter:
# The following line ensures that the Material Icons font is
# included with your application, so that you can use the icons in
# the material Icons class.
uses-material-design: true
assets:
- images/
Copy the code
4.4 Writing the UI layout of WeatherWidget
The Scaffold added the body property to write the UI layout as follows:
class WeatherState extends State<WeatherWidget>{
@override
Widget build(BuildContext context) {
// TODO: implement build
return Scaffold(
body: new Stack(
fit: StackFit.expand,
children: <Widget>[
new Image.asset("images/weather_bg.jpg",fit: BoxFit.fitHeight,),
new Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
new Container(
width: double.infinity,
margin: EdgeInsets.only(top: 40.0),
child: new Text(
"Guangzhou",
textAlign: TextAlign.center,
style: new TextStyle(
color: Colors.white,
fontSize: 30.0,),),),new Container(
width: double.infinity,
margin: EdgeInsets.only(top: 100.0),
child: new Column(
children: <Widget>[
new Text(
"20 °",
style: new TextStyle(
color: Colors.white,
fontSize: 80.0
)),
new Text(
"Fine",
style: new TextStyle(
color: Colors.white,
fontSize: 45.0
)),
new Text(
"The humidity 80%",
style: new TextStyle(
color: Colors.white,
fontSize: 30.0() [() [() [() [() [() [() [() }}Copy the code
Press CTRL + S and you can see the written UI on your phone, but the data is dead. Let’s see how to get the data over HTTP.
5. Obtain data through HTTP
In pubspec.yaml, add dependencies to HTTP.
dependencies:
flutter:
sdk: flutter
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^ 0.1.2
http: ^ 0.12.0
Copy the code
Then run the following command line in the current project directory:
$ flutter packages get
Copy the code
Or open the Pubspec. yaml file in Android Stuido and click the packages Get above
The point here is to pull the HTTP library.
5.1 Creating the WeatherData Class
Create WeatherData in the lib directory with new -> Dart File
class WeatherData{
String cond; / / the weather
String tmp; / / temperature
String hum; / / humidity
WeatherData({this.cond, this.tmp, this.hum});
factory WeatherData.fromJson(Map<String.dynamic> json) {
return WeatherData(
cond: json['HeWeather6'] [0] ['now'] ['cond_txt'],
tmp: json['HeWeather6'] [0] ['now'] ['tmp'] +"°",
hum: "Moisture"+json['HeWeather6'] [0] ['now'] ['hum'] +"%",); }factory WeatherData.empty() {
return WeatherData(
cond: "",
tmp: "",
hum: "",); }}Copy the code
5.2 Data Acquisition
class WeatherState extends State<WeatherWidget>{
WeatherData weather = WeatherData.empty();
WeatherState(){
_getWeather();
}
void _getWeather() async{
WeatherData data = await _fetchWeather();
setState((){
weather = data;
});
}
Future<WeatherData> _fetchWeather() async{
final response = await http.get('guangzhou & key = ebb698e9bb6844199e6fd23cbb9a77c5 https://free-api.heweather.com/s6/weather/now?location=');
if(response.statusCode == 200) {return WeatherData.fromJson(json.decode(response.body));
}else{
returnWeatherData.empty(); }}@overrideWidget build(BuildContext context) { ... }}Copy the code
5.3 Replace the previously written dead data with WeatherData
. child:new Column(
children: <Widget>[
newText( weather? .tmp, style:new TextStyle(
color: Colors.white,
fontSize: 80.0
)),
newText( weather? .cond, style:new TextStyle(
color: Colors.white,
fontSize: 45.0
)),
newText( weather? .hum, style:new TextStyle(
color: Colors.white,
fontSize: 30.0() [() [()Copy the code