Flutter-无法发出POST请求

时间:2019-04-06 05:07:16

标签: android ios json dart flutter

我正在使用Flutter开发移动应用程序。现在,我正在尝试创建一个新用户。为此,我需要将数据插入“注册”页面并向REST API发出POST请求。

这是我的注册页面- register_page.dart

import 'package:flutter/material.dart';

import '../models/user.dart';
import '../models/user_language.dart';
import '../models/user_right.dart';
import '../custom_functions/data_fetch.dart';
import '../common_functions/app_navigation.dart';

class RegisterPage extends StatelessWidget {


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Register"),
      ),

      body: Container(
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage("assets/images/background_login_5.jpg"),
            fit: BoxFit.cover,
          ),
        ),
        child: RegisterForm(),
      ),
    );
  }


}


class RegisterForm extends StatefulWidget
{
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return RegisterFormState();
  }

}

class RegisterFormState extends State<RegisterForm>
{
  final borderColorGreen = const Color(0xff339966);

  bool passwordVisible, confirmPasswordVisible;

  TextEditingController nameTxtController =TextEditingController();
  TextEditingController emailTxtController =TextEditingController();
  TextEditingController mobileTxtController =TextEditingController();
  TextEditingController passwordTxtController =TextEditingController();
  TextEditingController confirmPasswordTxtController =TextEditingController();

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    passwordVisible=false;
    confirmPasswordVisible=false;

