All tutorials

Flutter

intermediate

The Flutter API wrapper is useful for Dart or Flutter developers who wish to seamlessly integrate the what3words API into their Dart or Flutter applications, without the hassle of having to manage the low level API calls themselves.

A full example of how to integrate the what3words Flutter wrapper is available in our
github icon whiteFlutter Github repository

Also, a live sample of a Flutter application with Google Maps as a basemap is available in this FlutLab project.

1
2Installation

The artifact is available through pub.dev. Update your pubspec.yaml file with

dependencies:
 what3words: 3.1.0
Copied
3Setup

Import the what3words library

import 'package:what3words/what3words.dart';
Copied
4Initialise

Instantiate an instance of What3WordsV3, from which all API requests can be made.

var api = What3WordsV3('what3words-api-key');
Copied
5Usage

Convert to what3words address

This function converts coordinates (expressed as latitude and longitude) to a what3words address.

More information about ConvertTo3wa, including returned results is available in the what3words REST API documentation.

Find the words for (51.508344,0.12549900):

var words = await api
  .convertTo3wa(Coordinates(51.508344, -0.12549900))
  .language('en')
  .execute();
print('Words: ${words.data()?.toJson()}');
Copied

Convert to coordinates

This function converts a what3words address to a position, expressed as coordinates of latitude and longitude.

It takes the words parameter as a string of a what3words 'table.book.chair'

More information about ConvertToCoordinates, including returned results is available in the what3words REST API documentation.

Find the words for ///filled.count.soap:

var coordinates = await api
	.convertToCoordinates('table.book.chair')
	.execute();
print('Coordinates ${coordinates.data()?.toJson()}');
Copied

AutoSuggest

When presented with a what3words address which may be incorrectly entered, AutoSuggest returns a list of potential correct 3 word addresses. It needs the first two words plus at least the first character of the third word to produce suggestions.

This method provides corrections for mis-typed words (including plural VS singular), and words being in the wrong order.

Optionally, clipping can narrow down the possibilities, and limit results to:

  • One or more countries
  • A geographic area (a circle, box or polygon)

This dramatically improves results, so we recommend that you use clipping if possible.

To improve results even further, set the Focus to user’s current location. This will make AutoSuggest return results which are closer to the user.

More information about AutoSuggest, including returned results is available in the what3words REST API documentation.

Code example Simple basic call:

var autosuggest = await api
	.autosuggest('fun.with.code')
	.nResults(3)
	.execute();
print('Autosuggest: ${autosuggest.data()?.toJson()}');
Copied

Code example AutoSuggest, clipping the results returned to the United Kingdom and Belgium:

var autosuggest = await api
	.autosuggest('fun.with.code')
	.clipToCountry(['gb', 'be'])
	.execute();
print('Autosuggest: ${autosuggest.data()?.toJson()}');
Copied

Code example AutoSuggest, Focus on (51.4243877,-0.34745).

var autosuggest = await api
  .autosuggest('fun.with.code')
  .focus(Coordinates(51.4243877, -0.34745))
  .execute();
print('Autosuggest: ${autosuggest.data()?.toJson()}');
Copied

Code example AutoSuggest, with Generic Voice input type.

var autosuggest = await api
  .autosuggest('fun with code')
  .input-type('generic-voice')
  .language('en')
  .execute();
print('Autosuggest: ${autosuggest.data()?.toJson()}');
Copied

Grid section

Grid section returns a section of the what3words 3m x 3m grid as a set of horizontal and vertical lines covering the requested area, which can then be drawn onto a map.

The requested box must not exceed 4km from corner to corner, or a BadBoundingBoxTooBig error will be returned.

More information about GridSection, including returned results is available in the what3words REST API documentation.

Get a grid for 52.207988,0.116126) in the south west, and 52.208867,0.117540 in the north east:

// Obtain a grid section within the provided bounding box
var gridSection = await api
      .gridSection(Coordinates(51.515900, -0.212517), Coordinates(51.527649, -0.191746))
      .execute();
print(gridSection.data()?.toJson());
Copied

Available languages

This function returns the currently supported languages. It will return the two letter code, and the name of the language both in that language and in English.

More information about AvailableLanguages, including returned results is available in the what3words REST API documentation.

var languages = await api
	.availableLanguages()
	.execute();
print('Languages: ${languages.data()?.toJson()}');
Copied

Handling errors

Success of failure of an API call can be determined through the use of the isSuccessful() function.

If it’s been determined that an API call was not successful, code and message values which represent the error, are accessible from through the getError() function.

var autosuggest = await api
  .autosuggest('freshen.overlook.clo')
  .clipToCountry(['fr', 'de'])	
  .execute();

if (autosuggest.isSuccessful()) {
  ...
} else {
  var error = autosuggest.getError();

  if (error == What3WordsError.BAD_CLIP_TO_COUNTRY) {
    // Invalid country clip is provided
    print('BadClipToCountry: ${error.message}');
  }
}
Copied
6Full example

The example below is a simple Flutter application demonstrating a basic GUI application featuring a text box which accepts a what3words address, and a ‘Convert To Coordinates’ button which geocodes the what3words address provided, returning the WGS84 Coordinates back to screen.

import 'package:flutter/material.dart';
import 'package:what3words/what3words.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final appTitle = 'what3words';

    return MaterialApp(
      title: appTitle,
      home: Scaffold(
        appBar: AppBar(
          title: Text(appTitle),
        ),
        body: LocationForm(),
      ),
    );
  }
}

class LocationForm extends StatefulWidget {
  @override
  LocationFormState createState() {
    return LocationFormState();
  }
}

class LocationFormState extends State<LocationForm> {
  String twaHolder = '';
  var api = What3WordsV3('what3words-api-key');

  final _formKey = GlobalKey<FormState>();

  @override
  Widget build(BuildContext context) {
    var twaController = TextEditingController();
    var twaInput = TextFormField(
      controller: twaController,
      decoration: InputDecoration(
          hintText: "e.g. lock.spout.radar"
      ),
    );

    var convertToCoordsButton = ElevatedButton(
      child: Text("Convert To Coordinates"),
      onPressed: () async {
        var location = await api.convertToCoordinates(twaController.text).execute();
        setState(() {
          if (location.isSuccessful()) {
            twaHolder = '${location.coordinates.lat}, ${location.coordinates.lng}';
          } else {
            twaHolder = '${location.getError().code}: ${location.getError().message}';
          }
        });
      },
    );

    return Form(
      key: _formKey,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          twaInput,
          convertToCoordsButton,
          Text('$twaHolder', style: TextStyle(fontSize: 21))
        ],
      ),
    );
  }
}
Copied

Related tutorials