【问题标题】:Flutter is not posting my question to the APIFlutter 没有将我的问题发布到 API
【发布时间】:2022-01-17 03:32:56
【问题描述】:

我在 Flutter 中有这个注册页面,但它没有更新我的数据库...

我的 API 很好,当使用 postman 之类的东西并发送完全相同的 JSON 时,我的数据库会更新,所以问题在于以下代码:

postData() async {
  print('entered postDAta');
  var response = http.post(
      Uri.parse("http://localhost:8080/api/auth/signup"),
      body: {
        "username": "flota",
        "email": "hay@flut.com",
        "password": "87654321",
      }
  );
  print('exited postdata');
}

floatingActionButton: FloatingActionButton(
        onPressed: postData,
        child: Icon(Icons.add),
      ),

完整的代码以防万一

import 'dart:developer' as developer;
import 'dart:core';

import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'dart:convert';
import 'Widget/bezierContainer.dart';
import 'loginPage.dart';

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

postData() async {
  print('entered postDAta');
  var response = http.post(
      Uri.parse("http://localhost:8080/api/auth/signup"),
      body: {
        "username": "flota",
        "email": "hay@flut.com",
        "password": "87654321",
      }
  );
  print('exited postdata');
}

class SignUpPage extends StatefulWidget {
  SignUpPage({Key ?key, this.title}) : super(key: key);

  final String? title;

  @override
  _SignUpPageState createState() => _SignUpPageState();
}

class _SignUpPageState extends State<SignUpPage> {
  Widget _backButton() {
    return InkWell(
      onTap: () {
        Navigator.pop(context);
      },
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: 10),
        child: Row(
          children: <Widget>[
            Container(
              padding: EdgeInsets.only(left: 0, top: 10, bottom: 10),
              child: Icon(Icons.keyboard_arrow_left, color: Colors.black),
            ),
            Text('Back',
                style: TextStyle(fontSize: 12, fontWeight: FontWeight.w500))
          ],
        ),
      ),
    );
  }

  Widget _entryField(String title, {bool isPassword = false}) {
    return Container(
      margin: EdgeInsets.symmetric(vertical: 10),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Text(
            title,
            style: TextStyle(fontWeight: FontWeight.bold, fontSize: 15),
          ),
          SizedBox(
            height: 10,
          ),
          TextField(
              obscureText: isPassword,
              decoration: InputDecoration(
                  border: InputBorder.none,
                  fillColor: Color(0xfff3f3f4),
                  filled: true))
        ],
      ),
    );
  }

  Widget _submitButton() {
    return Container(
      width: MediaQuery.of(context).size.width,
      padding: EdgeInsets.symmetric(vertical: 15),
      alignment: Alignment.center,
      decoration: BoxDecoration(
          borderRadius: BorderRadius.all(Radius.circular(5)),
          boxShadow: <BoxShadow>[
            BoxShadow(
                color: Colors.grey.shade200,
                offset: Offset(2, 4),
                blurRadius: 5,
                spreadRadius: 2)
          ],
          gradient: LinearGradient(
              begin: Alignment.centerLeft,
              end: Alignment.centerRight,
              colors: [Color(0xfffbb448), Color(0xfff7892b)])),
      child: Text(
        'Register Now',
        style: TextStyle(fontSize: 20, color: Colors.white),
      ),
    );
  }

  Widget _loginAccountLabel() {
    return InkWell(
      onTap: () {
        Navigator.push(
            context, MaterialPageRoute(builder: (context) => LoginPage()));
      },
      child: Container(
        margin: EdgeInsets.symmetric(vertical: 20),
        padding: EdgeInsets.all(15),
        alignment: Alignment.bottomCenter,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'Already have an account ?',
              style: TextStyle(fontSize: 13, fontWeight: FontWeight.w600),
            ),
            SizedBox(
              width: 10,
            ),
            Text(
              'Login',
              style: TextStyle(
                  color: Color(0xfff79c4f),
                  fontSize: 13,
                  fontWeight: FontWeight.w600),
            ),
          ],
        ),
      ),
    );
  }

  Widget _title() {
    return RichText(
      textAlign: TextAlign.center,
      text: TextSpan(
          text: 'd',
          style: TextStyle(
              fontSize: 30,
              fontWeight: FontWeight.w700,
              color: Color(0xffe46b10)
          ),

          children: [
            TextSpan(
              text: 'ev',
              style: TextStyle(color: Colors.black, fontSize: 30),
            ),
            TextSpan(
              text: 'rnz',
              style: TextStyle(color: Color(0xffe46b10), fontSize: 30),
            ),
          ]),
    );
  }

  Widget _emailPasswordWidget() {
    return Column(
      children: <Widget>[
        _entryField("Username"),
        _entryField("Email id"),
        _entryField("Password", isPassword: true),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    final height = MediaQuery.of(context).size.height;
    return Scaffold(
      body: Container(
        height: height,
        child: Stack(
          children: <Widget>[
            Positioned(
              top: -MediaQuery.of(context).size.height * .15,
              right: -MediaQuery.of(context).size.width * .4,
              child: BezierContainer(),
            ),
            Container(
              padding: EdgeInsets.symmetric(horizontal: 20),
              child: SingleChildScrollView(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    SizedBox(height: height * .2),
                    _title(),
                    SizedBox(
                      height: 50,
                    ),
                    _emailPasswordWidget(),
                    SizedBox(
                      height: 20,
                    ),
                    _submitButton(),
                    SizedBox(height: height * .14),
                    _loginAccountLabel(),
                  ],
                ),
              ),
            ),
            Positioned(top: 40, left: 0, child: _backButton()),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: postData,
        child: Icon(Icons.add),
      ),
    );
  }
}
    

【问题讨论】:

  • var response = http.post换成var response = await http.post能解决吗?
  • 不,@enzo,谢谢
  • 调用此API时是否有错误日志?如果有的话,你可以在控制台中添加错误日志
  • 如果您尝试注册,请参考我的回答here 希望对您有所帮助。

标签: flutter


【解决方案1】:

当我们在移动设备中向服务器发送数据时,主要是原始格式。为此,我们必须使用 'jsonEncode' 进行转换,并且我们必须设置标题。

   postData() async {
     print('entered postDAta');
       var response = await http.post(
       Uri.parse("http://localhost:8080/api/auth/signup"),
      body: jsonEncode({
       "username": "flota",
       "email": "hay@flut.com",
      "password": "87654321",
      }),headers: {
      'Content-type': 'application/json',
      'Accept': 'application/json',
    }
   );
   print(response.body);
    print('exited postdata');
      }

【讨论】:

    【解决方案2】:
    postData() async {
      print('entered postDAta');
      var response = await http.post(
          Uri.parse("http://localhost:8080/api/auth/signup"),
          body: {
            "username": "flota",
            "email": "hay@flut.com",
            "password": "87654321",
          }
      );
      print('exited postdata');
    }
    

    在 http.post 之前使用 await。我认为它会起作用。

    【讨论】:

      【解决方案3】:

      我想你已经得到了答案,这里有一些资源来了解 API 方法的流程-

      flutter中的API可以通过官网处理-

      https://docs.flutter.dev/cookbook/networking/fetch-data

      这里有一个很好的 API 集成基本流程的文档-

      https://mobikul.com/http-api-calling-in-flutter/

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-12-16
        • 2016-12-19
        • 2019-12-28
        • 2020-02-08
        • 2021-07-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多