rest api flutter get 方法有效,而 post 无效

rest api flutter get method works while post doesnt

我从服务器响应中收到此错误

这是模型 api

你可以在这里找到完整的源代码https://github.com/alihassan75/project




// To parse this JSON data, do
//
//     final task = taskFromJson(jsonString);
import 'dart:collection';
import 'dart:core';
import 'package:flutter/foundation.dart';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

//List<Task> taskFromJson(String str) => List<Task>.from(json.decode(str).map((x) => Task.fromJson(x)));

//String taskToJson(List<Task> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

class Project {
 Project({
this.id,
required this.project_name,
this.created_at,
// required this.start_date,
//required this.end_date,
required this.user,
 });

  int? id;
 final String? project_name;
  DateTime? created_at;
 // final DateTime? start_date;
  //final DateTime? end_date;
  int user;

 factory Project.fromJson(Map<String, dynamic> json) => Project(
   id: json["id"],
   project_name: json["project_name"],
   created_at: DateTime.parse(json["created_at"]),
   // start_date: DateTime.parse(json["start_date"]),
   //end_date: DateTime.parse(json["end_date"]),
   user: json["user"],
 );

 Map<String, dynamic> toJson() => {
   "id": id,
   "project_name": project_name,
   "created_at": created_at?.toIso8601String(),
   // "start_date": start_date?.toIso8601String(),
    //"end_date": end_date?.toIso8601String(),
   "user": user,
 };
}
class ProjectProvider with ChangeNotifier{
 ProjectProvider(){
   this.fetchProject();
 }


 List<Project> _project = [];
 List<Project> get project {
   return [..._project];
 }

   void addProject(Project project) async {
   final response = await http.post(Uri.parse('http://mostafahamed.pythonanywhere.com/project/api'),
       headers: {"Content-Type": "application/json"}, body: json.encode(project));
   if (response.statusCode == 201) {
     project.id = json.decode(response.body)['id'];
     
     _project.add(project);
     notifyListeners();
   print('sucess');
   }
  else {
    print(response.body);
   throw Exception('Failed to add project');
 }
 }

 void deleteProject(Project project) async {
   final response =
       await http.delete(Uri.parse('http://mostafahamed.pythonanywhere.com/project/api${project.id}/'));
   if (response.statusCode == 204) {
     _project.remove(project);
     notifyListeners();
      print('sucess');
   }
  else {
  
   throw Exception('Failed to load tasks');
 }
 
 }



   fetchProject() async{
    final response = await http
     .get(Uri.parse('http://mostafahamed.pythonanywhere.com/project/api?format=json'));
   if (response.statusCode==200){
     var data = json.decode(response.body)as List;
     _project=data.map<Project>((json) => Project.fromJson(json)).toList();
    
     notifyListeners();
      print('sucess');
   }
  else {
   // If the server did not return a 200 OK response,
   // then throw an exception.
   throw Exception('Failed to load projects');
 }
 }
}



这里我回调post方法加数据功能

import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:project/model/project_model.dart';
//import 'package:intl/intl.dart';
import 'package:provider/provider.dart';
import 'package:project/model/user_Model.dart';
import 'home_page02.dart';

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

  @override
  State<NewProject> createState() => _NewProjectState();
}

class _NewProjectState extends State<NewProject> {
 final TextEditingController projectname = TextEditingController();
  //TextEditingController  datelController = TextEditingController();
  //DateTime _selectedDate = DateTime.now();
   //DateTime currentDate = DateTime.now();

