サンプル集  >  Flutter  >  郵便番号から住所を検索
郵便番号から住所を検索
2025/09/06

郵便番号から住所を検索してみます。

◆環境
OS Windows 10 Home 22H2 64bit OS x64 プロセッサ
Flutter 3.32.6
Dart 3.8.1
Android Studio Meerkat 2024.3.1

~/pubspec.yamlのdependenciesにhttp: ^1.1.0を追記します。


:
# versions available, run `flutter pub outdated`.
dependencies:
  flutter:
    sdk: flutter
  http: ^1.1.0

  # The following adds the Cupertino Icons font to your application.
:
以下略

Pub getをクリックします。


httpが追加された模様です。


~/lib/main.dartを編集します。

main.dart
  1: 
  2: 
  3: 
  4: 
  5: 
  6: 
  7: 
  8: 
  9: 
 10: 
 11: 
 12: 
 13: 
 14: 
 15: 
 16: 
 17: 
 18: 
 19: 
 20: 
 21: 
 22: 
 23: 
 24: 
 25: 
 26: 
 27: 
 28: 
 29: 
 30: 
 31: 
 32: 
 33: 
 34: 
 35: 
 36: 
 37: 
 38: 
 39: 
 40: 
 41: 
 42: 
 43: 
 44: 
 45: 
 46: 
 47: 
 48: 
 49: 
 50: 
 51: 
 52: 
 53: 
 54: 
 55: 
 56: 
 57: 
 58: 
 59: 
 60: 
 61: 
 62: 
 63: 
 64: 
 65: 
 66: 
 67: 
 68: 
 69: 
 70: 
 71: 
 72: 
 73: 
 74: 
 75: 
 76: 
 77: 
 78: 
 79: 
 80: 
 81: 
 82: 
 83: 
 84: 
 85: 
 86: 
 87: 
 88: 
 89: 
 90: 
 91: 
 92: 
 93: 
 94: 
 95: 
 96: 
 97: 
 98: 
 99: 
100: 
101: 
102: 
103: 
104: 
105: 
106: 
107: 
108: 
109: 
110: 
111: 
import 'package:flutter/material.dart';

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

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme:
          ColorScheme.fromSeed(seedColor: Colors.deepPurple),
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  TextEditingController controller = TextEditingController();
  List<String> items = [];
  String errorMessage = '';

  Future<void> loadZipCode(String zipCode) async {
    debugPrint("zipCode: $zipCode");

    if ( zipCode.length != 7 ) {
      setState(() {
        errorMessage = '郵便番号7桁を入力してください';
      });
      return;
    }

    setState(() {
      errorMessage = 'APIレスポンス待ち';
    });
    final response = await http.get(
      Uri.parse('https://zipcloud.ibsnet.co.jp/api/search'
                '?zipcode=$zipCode')
    );

    debugPrint("response.statusCode=${response.statusCode}");
    if (response.statusCode != 200) {
      debugPrint("response.statusCode != 200");
      return;
    }

    final body = json.decode(response.body) as Map<String, dynamic>;
    debugPrint("body=$body");
    final results = (body['results'] ?? []) as List<dynamic>;

    if (results.isEmpty) {
      debugPrint("results.isEmpty.");
      setState(() {
        errorMessage = '郵便番号がありません。';
      });
    } else {
      setState(() {
        errorMessage = '';
        items = results
          .map((result) =>
        "${result['address1']}"
        "${result['address2']}"
        "${result['address3']}"
        ).toList(growable: false);
      });
    }
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: TextField(
          controller: controller,
          keyboardType: TextInputType.number,
          onChanged: (value) {
            if (value.isNotEmpty) {
              loadZipCode(value);
            }
          },
        ),
      ),
      body: ListView.builder(
        itemBuilder: (context, index) {
          if (errorMessage.isNotEmpty) {
            return ListTile(title: Text(errorMessage));
          } else {
            return ListTile(title: Text(items[index]));
          }
        },
        itemCount: items.length,
      ),
    );
  }
}

起動してみます。


1と入力してみます。。


Consoleにメッセージが表示されました。

I/flutter ( 9668): zipCode: 1

続けて残りの郵便番号を入力してみます。 7桁入力すると住所が表示されました。


Consoleには入力の都度メッセージが表示されました。

I/flutter ( 9668): zipCode: 1
I/flutter ( 9668): zipCode: 10
I/flutter ( 9668): zipCode: 103
I/flutter ( 9668): zipCode: 1030
I/flutter ( 9668): zipCode: 10300
I/flutter ( 9668): zipCode: 103002
I/flutter ( 9668): zipCode: 1030022
I/flutter ( 9668): response.statusCode=200
I/flutter ( 9668): body={message: null, results: [{address1: 東京都, 
address2: 中央区, address3: 日本橋室町, kana1: トウキョウト, kana2: チュウオウ
ク, kana3: ニホンバシムロマチ, prefcode: 13, zipcode: 1030022}], status: 200
}

1文字削除したところ郵便番号7桁を入力してくださいと表示されました。


Consoleには1文字減らした文字が表示されました。

I/flutter ( 9668): zipCode: 103002

適当な郵便番号を入力したところ郵便番号がありませんと表示されました。


Consoleにはresponse.statusCode=200とresults: nullが表示されました。

I/flutter ( 9862): zipCode: 1030029
I/flutter ( 9862): response.statusCode=200
I/flutter ( 9862): body={message: null, results: null, status: 200}
I/flutter ( 9862): results.isEmpty.

期待通りに動作しました。

▲ PageTop  ■ Home


Copyright (C) 2025 ymlib.com