Home > Back-end >  The named parameter 'body' isn't defined The named parameter 'header' isn
The named parameter 'body' isn't defined The named parameter 'header' isn

Time:11-26

I'm new to programming in general and very new to flutter, I get this following error message on both the "body" and "header" in the code which is marked in bold. I have tried everything I could find online for any help, but now found any solution, I figure this probobly isn't the hardest thing for someone who knows programming to solve, but I'm a beginner so I would really like the help. Thanks in advance.

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

const API_URL = 'https://todoapp-api-pyq5q.ondigitalocean.app';
const API_KEY = '7037674e-2262-4502-a2e1-29c940bd2a7a';

class Api {
  static Future addTodoModel(TodoModel todo) async {
    var json = todo.toJson();
    var bodyString = jsonEncode(json);
    

    var response = await http.post(Uri.parse('$API_URL/todos?key=$API_KEY',
        **body: bodyString, headers:** {'Content-Type': 'application/json'}));
    if (response.statusCode == 200) {
      return response;
    } else {
      print('error on add');
      return null;
    }
  }

  static Future updateTodo(TodoModel todo, todoId) async {
    var json = todo.toJson();
    var bodyString = jsonEncode(json);

    var response = await http.put(Uri.parse('$API_URL/todos/$todoId?key=$API_KEY',
        **body: bodyString, headers:** {'Content-Type': 'application/json'}));
    if (response.statusCode == 200) {
      return response;
    } else {
      print('error on update');
      return null;
    }
  }

  static Future removeTodoModel(String todoId) async {
    try {
      var response = await http.delete(Uri.parse('$API_URL/todos/$todoId?key=$API_KEY'));
      if (response.statusCode == 200) {
        return response;
      }
      print('exception on remove');
    } catch (exception) {
      throw exception;
    }
  }

  static Future<List<TodoModel>> getTodoModel() async {
    try {
      var response = await http.get(Uri.parse('$API_URL/todos?key=$API_KEY'));
      var json = jsonDecode(response.body);
      return json.map<TodoModel>((data) {
        return TodoModel.fromJson(data);
      }).toList();
    } catch (exception) {
      throw exception;
    }
  }
}

CodePudding user response:

Uri.parse

The Uri.parse funtion has no "header" or "body" parameter.

"headers" and "body" should be post method's params, like this: http post

CodePudding user response:

Body and Headers are available in method of http. For example:

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

// POST method

   final response = await http.post(
      url,
      headers: {}, // Map<String*, String*>* headers
      body: json.encode(params), // params is Map<String, dynamic>
    );
  • Related