Исключение формата флаттера: неожиданный символ (в символе 1) - PullRequest
0 голосов
/ 28 апреля 2020

Я получаю исключение в проекте Flutter. Ошибка выглядит следующим образом:

Exception has occurred.
FormatException (FormatException: Unexpected character (at character 1)
<!DOCTYPE html>
^
)

Это отображается в строке «throw error». Код ниже:

Future<void> _authenticate(
      String email, String password, String urlSegment) async {
    final url =
        "https://identitytoolkit.googleapis.com/v1/accounts:$urlSegment?key=AIzaSyC9Rz9CDv-_hc68I_wdvogF2ZnDHCpr2Y8";
    try {
      final response = await http.post(
        url,
        body: json.encode(
          {
            "email": email,
            "password": password,
            "returnSecureToken": true,
          },
        ),
      );
      print(response.body);
      final responseData = json.decode(response.body);
      if (responseData["error"] != null) {
        throw HttpException(responseData["error"]["message"]);
      }
      _token = responseData["idToken"];
      _userId = responseData["localId"];
      _expiryDate = DateTime.now().add(
        Duration(
          seconds: int.parse(
            responseData["expiresIn"],
          ),
        ),
      );
      _autoLogout();
      notifyListeners();
      final prefs = await SharedPreferences.getInstance();
      final userData = json.encode(
        {
          "token": _token,
          "userId": _userId,
          "expiryDate": _expiryDate.toIso8601String(),
        },
      );
      prefs.setString("userData", userData);
    } catch (error) {
      throw error;           //Exception is showing here
    }
  }

Сообщение об ошибке выглядит так, как показано на изображении (щелкните)

На консоли отладки отображается следующее сообщение:

I/flutter (18432): <!DOCTYPE html>
I/flutter (18432): <html lang=en>
I/flutter (18432):   <meta charset=utf-8>
I/flutter (18432):   <meta name=viewport content="initial-scale=1, minimum-scale=1, width=device-width">
I/flutter (18432):   <title>Error 404 (Not Found)!!1</title>
I/flutter (18432):   <style>
I/flutter (18432):     *{margin:0;padding:0}html,code{font:15px/22px arial,sans-serif}html{background:#fff;color:#222;padding:15px}body{margin:7% auto 0;max-width:390px;min-height:180px;padding:30px 0 15px}* > body{background:url(//www.google.com/images/errors/robot.png) 100% 5px no-repeat;padding-right:205px}p{margin:11px 0 22px;overflow:hidden}ins{color:#777;text-decoration:none}a img{border:0}@media screen and (max-width:772px){body{background:none;margin-top:0;max-width:none;padding-right:0}}#logo{background:url(//www.google.com/images/branding/googlelogo/1x/googlelogo_color_150x54dp.png) no-repeat;margin-left:-5px}@media only screen and (min-resolution:192dpi){#logo{background:url(//www.google.com/images/branding/googlelogo/2x/googlelogo_color_150x54dp.png) no-repeat 0% 0%/100% 100%;-moz-border-image:url(//www.google.com/images/brand
I/flutter (18432): FormatException: Unexpected character (at character 1)
I/flutter (18432): <!DOCTYPE html>
I/flutter (18432): ^

Пожалуйста, помогите

Ответы [ 2 ]

0 голосов
/ 03 мая 2020

Мои конечные точки были неверны в http-URL. Я использовал некоторые старые конечные точки в своем http-адресе.

Согласно документации Firebase REST Auth, мне пришлось использовать signUp для функции регистрации и signInWithPassword для функции входа в систему и передать ее urlSegment в _authenticate().

0 голосов
/ 28 апреля 2020

Похоже, вы не получаете JSON в качестве ответа, поэтому при декодировании выдается это исключение. Попробуйте API в почтальоне, чтобы увидеть, является ли ответ JSON.

...