mirrored_repositories/Dart-programing/get_postal_code
import 'dart:async';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
final myController = TextEditingController();
Future<Autogenerated> fetchAlbum(String code) async {
//  1600021
  int str1=int.parse(code.substring(0,3));
  var str2=code.substring(3);
String url="https://madefor.github.io/postal-code-api/api/v1/"+str1.toString()+"/"+str2.toString()+".json";
print(url);
  final response = await http
      .get(url);
  print("response from server ${response.body}");
  if (response.statusCode == 200) {
    // If the server did return a 200 OK response, then parse the JSON.
    return Autogenerated.fromJson(json.decode(response.body));
  } else {
    // If the server did not return a 200 OK response, then throw an exception.
    throw Exception('Failed to load address');
  }
}

//class Album {
//  final int userId;
//  final int id;
//  final String title;
//
//  Album({this.userId, this.id, this.title});
//
//  factory Album.fromJson(Map<String, dynamic> json) {
//    return Album(
//      userId: json['userId'],
//      id: json['id'],
//      title: json['title'],
//    );
//  }
//}
class Data {
  String prefcode;
  Ja ja;
  Ja en;

  Data({this.prefcode, this.ja, this.en});

  Data.fromJson(Map<String, dynamic> json) {
    prefcode = json['prefcode'];
    ja = json['ja'] != null ? new Ja.fromJson(json['ja']) : null;
    en = json['en'] != null ? new Ja.fromJson(json['en']) : null;
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['prefcode'] = this.prefcode;
    if (this.ja != null) {
      data['ja'] = this.ja.toJson();
    }
    if (this.en != null) {
      data['en'] = this.en.toJson();
    }
    return data;
  }
}

class Autogenerated {
  String code;
  List<Data> data;

  Autogenerated({this.code, this.data});

  Autogenerated.fromJson(Map<String, dynamic> json) {
    code = json['code'];
    if (json['data'] != null) {
      data = new List<Data>();
      json['data'].forEach((v) {
        data.add(new Data.fromJson(v));
      });
    }
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['code'] = this.code;
    if (this.data != null) {
      data['data'] = this.data.map((v) => v.toJson()).toList();
    }
    return data;
  }
}

class Ja {
  String prefecture;
  String address1;
  String address2;
  String address3;
  String address4;

  Ja(
      {this.prefecture,
      this.address1,
      this.address2,
      this.address3,
      this.address4});

  Ja.fromJson(Map<String, dynamic> json) {
    prefecture = json['prefecture'];
    address1 = json['address1'];
    address2 = json['address2'];
    address3 = json['address3'];
    address4 = json['address4'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['prefecture'] = this.prefecture;
    data['address1'] = this.address1;
    data['address2'] = this.address2;
    data['address3'] = this.address3;
    data['address4'] = this.address4;
    return data;
  }
}

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  MyApp({Key key}) : super(key: key);

  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  Future<Autogenerated> futureAlbum;

  @override
  void initState() {
    super.initState();
    if(myController.text==null){
      futureAlbum = fetchAlbum("1600001");

    }

  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Fetch Data Example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: Text('Fetch Data Example'),
        ),
        body: Column(
          children: <Widget>[
            Padding(
              padding: const EdgeInsets.all(16.0),
              child: TextField(
                controller: myController,
                maxLength: 7,
              ),
            ),
            RaisedButton(
              child: Text("enter the code"),
              onPressed: (){
                setState(() {
                  futureAlbum = fetchAlbum(myController.text);
                });


              },
            ),
            Center(
              child:
              FutureBuilder<Autogenerated>(
                future: futureAlbum,
                builder: (context, snapshot) {
                  if (snapshot.hasData) {
                    print("get data ${snapshot.data.code}");
                    print("get prefcode ${snapshot.data.data[0].prefcode}");
                    print("get english ${snapshot.data.data[0].en.prefecture}");
                    return Column(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: <Widget>[
                        Text(snapshot.data.code),
                        Text(snapshot.data.data[0].prefcode),
                        Text(snapshot.data.data[0].en.prefecture),
                        Text(snapshot.data.data[0].en.address1)
                      ],
                    );
                  } else if (snapshot.hasError) {
                    return Text("${snapshot.error}");
                  }

                  // By default, show a loading spinner.
                  return CircularProgressIndicator();
                },
              ),
            ),
          ],
        ),
      ),
    );
  }
}