  // Future<void> _selectDate(BuildContext context) async {
  //   final DateTime? pickedDate = await showDatePicker(
  //       context: context,
  //       initialDate: currentDate,
  //       firstDate: DateTime(2015),
  //       lastDate: DateTime(2050));
  //   if (pickedDate != null && pickedDate != currentDate)
  //     setState(() {
  //       currentDate = pickedDate;
  //     });
  //     else print('empty')
  //     ;}
  void onAdd() {
     //final DateTime? textVal = DateTime.parse(datelController.text);
    final String desVal = projectname.text;

    if (/*textVal != null&&*/  desVal.isNotEmpty) {
      final Project project = Project(/*end_date: textVal,*/ project_name: desVal, user: 1,   /*start_date: null,*/ );
      Provider.of<ProjectProvider>(context, listen: false).addProject(project);
      print('$desVal in sucess');
    }
    else{
      print('empty or vaild');
      //print('$textVal in vaild');
    }
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      // App Bar The upper part in the application
      appBar: AppBar(
        backgroundColor:const Color(0xff076792),
        title: const Padding(
          padding: EdgeInsets.only(
            left: 50.0,
          ),
          // project Name
          child: Text(
            'New Project',
            style: TextStyle(
              color: Colors.white,
              fontWeight: FontWeight.bold,
              fontSize: 25.0,
                shadows: [
                  Shadow(
                      color: Color(0xa6A2B6D4),
                      offset: Offset(7,5),
                      blurRadius:20),
                ]
            ),
          ),
        ),
        iconTheme: const IconThemeData(
          color:Colors.white,
          size: 30.0,
        ),
      ),
      body: SingleChildScrollView(
        child: Column(
          children: [
            const Padding(
              padding: EdgeInsets.only(
                left: 10.0,
                top: 30.0,
              ),
              child: Padding(
                padding: EdgeInsets.only(right: 80.0),
                child: Text(
                  'Creating New Project',
                  style: TextStyle(
                    fontSize: 25.0,
                    color: Color(0xff076792),
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ),
            ),
            Container(
              margin: const EdgeInsets.fromLTRB(43, 24, 43, 15),
              child:  SizedBox(
                height: 45,
                child: TextField(
                  controller: projectname,
                  decoration: const InputDecoration(
                    hintText: "Enter project Name", //اليوسر يدخل اسم المشروع
                    hintStyle: TextStyle(
                      fontSize: 20,
                      color: Color(0xffc9c9c9), /*height: 2.5*/
                    ),
                    enabledBorder: OutlineInputBorder(
                        borderSide:
                            BorderSide(width: 2, color: Color(0xFF09679a))),
                  ),
                  keyboardType: TextInputType.name,
                ),
              ),
            ),
            // Container(
            //   margin: const EdgeInsets.fromLTRB(43, 0, 43, 20),
            //   child: SizedBox(
            //     height: 45,
            //     child: TextField(
            //       controller: datelController,
            //       onTap: () {
            //           showDatePicker(
            //           context: context,
            //           initialDate: DateTime.now(),
            //           firstDate: DateTime.now(),
            //           lastDate: DateTime(2050),
            //         ).then((value) {
            //           datelController.text = DateFormat("yyyy-MM-dd").format(value!);
            //         });
            //       },
            //       decoration: const InputDecoration(
            //         hintText: "End Date",
            //         hintStyle: TextStyle(
            //           fontSize: 20,
            //           color: Color(0xffc9c9c9),
            //         ),
            //         enabledBorder: OutlineInputBorder(
            //             borderSide: BorderSide(width: 2, color: Color(0xFF09679a))),
            //       ),
            //       keyboardType: TextInputType.datetime,
            //     ),
            //   ),
            // ),
            const SizedBox(
              height: 10.0,
            ),
            Container(
              width: double.infinity,
              height: 54,
              margin: const EdgeInsets.fromLTRB(75, 0, 75, 0),
              child: ElevatedButton(
                onPressed: () {
                  onAdd();
                  //_selectDate(context);
                      //Navigator.of(context).pop();
                },
                child: const Text(
                  'Create',
                  style: TextStyle(fontSize: 26, fontWeight: FontWeight.w400),
                ),
                style: ElevatedButton.styleFrom(
                    primary: const Color(0xFF09679a),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(30),
                      // f... flutter buttons!
                      side: const BorderSide(color: Colors.black, width: 1),
                    )),
              ),
            ),
            Container(
              alignment: Alignment.center,
              child: const Padding(
                padding: EdgeInsets.only(left: 60, top: 15.0, right: 60.0),
                child: Text(
                  'By Creating This Project You Will Be Admin Of The Project',
                  style: TextStyle(
                    fontSize: 18.0,
                    fontStyle: FontStyle.italic,
                    color: Colors.black,
                  ),
                ),
              ), //just text
            ),
           // Text(currentDate.toString()),
            // ElevatedButton(
            //   onPressed: () => _selectDate(context),
            //   child: Text('Select date'),
            // ),
          ],
        ),
      ),
    );
  }
}




此应用程序用于登录用户并查看项目并添加待办事项应用程序等项目 在 django 服务器上我可以添加项目并使用来自 [=29= 的管理员邮件查看项目注册字符串] 后端服务器 .. 在这个应用程序中我只能查看项目但不能添加新项目它是我的毕业项目所以我的生活取决于这个 :D 完整的源代码 https://github.com/alihassan75/project

您没有获取数据“用户”,因为您在登录后没有保存“用户”。

You need to save the user in any local storage. For, the demo purpose I will be saving that on HIVE

  1. 导入pubspec.yaml中的hive包 配置单元:^2.1.0
  2. 在主函数中(在 运行 应用程序之前)初始化并打开一个框“用户”
await Hive.initFlutter();
await Hive.openBox('User');
  1. 您可以像这样在登录功能中推送到用户框。
box = Hive.box('User');
int userId = responseJson['user']['id'];
box.put('user_id', userId);
  1. 您可以像这样随时阅读用户。
 late Box box;
 late int userid;
 box = Hive.box('User');
 super.initState();
 final data = box.get('user_id');
  1. 现在您可以将数据传递给 http api 调用。

谢谢