    return ListView(
          children: <Widget>[
            _buildTitleSection(),
            _buildInputFields("Name",nameTxtController, TextInputType.text, Icons.border_color, Colors.white),
            _buildInputFields("Email",emailTxtController,TextInputType.emailAddress, Icons.email, Colors.white),
            _buildInputFields("Mobile",mobileTxtController, TextInputType.phone, Icons.phone, Colors.white),
            _buildPasswordFields("Password",passwordTxtController,TextInputType.text),
            _buildPasswordFields("Confirm Password",confirmPasswordTxtController, TextInputType.text),
            _buildRegisterButton(),
          ],
        );
  }

  Widget _buildTitleSection() {
    return Container(
        margin: EdgeInsets.only(top: 20),
        padding: EdgeInsets.all(32),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              "manningmarket.lk",
              style: TextStyle(
                color: borderColorGreen,
                fontWeight: FontWeight.w900,
                fontSize: 25,
              ),
            ),
          ],
        ));
  }

  Widget _buildInputFields(String label, TextEditingController textController, TextInputType textInputType, IconData icon, Color iconColor) {
    return Container(
        margin: EdgeInsets.only(left: 20, bottom: 20),
        child: Column(
          children: <Widget>[

            Container(
              padding: EdgeInsets.only(right: 20),
              child: Row(
                children: <Widget>[
                  Flexible(
                    child: TextFormField(
                      controller: textController,
                      style: new TextStyle(color: Colors.white),
                      keyboardType: textInputType,
                      decoration: InputDecoration(
                        labelText: label,
                        fillColor: Colors.white,
                        labelStyle: TextStyle(
                            color: Colors.white, fontWeight: FontWeight.w600),
                        enabledBorder: OutlineInputBorder(
                          borderSide: const BorderSide(
                              color: Colors.white30, width: 2.0),
                          borderRadius: BorderRadius.circular(25.0),
                        ),
                        suffixIcon: IconButton(
                        icon: Icon(
                          icon,
                          color: iconColor
                        ),
                        onPressed: (){},
                      )
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ],
        ));
  }

    Widget _buildPasswordFields(String label, TextEditingController textController, TextInputType textInputType) {
    return Container(
        margin: EdgeInsets.only(left: 20, bottom: 20),
        child: Column(
          children: <Widget>[

            Container(
              padding: EdgeInsets.only(right: 20),
              child: Row(
                children: <Widget>[
                  Flexible(
                    child: TextFormField(
                      controller: textController,
                      style: new TextStyle(color: Colors.white),
                      keyboardType: textInputType,
                      decoration: InputDecoration(
                        labelText: label,
                        fillColor: Colors.white,
                        labelStyle: TextStyle(
                            color: Colors.white, fontWeight: FontWeight.w600),
                        enabledBorder: OutlineInputBorder(
                          borderSide: const BorderSide(
                              color: Colors.white30, width: 2.0),
                          borderRadius: BorderRadius.circular(25.0),
                        ),
                        suffixIcon: IconButton(
                        icon: Icon(
                          // Based on passwordVisible state choose the icon
                          passwordVisible
                              ? Icons.visibility
                              : Icons.visibility_off,
                          color: Theme.of(context).primaryColorDark,
                        ),
                        onPressed: () {
                          // Update the state i.e. toogle the state of passwordVisible variable
                          setState(() {
                            passwordVisible
                                ? passwordVisible = false
                                : passwordVisible = true;
                          });
                        },
                      )
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ],
        ));
  }

  Widget _buildRegisterButton() {
    return Container(
      margin: EdgeInsets.only(top: 10, right: 20, left: 20),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Flexible(
              child: SizedBox(
                  width: double.infinity, // match_parent
                  child: RaisedButton(
                    child: Text(
                      "Create Account",
                      style: TextStyle(
                          color: Colors.white,
                          fontSize: 18,
                          fontWeight: FontWeight.normal),
                    ),
                    shape: RoundedRectangleBorder(
                        borderRadius: new BorderRadius.circular(30.0)),
                    color: borderColorGreen,
                    onPressed: () {
                      setState(() {
                        _createUser();
                      });

                    },
                  )))
        ],
      ),
    );
  }

  void _createUser()
  {

    UserRight userRight = UserRight(
      iduserRight: 2
    );

    UserLanguage userLanguage = UserLanguage(
      iduserLanguage: 1
    );

    User user = User(
      name: nameTxtController.text,
      email: emailTxtController.text,
      phone: mobileTxtController.text,
      userLanguage: userLanguage,
      userRights: userRight

    );

    DataFetch().createUser(AppNavigation.getAPIUrl() +
          "user/saveUser", user).then((String result){
            print("RESULT IS: "+result);
          });
  }

}

请检查_createUser以查看数据post部分

现在,下面是执行post工作的代码

//Create User
  Future<String> createUser(
      String url, User body) async {
    return http.post(url, body: body.toJson()).then((http.Response response) {
      final int statusCode = response.statusCode;

      if (statusCode < 200 || statusCode > 400 || response.body == null) {
        throw new Exception("Error while fetching data");
      } else {
        return response.body;
      }
    });
  }

最后,模型。首先让我们看一下User模型

User.dart

import 'package:json_annotation/json_annotation.dart';

import './user_language.dart';
import './user_right.dart';


part 'user.g.dart';


@JsonSerializable()

class User {
  int iduser;
  UserLanguage userLanguage;
  UserRight userRights;
  String name;
  String address;
  String phone;
  String email;
  int dob;
  int deleteTimestamp;
  int dateCreated;
  int lastUpdated;

  User(
      {this.iduser,
      this.userLanguage,
      this.userRights,
      this.name,
      this.address,
      this.phone,
      this.email,
      this.dob,
      this.deleteTimestamp,
      this.dateCreated,
      this.lastUpdated});


  factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);

  Map<String, dynamic> toJson() => _$UserToJson(this);
}

User.g.dart

// GENERATED CODE - DO NOT MODIFY BY HAND

part of 'user.dart';

// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************

User _$UserFromJson(Map<String, dynamic> json) {
  return User(
      iduser: json['iduser'] as int,
      userLanguage: json['userLanguage'] == null
          ? null
          : UserLanguage.fromJson(json['userLanguage'] as Map<String, dynamic>),
      userRights: json['userRights'] == null
          ? null
          : UserRight.fromJson(json['userRights'] as Map<String, dynamic>),
      name: json['name'] as String,
      address: json['address'] as String,
      phone: json['phone'] as String,
      email: json['email'] as String,
      dob: json['dob'] as int,
      deleteTimestamp: json['deleteTimestamp'] as int,
      dateCreated: json['dateCreated'] as int,
      lastUpdated: json['lastUpdated'] as int);
}

Map<String, dynamic> _$UserToJson(User instance) => <String, dynamic>{
      'iduser': instance.iduser,
      'userLanguage': instance.userLanguage,
      'userRights': instance.userRights,
      'name': instance.name,
      'address': instance.address,
      'phone': instance.phone,
      'email': instance.email,
      'dob': instance.dob,
      'deleteTimestamp': instance.deleteTimestamp,
      'dateCreated': instance.dateCreated,
      'lastUpdated': instance.lastUpdated
    };

user_right.dart

import 'package:json_annotation/json_annotation.dart';

part 'user_right.g.dart';

@JsonSerializable()

class UserRight
{
   int iduserRight;
   String userRight;
   int deleteTimestamp;
   int dateCreated;
   int lastUpdated;

   UserRight({this.iduserRight, this.userRight, this.deleteTimestamp, this.dateCreated, this.lastUpdated});

  factory UserRight.fromJson(Map<String, dynamic> json) =>
      _$UserRightFromJson(json);

  Map<String, dynamic> toJson() => _$UserRightToJson(this);
}

user_right.g.dart

// GENERATED CODE - DO NOT MODIFY BY HAND

part of 'user_right.dart';

// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************

UserRight _$UserRightFromJson(Map<String, dynamic> json) {
  return UserRight(
      iduserRight: json['iduserRight'] as int,
      userRight: json['userRight'] as String,
      deleteTimestamp: json['deleteTimestamp'] as int,
      dateCreated: json['dateCreated'] as int,
      lastUpdated: json['lastUpdated'] as int);
}

Map<String, dynamic> _$UserRightToJson(UserRight instance) => <String, dynamic>{
      'iduserRight': instance.iduserRight,
      'userRight': instance.userRight,
      'deleteTimestamp': instance.deleteTimestamp,
      'dateCreated': instance.dateCreated,
      'lastUpdated': instance.lastUpdated
    };

user_language.dart

import 'package:json_annotation/json_annotation.dart';

part 'user_language.g.dart';

@JsonSerializable()

class UserLanguage {
  int iduserLanguage;
  String language;
  int deleteTimestamp;
  int dateCreated;
  int lastUpdated;

  UserLanguage({this.iduserLanguage, this.language, this.deleteTimestamp,
      this.dateCreated, this.lastUpdated});

  factory UserLanguage.fromJson(Map<String, dynamic> json) =>
      _$UserLanguageFromJson(json);

  Map<String, dynamic> toJson() => _$UserLanguageToJson(this);
}

user_language.g.dart

// GENERATED CODE - DO NOT MODIFY BY HAND

part of 'user_language.dart';

// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************

UserLanguage _$UserLanguageFromJson(Map<String, dynamic> json) {
  return UserLanguage(
      iduserLanguage: json['iduserLanguage'] as int,
      language: json['language'] as String,
      deleteTimestamp: json['deleteTimestamp'] as int,
      dateCreated: json['dateCreated'] as int,
      lastUpdated: json['lastUpdated'] as int);
}

Map<String, dynamic> _$UserLanguageToJson(UserLanguage instance) =>
    <String, dynamic>{
      'iduserLanguage': instance.iduserLanguage,
      'language': instance.language,
      'deleteTimestamp': instance.deleteTimestamp,
      'dateCreated': instance.dateCreated,
      'lastUpdated': instance.lastUpdated
    };

执行注册页面并按注册按钮时,出现以下错误

E/flutter ( 2367): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: NoSuchMethodError: The getter 'length' was called on null.
E/flutter ( 2367): Receiver: null
E/flutter ( 2367): Tried calling: length
E/flutter ( 2367): #0      Object.noSuchMethod (dart:core/runtime/libobject_patch.dart:50:5)
E/flutter ( 2367): #1      _Uri._uriEncode (dart:core/runtime/liburi_patch.dart:44:23)
E/flutter ( 2367): #2      Uri.encodeQueryComponent (dart:core/uri.dart:1098:17)
E/flutter ( 2367): #3      mapToQuery.<anonymous closure>
E/flutter ( 2367): #4      CastMap.forEach.<anonymous closure> (dart:_internal/cast.dart:286:8)
E/flutter ( 2367): #5      __InternalLinkedHashMap&_HashVMBase&MapMixin&_LinkedHashMapMixin.forEach (dart:collection/runtime/libcompact_hash.dart:367:8)
E/flutter ( 2367): #6      CastMap.forEach (dart:_internal/cast.dart:285:13)
E/flutter ( 2367): #7      mapToQuery
E/flutter ( 2367): #8      Request.bodyFields=
E/flutter ( 2367): #9      BaseClient._sendUnstreamed
E/flutter ( 2367): <asynchronous suspension>
E/flutter ( 2367): #10     BaseClient.post
E/flutter ( 2367): #11     post.<anonymous closure>
E/flutter ( 2367): #12     _withClient
E/flutter ( 2367): <asynchronous suspension>
E/flutter ( 2367): #13     post
E/flutter ( 2367): #14     DataFetch.createUser
E/flutter ( 2367): <asynchronous suspension>
E/flutter ( 2367): #15     RegisterFormState._createUser
E/flutter ( 2367): #16     RegisterFormState._buildRegisterButton.<anonymous closure>.<anonymous closure>
E/flutter ( 2367): #17     State.setState 
E/flutter ( 2367): #18     RegisterFormState._buildRegisterButton.<anonymous closure>
E/flutter ( 2367): #19     _InkResponseState._handleTap 
E/flutter ( 2367): #20     _InkResponseState.build.<anonymous closure> 
E/flutter ( 2367): #21     GestureRecognizer.invokeCallback 
E/flutter ( 2367): #22     TapGestureRecognizer._checkUp 
E/flutter ( 2367): #23     TapGestureRecognizer.acceptGesture 
E/flutter ( 2367): #24     GestureArenaManager.sweep 
E/flutter ( 2367): #25     _WidgetsFlutterBinding&BindingBase&GestureBinding.handleEvent 
E/flutter ( 2367): #26     _WidgetsFlutterBinding&BindingBase&GestureBinding.dispatchEvent 
E/flutter ( 2367): #27     _WidgetsFlutterBinding&BindingBase&GestureBinding._handlePointerEvent 
E/flutter ( 2367): #28     _WidgetsFlutterBinding&BindingBase&GestureBinding._flushPointerEventQueue 
E/flutter ( 2367): #29     _WidgetsFlutterBinding&BindingBase&GestureBinding._handlePointerDataPacket 
E/flutter ( 2367): #30     _rootRunUnary (dart:async/zone.dart:1136:13)
E/flutter ( 2367): #31     _CustomZone.runUnary (dart:async/zone.dart:1029:19)
E/flutter ( 2367): #32     _CustomZone.runUnaryGuarded (dart:async/zone.dart:931:7)
E/flutter ( 2367): #33     _invoke1 (dart:ui/hooks.dart:223:10)
E/flutter ( 2367): #34     _dispatchPointerDataPacket (dart:ui/hooks.dart:144:5)
E/flutter ( 2367):

我该如何解决?

特别说明

https://flutter.dev/docs/development/data-and-backend/json一样,{p> <>。g.dart类(例如:user.g.dart)是通过flutter packages pub run build_runner build生成的。在这里介绍的模型类中,我使用了named arguments


更新2

我应用了@diegoveloper的第二个建议。以下是user.dart

import 'package:json_annotation/json_annotation.dart';

import './user_language.dart';
import './user_right.dart';

part 'user.g.dart';

@JsonSerializable()

class User {
  int iduser;
  UserLanguage userLanguage;
  UserRight userRights;
  String name;
  String address;
  String phone;
  String email;
  int dob;
  int deleteTimestamp;
  int dateCreated;
  int lastUpdated;

  User(
      {this.iduser,
      this.userLanguage,
      this.userRights,
      this.name,
      this.address,
      this.phone,
      this.email,
      this.dob,
      this.deleteTimestamp,
      this.dateCreated,
      this.lastUpdated});

  factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);


  Map<String, dynamic> toJson(User instance) => <String, dynamic>{
  "iduser": instance.iduser,
  "userLanguage": instance.userLanguage.toJson(),
  "userRights": instance.userRights.toJson(),
  "name": instance.name,
  "address": instance.address,
  "phone": instance.phone,
  "email": instance.email,
  "dob": instance.dob,
  "deleteTimestamp": instance.deleteTimestamp,
  "dateCreated": instance.dateCreated,
  "lastUpdated": instance.lastUpdated
  };

}

下面是flutter packages pub run build_runner build命令生成的代码。

user.g.dart

// GENERATED CODE - DO NOT MODIFY BY HAND

part of 'user.dart';

// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************

User _$UserFromJson(Map<String, dynamic> json) {
  return User(
      iduser: json['iduser'] as int,
      userLanguage: json['userLanguage'] == null
          ? null
          : UserLanguage.fromJson(json['userLanguage'] as Map<String, dynamic>),
      userRights: json['userRights'] == null
          ? null
          : UserRight.fromJson(json['userRights'] as Map<String, dynamic>),
      name: json['name'] as String,
      address: json['address'] as String,
      phone: json['phone'] as String,
      email: json['email'] as String,
      dob: json['dob'] as int,
      deleteTimestamp: json['deleteTimestamp'] as int,
      dateCreated: json['dateCreated'] as int,
      lastUpdated: json['lastUpdated'] as int);
}

Map<String, dynamic> _$UserToJson(User instance) => <String, dynamic>{
      'iduser': instance.iduser,
      'userLanguage': instance.userLanguage,
      'userRights': instance.userRights,
      'name': instance.name,
      'address': instance.address,
      'phone': instance.phone,
      'email': instance.email,
      'dob': instance.dob,
      'deleteTimestamp': instance.deleteTimestamp,
      'dateCreated': instance.dateCreated,
      'lastUpdated': instance.lastUpdated
    };

然后,我不得不修改我的Future代码。请在下面检查。现在您可以看到我必须将User对象传递到toJSON方法中。

 Future<String> createUser(
      String url, User body) async {

      print("BODY: "+body.toJson(body).toString());

    return http.post(url, body: convert.json.encode(body.toJson(body))).then((http.Response response) {
      final int statusCode = response.statusCode;

      print("RESPONSE: "+response.body);
      print("STATUS CODE: "+statusCode.toString());

      if (statusCode < 200 || statusCode > 400 || response.body == null) {
        throw new Exception("Error while fetching data");
      } else {
        return response.body;
      }
    });
  }

我收到以下错误

flutter (21372): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: Exception: Error while fetching data
E/flutter (21372): #0      DataFetch.createUser.<anonymous closure>
E/flutter (21372): #1      _rootRunUnary (dart:async/zone.dart:1132:38)
E/flutter (21372): #2      _CustomZone.runUnary (dart:async/zone.dart:1029:19)
E/flutter (21372): #3      _FutureListener.handleValue (dart:async/future_impl.dart:126:18)
E/flutter (21372): #4      Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:639:45)
E/flutter (21372): #5      Future._propagateToListeners (dart:async/future_impl.dart:668:32)
E/flutter (21372): #6      Future._complete (dart:async/future_impl.dart:473:7)
E/flutter (21372): #7      _SyncCompleter.complete (dart:async/future_impl.dart:51:12)
E/flutter (21372): #8      _AsyncAwaitCompleter.complete (dart:async/runtime/libasync_patch.dart:28:18)
E/flutter (21372): #9      _completeOnAsyncReturn (dart:async/runtime/libasync_patch.dart:294:13)
E/flutter (21372): #10     _withClient (package:http/http.dart)
E/flutter (21372): <asynchronous suspension>
E/flutter (21372): #11     post
E/flutter (21372): #12     DataFetch.createUser
E/flutter (21372): <asynchronous suspension>
E/flutter (21372): #13     RegisterFormState._createUser
E/flutter (21372): #14     RegisterFormState._buildRegisterButton.<anonymous closure>.<anonymous closure>
E/flutter (21372): #15     State.setState 
E/flutter (21372): #16     RegisterFormState._buildRegisterButton.<anonymous closure>
E/flutter (21372): #17     _InkResponseState._handleTap 
E/flutter (21372): #18     _InkResponseState.build.<anonymous closure> 
E/flutter (21372): #19     GestureRecognizer.invokeCallback 
E/flutter (21372): #20     TapGestureRecognizer._checkUp 
E/flutter (21372): #21     TapGestureRecognizer.acceptGesture 
E/flutter (21372): #22     GestureArenaManager.sweep 
E/flutter (21372): #23     _WidgetsFlutterBinding&BindingBase&GestureBinding.handleEvent 
E/flutter (21372): #24     _WidgetsFlutterBinding&BindingBase&GestureBinding.dispatchEvent 
E/flutter (21372): #25     _WidgetsFlutterBinding&BindingBase&GestureBinding._handlePointerEvent 
E/flutter (21372): #26     _WidgetsFlutterBinding&BindingBase&GestureBinding._flushPointerEventQueue 
E/flutter (21372): #27     _WidgetsFlutterBinding&BindingBase&GestureBinding._handlePointerDataPacket 
E/flutter (21372): #28     _rootRunUnary (dart:async/zone.dart:1136:13)
E/flutter (21372): #29     _CustomZone.runUnary (dart:async/zone.dart:1029:19)
E/flutter (21372): #30     _CustomZone.runUnaryGuarded (dart:async/zone.dart:931:7)
E/flutter (21372): #31     _invoke1 (dart:ui/hooks.dart:223:10)
E/flutter (21372): #32     _dispatchPointerDataPacket (dart:ui/hooks.dart:144:5)
E/flutter (21372):

在下面打印响应。正文给出

<!doctype html><html lang="en"><head><title>HTTP Status 415 – Unsupported Media Type</title><style type="text/css">h1 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:22px;} h2 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:16px;} h3 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:14px;} body {font-family:Tahoma,Arial,sans-serif;color:black;background-color:white;} b {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;} p {font-family:Tahoma,Arial,sans-serif;background:white;color:black;font-size:12px;} a {color:black;} a.name {color:black;} .line {height:1px;background-color:#525D76;border:none;}</style></head><body><h1>HTTP Status 415 – Unsupported Media Type</h1><hr class="line" /><p><b>Type</b> Status Report</p><p><b>Message</b> Unsupported Media Type</p><p><b>Description</b> The origin server is refusing to service the request because the payload is in a format

1 个答案:

答案 0 :(得分:1)

在发送数据之前,您必须对body进行编码。

更改此:

return http.post(url, body: body.toJson())

对此:

return http.post(url, body: json.encode(body.toJson()))

更新

根据您的最后一个错误,我认为您忘记解析toJson userLanguage和userRights

Map<String, dynamic> _$UserToJson(User instance) => <String, dynamic>{
  'iduser': instance.iduser,
  'userLanguage': instance.userLanguage.toJson(),
  'userRights': instance.userRights.toJson(),