Home > Software engineering >  How to create post request on flutter?
How to create post request on flutter?

Time:08-04

I've create a flutter app that has a textfield with a button I want that every word i insert to the textfield and whan i will press the button this data will be written on a google sheet

I don't understand why it doesn't work

import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'dart:convert' as convert;
import 'package:http/http.dart' as http;

import 'model.dart';

String tax = 'ert';
final wordi = TextEditingController();
String taxi = wordi.text;

class BillSplit extends StatefulWidget {
  // const BillSplit({Key? key}) : super(key: key);

  @override
  State<BillSplit> createState() => _BillSplitState();
}

class _BillSplitState extends State<BillSplit> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        margin: EdgeInsets.only(left: 20, right: 20),
        child: Column(children: [
          Container(
            alignment: Alignment.centerLeft,
            margin: EdgeInsets.only(top: 30),
            child: Text(
              'split',
              style:
                  GoogleFonts.abel(fontSize: 20, fontWeight: FontWeight.w600),
            ),
          ),
          SizedBox(height: 15),
          Container(
            width: MediaQuery.of(context).size.width,
            height: 300,
            decoration: BoxDecoration(color: Colors.amber),
            child: Column(
              children: [
                Text(
                  'total',
                  style: GoogleFonts.abel(
                      fontSize: 20, fontWeight: FontWeight.w600),
                ),
                Text(
                  '${tax.toString()}',
                  style: GoogleFonts.abel(
                      fontSize: 20, fontWeight: FontWeight.w600),
                ),
                Container(
                  width: MediaQuery.of(context).size.width / 2,
                  child: TextField(
                    keyboardType: TextInputType.number,
                    controller: wordi,
                    onChanged: (value) {
                      setState(() {
                        tax = value;
                      });
                    },
                    decoration: InputDecoration(
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(20),
                      ),
                      labelText: "Tax",
                      labelStyle: GoogleFonts.abel(
                          fontSize: 20, fontWeight: FontWeight.w300),
                    ),
                  ),
                ),
                RaisedButton(
                  onPressed: () async {
                    // final body = json.encode(tax);
                    final url = Uri.parse(
                        'https://script.google.com/macros/s/AKfycbyt3ECPqAweBMQFgi96BqTkTzE_HPpFr0hwpGf9pisQ1asTp-g2C5geYfy2XAZUvd2-/exec');
                    final response = await http.post(
                      url,
                      // headers: {'Content-Type': 'application/json'},
                      body: json.encode({
                        taxi,
                      }),
                    );

                    print('Response status: ${response.statusCode}');
                    print('Response body: ${response.body}');
                  }, // },
                  child: Text('Open'),
                ),
              ],
            ),
          )
        ]),
      ),
    );
  }
}

// void sendData() {
//   String taxi = wordi.text;
// }

I get the following error:

Error: Converting object to an encodable object failed: Instance of 'HashSet' at Object.throw [as throw] (localhost:58716/dart_sdk.js:5080:11) at convert._JsonStringStringifier.new.writeObject –

and here is the google app script code that should get the data from the flutter app and need to write it on the google sheet

function doPost(e) {
  var ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/1z6y1I3b8xm9XLg-W-VhMOn4d8uHSa0Kv6mK_kwVZu7M/edit#gid=0");
var sh = ss.getSheetByName("Sheet1");

  sheetApp(e);
  Logger.log(e.parameter);
}


function sheetApp(e) {
  SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1').getRange(4,1).setValue(e);
}

CodePudding user response:

Try this:

Just a guess

function sheetApp(e) {
SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1').getRange(4,1).setValue(JSON.stringify(e));
}

Regarding your commment. Then what does the following logger statement deliver?

function doPost(e) {
  Logger.log(JSON.stringify(e));//Please provide this 
  var ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/1z6y1I3b8xm9XLg-W-VhMOn4d8uHSa0Kv6mK_kwVZu7M/edit#gid=0");
var sh = ss.getSheetByName("Sheet1");

  sheetApp(e);
  Logger.log(e.parameter);
}

CodePudding user response:

{taxi,} is not valid json, so json.encode will throw.

CodePudding user response:

You can't do

json.encode({
  axi,
}),

The parameter of json.encode needs to be a map, a list, or a string for example. {axi} is a set and is not a valid parameter. Maybe try:

json.encode([
  axi
]),

or

json.encode(axi),
  • Related