【问题标题】:Send Form to API in Flutter在 Flutter 中向 API 发送表单
【发布时间】:2023-03-19 02:39:01
【问题描述】:

我仍在努力适应 Flutter。我有一个用户注册表单,当用户单击按钮时,我希望将所有文本发送到我的 api 链接。但是有没有简单的方法可以做到这一点?还是我应该一一发短信?我的文本不应为空。我怎样才能提供这个?

我将来会调用我的 api,我想发送用户将在此处输入我的数据的文本。

        Future<RegisterComplete> createRegisterComplete(
        String email, String language) async {
      final http.Response response = await http.post(
        'MY API URL',
        headers: <String, String>{'Content-Type': 'application/json'},
        body: jsonEncode(<String, String>{
          'firstName': ' ',
          'lastName': ' ',
          'password': ' ',
          'countryCode': ' ',
          'language': ' ',
        }),
      );
      if (response.statusCode == 201) {
        return RegisterComplete.fromJson(json.decode(response.body));
      } else {
        print('Here:${response.statusCode}');
        throw Exception('Failed to load page');
      }
    }
    
    class RegisterPage extends StatefulWidget {
   
      @override
      _RegisterPageState createState() => _RegisterPageState();
    }
    
    class _RegisterPageState extends State<RegisterPage> {
      Future<ConfirmCode> _confirmCode;
      var textFieldPasswordController = TextEditingController();
      var textFieldConfirmPasswordController = TextEditingController();
 var cityController=TextEditingController();
  var nameController=TextEditingController();
  var surnameController=TextEditingController();
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          body: SafeArea(
            child: SingleChildScrollView(
              child: Column(
                children: [
                  Padding(
                    padding: const EdgeInsets.all(16.0),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        IconButton(
                          icon: Icon(Icons.arrow_back),
                          onPressed: () {
                            Navigator.pop(context);
                          },
                        ),
                        Text(
                          allTranslations.text('login'),
                          style: TextStyle(
                            fontSize: 13,
                            fontWeight: FontWeight.w600,
                            color: HexColor('#4A8EB0'),
                          ),
                        ),
                      ],
                    ),
                  ),
                  Text(
                      allTranslations.text('signUp'),
                    style: TextStyle(fontSize: 26, fontWeight: FontWeight.bold),
                  ),
                  _paddingWidget('E-mail', 'E-mail',emailController),
                 
                _paddingPasswordWidget(allTranslations.text('password'), allTranslations.text('password')),
                  _paddingWidget('City', 'City',cityController),
                  _paddingWidget('Name', 'Name',nameController),
                  _paddingWidget('Surname', 'Surname',surnameController),
                  Padding(
                    padding: EdgeInsets.all(16.0),
                    child: Container(
                      height: 50.0,
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(16),
                        color: HexColor('#B0B0B0'),
                        boxShadow: [
                          BoxShadow(
                            color: Colors.black.withOpacity(0.05),
                            blurRadius: 6,
                            offset: Offset(0, 2), // changes position of shadow
                          ),
                          BoxShadow(
                            color: Colors.black.withOpacity(0.1),
                            blurRadius: 20,
                            offset: Offset(0, 10), // changes position of shadow
                          ),
                        ],
                      ),
                      child: InkWell(
                        onTap: () {
                          setState(() {
                          BUTTON I USE FOR SİGN UP
                          });
                        },
                        child: Center(
                          child: Text(
                            allTranslations.text('signUp'),
                            style: TextStyle(
                              fontSize: 16,
                              color: Colors.white,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        );
      }
    
      _paddingWidget(String hintTextStr, String labelTextStr,TextEditingController _controller) {
        return Padding(
          padding: EdgeInsets.only(top: 15, left: 22, right: 22),
          child: TextFormField(
            controller: _controller,
            keyboardType: TextInputType.text,
            style: TextStyle(
              color: HexColor('#868686'),
            ),
            decoration: CommonInputStyle.textFieldStyle(
              hintTextStr: hintTextStr,
              labelTextStr: labelTextStr,
            ),
          ),
        );
      }
    
      _buttonWidget(String title,GestureTapCallback onPressed) {
        return Container(
          height: 40,
          width: 160,
          child: RaisedButton(
            child: Text(
              title,
              style: TextStyle(color: Colors.white),
            ),
            onPressed: onPressed,
            color: HexColor('#4A8EB0'),
            shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
          ),
        );
      }
    
      _paddingPasswordWidget(String hintTextStr, String labelTextStr) {
        return Padding(
          padding: EdgeInsets.only(top: 15, left: 22, right: 22),
          child: TextFormField(
            controller: textFieldPasswordController,
            keyboardType: TextInputType.text,
            style: TextStyle(
              color: HexColor('#868686'),
            ),
            decoration: CommonInputStyle.textFieldStyle(
              hintTextStr: hintTextStr,
              labelTextStr: labelTextStr,
            ),
            obscureText: true,
          ),
        );
      }
   

【问题讨论】:

    标签: api flutter


    【解决方案1】:

    首先。

    这个方法应该包括var data,它将成为你的身体的处理程序。

    像这样:

    Future<RegisterComplete> createRegisterComplete(
        String email, String language, var data) async {
      final http.Response response = await http.post(
        'MY API URL',
        headers: <String, String>{'Content-Type': 'application/json'},
        body: jsonEncode(data),
      );
      if (response.statusCode == 201) {
        return RegisterComplete.fromJson(json.decode(response.body));
      } else {
        print('Here:${response.statusCode}');
        throw Exception('Failed to load page');
      }
    }
    
    
    

    现在,这允许您实际包装来自 TextEditingControllers 的所有数据,因此您可以执行以下操作:

    child: InkWell(
                            onTap: () async {
                              setState(() {
                              var data = {
                                'firstName': nameController.text,
    'lastName': lastNameController.text,
              'password': passwordController.text,
              'countryCode': countryCodeController.text,
              'language': languageController.text,
    
                              }
    
    // here you do an actual API call
       await createRegisterComplete(emailController.text, languageController.text, data);
    
    
                              });
                            },
    

    但是有一种更好的方法可以实现这一点,它使用存储库来处理类似的事情。

    查看博客 -> https://medium.com/@cesarmcferreira/flutter-mvvm-architecture-using-dependency-injection-di-state-management-repository-pattern-92a4ef6ddfc3

    但还有很多例子

    【讨论】:

      猜你喜欢
      • 2021-10-01
      • 2021-01-10
      • 2022-09-26
      • 2014-07-10
      • 2022-12-11
      • 2018-12-30
      • 2023-03-31
      • 2020-07-31
      • 2019-03-26
      相关资源
      最近更新 更多