# A Gun Milan (kundli matching) widget in Flutter

> Matching two birth charts is one POST with two birth objects. The Flutter app sends them to your backend, which adds the key and calls AstroNode; the app renders the eight koot scores. The backend ran against the API; the Dart side is written to the same contract.

Source: https://astronode.dev/integrations/flutter · Updated: 2026-12-01

**How this page was verified:** The Go backend was executed (`go run`, `net/http/httptest`) against the in-memory API, including the 400 path. **The Dart code was not executed** - there is no Dart runtime on the build machine; it was written against the JSON the Go handler actually returned.

## Keys and `--dart-define`

`--dart-define=ASTRONODE_API_KEY=...` feels like configuration, but the value is compiled into the app binary and can be recovered from it. Use dart-defines for things that are safe to publish (your backend's URL), never for the AstroNode key.

```bash
flutter run --dart-define=BACKEND_URL=https://api.your-app.example.com
```

## The backend (Go)

Any backend works; this one is a single Go handler that forwards the two births, decodes only the fields the widget uses, and passes AstroNode's error code through. It reads `ASTRONODE_API_KEY` from the server's environment.

```go
var astronode = &http.Client{Timeout: 15 * time.Second}

func baseURL() string {
	if u := os.Getenv("ASTRONODE_BASE_URL"); u != "" {
		return u
	}
	return "https://api.astronode.dev"
}

// POST /match  {"person_a": {...birth}, "person_b": {...birth}}
func matchHandler(w http.ResponseWriter, r *http.Request) {
	body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 4096))
	if err != nil {
		http.Error(w, "body too large", http.StatusRequestEntityTooLarge)
		return
	}
	req, _ := http.NewRequestWithContext(r.Context(), http.MethodPost,
		baseURL()+"/v1/compatibility", bytes.NewReader(body))
	req.Header.Set("Authorization", "Bearer "+os.Getenv("ASTRONODE_API_KEY"))
	req.Header.Set("Content-Type", "application/json")

	res, err := astronode.Do(req)
	if err != nil {
		http.Error(w, "upstream unavailable", http.StatusBadGateway)
		return
	}
	defer res.Body.Close()

	var env struct {
		Data struct {
			Total struct {
				Score  float64 `json:"score"`
				Max    float64 `json:"max"`
				Bucket string  `json:"bucket"`
			} `json:"total"`
			Koots []struct {
				Name  string  `json:"name"`
				Score float64 `json:"score"`
				Max   float64 `json:"max"`
			} `json:"koots"`
		} `json:"data"`
		Error *struct {
			Code string `json:"code"`
		} `json:"error"`
	}
	if err := json.NewDecoder(res.Body).Decode(&env); err != nil || env.Error != nil {
		w.WriteHeader(res.StatusCode)
		json.NewEncoder(w).Encode(map[string]any{"error": env.Error})
		return
	}
	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(env.Data)
```

What it returned for the two sample births (Mumbai 1973 and Delhi 1975):

```json
{"total":{"score":29,"max":36,"bucket":"Excellent"},
 "koots":[{"name":"varna","score":1,"max":1},{"name":"vashya","score":2,"max":2},
          {"name":"tara","score":3,"max":3},{"name":"yoni","score":2,"max":4},
          {"name":"graha_maitri","score":3,"max":5},{"name":"gana","score":3,"max":6},
          {"name":"bhakoot","score":7,"max":7},{"name":"nadi","score":8,"max":8}]}
```

Sending only `person_a` came back as `400 {"error":{"code":"VALIDATION_ERROR"}}`. The full response also carries `initial_score` and a `cancellation_note` per koot - here Gana scored 0 before a cancellation raised it to 3 - and a `manglik_match` block; see [how Gun Milan is scored](https://astronode.dev/guides/ashtakoot-gun-milan-scoring) before you decide what to show.

## The Dart side

`lib/match.dart` (uses the `http` package):

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

const backendUrl = String.fromEnvironment('BACKEND_URL');

class Koot {
  Koot(this.name, this.score, this.max);
  final String name;
  final double score;
  final double max;

  factory Koot.fromJson(Map<String, dynamic> j) => Koot(
        j['name'] as String,
        (j['score'] as num).toDouble(), // JSON 3 decodes as int, 2.5 as double
        (j['max'] as num).toDouble(),
      );
}

class Match {
  Match(this.score, this.max, this.bucket, this.koots);
  final double score;
  final double max;
  final String bucket;
  final List<Koot> koots;

  factory Match.fromJson(Map<String, dynamic> j) {
    final total = j['total'] as Map<String, dynamic>;
    return Match(
      (total['score'] as num).toDouble(),
      (total['max'] as num).toDouble(),
      total['bucket'] as String,
      (j['koots'] as List).map((k) => Koot.fromJson(k as Map<String, dynamic>)).toList(),
    );
  }
}

Future<Match> fetchMatch(Map<String, Object> personA, Map<String, Object> personB) async {
  final res = await http.post(
    Uri.parse('$backendUrl/match'),
    headers: {'Content-Type': 'application/json'},
    body: jsonEncode({'person_a': personA, 'person_b': personB}),
  );
  if (res.statusCode != 200) {
    throw Exception('match failed: HTTP ' + res.statusCode.toString());
  }
  return Match.fromJson(jsonDecode(res.body) as Map<String, dynamic>);
}
```

Rendering the koots:

```dart
class MatchView extends StatelessWidget {
  const MatchView({super.key, required this.match});
  final Match match;

  @override
  Widget build(BuildContext context) {
    return ListView(
      children: [
        ListTile(
          title: Text(match.bucket),
          trailing: Text(match.score.toStringAsFixed(0) + ' / ' + match.max.toStringAsFixed(0)),
        ),
        for (final k in match.koots)
          ListTile(
            title: Text(k.name),
            subtitle: LinearProgressIndicator(value: k.score / k.max),
            trailing: Text(k.score.toStringAsFixed(1)),
          ),
      ],
    );
  }
}
```

## The mistakes that bite first

- **`as double` on a JSON number.** Every score above is a whole number, so `jsonDecode` returns an `int`, and `j['score'] as double` throws `type 'int' is not a subtype of type 'double'`. Dart decodes a JSON number as `double` only when it has a fractional part, and the same app will soon parse fields that do (`degree_in_sign`, dasha `years`) - so cast every number through `num` and call `toDouble()`, as the model does.
- **No network in the release build.** Flutter's debug and profile builds add the `INTERNET` permission for you; the main `AndroidManifest.xml` does not. If matching works in `flutter run` and fails silently in the Play build, add `<uses-permission android:name="android.permission.INTERNET"/>` to `android/app/src/main/AndroidManifest.xml`.
- **Sending a date-time instead of date + time.** The backend forwards exactly what the app sends, and each person needs `date`, local `time`, `tz_offset_minutes`, `lat`, `lng` - not an ISO timestamp from a `DateTime`. Build the map from the picker's wall-clock fields.

## Questions

**Which AstroNode endpoints does the Flutter example call?**

1 endpoint: Kundli Matching (Ashtakoot Gun Milan) (`POST /v1/compatibility`).

**Was the Flutter code on this page actually run?**

The Go backend was executed (`go run`, `net/http/httptest`) against the in-memory API, including the 400 path. **The Dart code was not executed** - there is no Dart runtime on the build machine; it was written against the JSON the Go handler actually returned.

## Endpoints

- [`POST /v1/compatibility`](https://astronode.dev/capabilities/compatibility/compatibility) - Kundli Matching (Ashtakoot Gun Milan) API
