1 year ago

#380662

test-img

gerypratama

Why does my jsonDecode() method in Flutter throw a Format Exception?

I've been learning mobile development on Flutter for a while and currently trying to build a single-page text translation app, for exercise. I tried to integrate a Google Translate API.

I'm having trouble running the app due to an error (Format Exception) in the jsonDecode() method I use to extract the translation result json object (Post method HTTP request)

Here's my home screen code

import 'package:flutter/material.dart';
import '../models/input_model.dart';

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

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  TextEditingController textController = TextEditingController();

  final translation = Sentence();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Translation App')),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [

////////////// Widget for the translation source text //////////////

            Container(
                width: MediaQuery.of(context).size.width / 1.5,
                child: TextField(
                  controller: textController,
                  decoration: InputDecoration(
                      border: OutlineInputBorder(
                          borderRadius: BorderRadius.all(Radius.circular(8)))),
                )),

////////////////////////////////////////////////////////////////////

            ElevatedButton(
                onPressed: () {
                  Sentence.connectToAPI('en', 'de', textController.text); //static language option
                  setState(() {});                                        //input for testing
                },
                child: Text('Translate')),

////////////// Widget for the translation result text //////////////

            Container(
                width: MediaQuery.of(context).size.width / 1.5,
                child: Text((translation.trans == null)
                    ? 'no data'
                    : translation.trans.toString())),
          ],
        ),
      ),
    );
  }
}

And here's the model file where the problem lies:

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

class Sentence {
  Sentence({
    this.trans,
    this.orig,
    this.backend,
  });

  String? trans;
  String? orig;
  int? backend;

  factory Sentence.fromJson(Map<String, dynamic> json) => Sentence(
        trans: json["trans"],
        orig: json["orig"],
        backend: json["backend"],
      );

  Map<String, dynamic> toJson() => {
        "trans": trans,
        "orig": orig,
        "backend": backend,
      };

  static Future<Sentence> connectToAPI(
      String from, String to, String text) async {
    String pathURL =
        'https://translate.google.com/translate_a/single?client=at&dt=t&dt=ld&dt=qca&dt=rm&dt=bd&dj=1&ie=UTF-8&oe=UTF-8&inputm=2&otf=2&iid=1dd3b944-fa62-4b55-b330-74909a99969e';
    var response =
        await http.post(Uri.parse(pathURL), headers: <String, String>{
      'Content-Type': 'application/x-www-form-urlencoded',
      'User-Agent': 'PostmanRuntime/7.29.0'
    }, body: {
      'sl': from,
      'tl': to,
      'q': text
    });
    var jsonObject = jsonDecode(response.body); //the exception error message pointed here
    var textObject = (jsonObject as Map<String, dynamic>)['sentences'];

    return Sentence.fromJson(textObject);
  }
}

The exception error message was:

FormatException (FormatException: Unexpected character (at character 1)

^

I'm still a newbie and it really confuses me. I tried to search for the explanation of the error message on Google but still having a hard time understanding it. What seems to be the problem here?

json

flutter

dart

httprequest

0 Answers

Your Answer

Accepted video resources