2

I want cannot post data from flutter emulator to database. This is the error I got after run the emulator and enter the data.

Exception has occurred. FormatException (FormatException: Unexpected character (at character 1) ^ )

this is my api.dart import 'dart:convert';

import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';
class CallApi{
    final String _url = 'http://10.2.2.0/voyceb/api/';

    postData(data, apiUrl) async {
        var fullUrl = _url + apiUrl + await _getToken(); 
        return await http.post(
            fullUrl, 
            body: jsonEncode(data), 
            headers: _setHeaders()
        );
    }
    getData(apiUrl) async {
       var fullUrl = _url + apiUrl + await _getToken(); 
       return await http.get(
         fullUrl, 
         headers: _setHeaders()
       );
    }

    _setHeaders() => {
        'Content-type' : 'application/json',
        'Accept' : 'application/json',
    };

    _getToken() async {
        SharedPreferences localStorage = await
        SharedPreferences.getInstance();
        var token = localStorage.getString('token');
        return '?token=$token';
    }
}

the error shown at part in signup.dart

var res = await CallApi().postData(data, 'register');
var body = json.decode(res.body);

error shown at

var body = json.decode(res.body);

at json.decode.

I want data to be insert to database as I enter in emulator.

bihanns
  • 49
  • 1
  • 2
  • 10

2 Answers2

1

Maybe there's a problem on JSON encode and decode process.

You may solve that using this

var res = await CallApi().postData(data, 'register');
var encodeFirst = json.encode(res.body);
var data = json.decode(encodeFirst);
ejabu
  • 2,998
  • 23
  • 31
  • or maybe theres an issue on your Laravel server. possible duplicate of https://stackoverflow.com/questions/55671441/flutter-formatexception-unexpected-character-at-character-1/55677287 – ejabu Aug 19 '19 at 04:54
  • i dont think so. I think my error is different because it also display this error. > – bihanns Aug 19 '19 at 07:03
0

sometimes you need to check yours .htacess file.

Ejeh
  • 425
  • 5
  • 7