返回

android-rest api Fatter get方法有效,而post方法无效

发布时间:2022-04-19 15:55:22 345
# java

我在服务器响应中有此错误我在服务器响应中有此错误

这是模型和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'),
            // ),
          ],
        ),
      ),
    );
  }
}



此应用程序用于登录用户、查看项目和添加项目,如todo app在django服务器上,我可以通过python后端服务器的管理邮件添加项目和查看项目regstring。。在这个应用程序中,我只能查看项目,但不能添加新项目。这是我的毕业项目,所以我的生活依赖于:D完整的源代码https://github.com/alihassan75/project
特别声明:以上内容(图片及文字)均为互联网收集或者用户上传发布,本站仅提供信息存储服务!如有侵权或有涉及法律问题请联系我们。
举报
评论区(0)
按点赞数排序
用户头像
下一篇
gstreamer管道sendEOS死锁 2022-04-19 14:37:00