Skip to main content

flutter_cep2 1.1.1 copy "flutter_cep2: ^1.1.1" to clipboard
flutter_cep2: ^1.1.1 copied to clipboard

Brazilian ZIP code (CEP) lookup for Dart and Flutter, backed by the ViaCEP API. JSON or XML, typed model, clear errors, every platform.

[flutter_cep2: Brazilian ZIP code lookup for Dart and Flutter]

pub version pub points pub likes downloads
tests coverage license platforms

Look up any Brazilian CEP, or find the CEPs of a street, with one call.
Typed results, one exception type, every platform. Powered by ViaCEP.

Quick start • Usage • Errors • API • Example • FAQ • Contributing


✨ Features #

Feature Details
🔎 CEP lookup 01310-100, 01310100 and 01.310-100 all work
🗺️ Search by address State + city + street returns every matching CEP
🧱 Typed model An immutable Cep with value equality and fromJson/toJson
🚦 Clear errors One CepException with a CepErrorType for every failure
⏱️ Timeouts that cancel A slow request is aborted, not just abandoned
🔤 JSON or XML Pick the ViaCEP format; you get the same Cep back
🧪 Testable Inject any http.Client; 100% line coverage in the package itself
🌍 Pure Dart Android, iOS, web, Windows, macOS, Linux and server-side Dart

🚀 Quick start #

dart pub add flutter_cep2      # or: flutter pub add flutter_cep2
import 'package:flutter_cep2/flutter_cep2.dart';

Future<void> main() async {
  final cep = FlutterCep2();
  try {
    final address = await cep.search('01310-100');
    print('${address.logradouro}, ${address.bairro} - ${address.localidade}/${address.uf}');
    // Avenida Paulista, Bela Vista - São Paulo/SP
  } on CepException catch (e) {
    print('Lookup failed: ${e.message}');
  } finally {
    cep.dispose();
  }
}

Requires Dart 3.0+ (Flutter 3.10+).

📖 Usage #

Look up a CEP #

final address = await cep.search('01310100');
print(address.estado); // São Paulo
print(address.ddd);    // 11

Keep one FlutterCep2 for as long as you need it and call dispose() at the end: every lookup reuses the same HTTP connection.

Search by address #

Don't know the CEP? Give the state, city and street:

final matches = await cep.searchAddress('RS', 'Porto Alegre', 'Domingos Jose');
for (final m in matches) {
  print('${m.cep}  ${m.logradouro}, ${m.bairro}');
}
// 91790-072  Rua Domingos José Poli, Restinga
// 90420-200  Rua Domingos José de Almeida, Rio Branco

uf is the two-letter state code; city and street need at least 3 characters. ViaCEP returns up to 50 matches, and no match is an empty list, not an error.

XML instead of JSON #

await cep.search('01310-100', output: CepOutputFormat.xml);

The result is the same Cep; only the wire format changes.

Timeout and custom HTTP client #

final cep = FlutterCep2(
  timeout: const Duration(seconds: 5), // default: 10 seconds
  client: myHttpClient,                // optional; you keep ownership
);

When the timeout runs out the request is aborted and search throws a CepException of type timeout. A client you pass in stays open after dispose(); closing it is up to you.

🚨 Error handling #

Every failure is a CepException. Branch on type; message is for logs.

try {
  await cep.search(input);
} on CepException catch (e) {
  switch (e.type) {
    case CepErrorType.invalidFormat:
    case CepErrorType.notFound:
      showFieldError('Check the CEP');
    default:
      showRetry();
  }
}
type When
invalidFormat The CEP doesn't have 8 digits, or the address is too short. Nothing is sent
notFound ViaCEP has no address for the CEP
http ViaCEP answered with a status other than 200
timeout No answer within timeout
network The request could not be sent (offline, DNS, TLS...)
invalidResponse The body could not be read as a ViaCEP answer

🧪 Testing your code #

Pass a fake client, for example MockClient from package:http/testing.dart:

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

final client = MockClient((request) async => http.Response(
      '{"cep": "01310-100", "logradouro": "Avenida Paulista", "bairro": "Bela Vista", '
      '"localidade": "São Paulo", "uf": "SP", "ibge": "3550308"}',
      200,
      headers: {'content-type': 'application/json; charset=utf-8'},
    ));
final cep = FlutterCep2(client: client);

📚 API reference #

Member Description
FlutterCep2({http.Client? client, Duration timeout}) Creates the service. timeout defaults to 10 seconds
Future<Cep> search(String cep, {CepOutputFormat output}) Looks up one CEP
Future<List<Cep>> searchAddress(String uf, String city, String street, {CepOutputFormat output}) Lists the CEPs of a street
void dispose() Closes the HTTP client the service created

Full docs on pub.dev.

Fields of Cep
Property Type Description
cep String Postal code in XXXXX-XXX format
logradouro String Street name
complemento String? Extra address info
bairro String Neighborhood
localidade String City
uf String State abbreviation (SP, RJ, ...)
estado String? State name (São Paulo, ...)
regiao String? Region (Sudeste, ...)
unidade String? Postal unit
ibge String IBGE municipality code
gia String? GIA code (São Paulo only)
ddd String? Area code
siaf String? SIAFI code (siafi in the API)

Cep is immutable, compares by value and converts with Cep.fromJson and toJson().

📱 Example app #

[Example app showing the address of CEP 01310-100]

The example/ folder has a Flutter app that looks up CEPs in JSON or XML, shows every field of the address and copies any of them with one tap.

cd example
flutter run

❓ FAQ #

Is ViaCEP free? Are there limits?

ViaCEP is a free public service, not run by this package. It asks clients not to send bulk lookups, and heavy use may get your IP blocked. Cache the results you look up often.

Does it work on Flutter web?

Yes. ViaCEP allows cross-origin requests, so the same code runs in the browser. The example app above is the web build.

Can I use it without Flutter?

Yes. The package is pure Dart and only depends on http, xml and meta, so it also works in CLIs and on the server.

Why are the field names in Portuguese?

They mirror the ViaCEP API (logradouro, bairro, localidade...), so anything you read in the ViaCEP docs maps one to one.

🤝 Contributing #

Bug reports, ideas and pull requests are welcome. Read CONTRIBUTING.md to set up the project and see what CI checks, and follow the Code of Conduct. Found a security issue? Use SECURITY.md, not a public issue.

If this package saves you time, ⭐ the repository and 👍 it on pub.dev: it helps other people find it.

📄 License #

GNU Lesser General Public License v2.1.

6
likes
0
points
1k
downloads

Publisher

verified publishervitormelo.dev.br

Weekly Downloads

Brazilian ZIP code (CEP) lookup for Dart and Flutter, backed by the ViaCEP API. JSON or XML, typed model, clear errors, every platform.

Repository (GitHub)
View/report issues

Topics

#cep #brazil #address #zipcode #viacep

Funding

Consider supporting this project:

github.com

License

unknown (license)

Dependencies

http, meta, xml

More

Packages that depend on flutter_cep2