在flutter中动态构建表单,以JSON格式发布新数据

j9per5c4  于 2023-03-13  发布在  Flutter
关注(0)|答案(1)|浏览(308)

我有一个类来使用通过JSON发送的Web服务中的REST数据。我使用一个类来获取正确格式的数据。类如下所示:

class BuildingSiteVisits {
  int? id;
  String? name;
  Float? lat;
  Float? long;

BuildingSiteVisits(
      {this.id,
      this.name,
      this.lat,
      this.long});

BuildingSiteVisits.fromJson(Map<String, dynamic> json) {
id = json['id'];
    name = json['name'];
    lat = json['lat'];
    long = json['long'];
}

Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = <String, dynamic>{};
data['id'] = id;
    data['name'] = name;
    data['lat'] = lat;
    data['long'] = long;
    return data;
  }
}

Original类有更多的字段。我如何创建一个动态表单,可以发送正确的JSON,正确的类型转换,如字符串的引用值,int和float的不引用等。对于类中的每个字段,应该有一个对应的texteditfield。到目前为止,我已经从字符串列表中完成了,但Web服务将忽略这些值,因为错误的格式字段。

4smxwvx5

4smxwvx51#

我们使用http.post()方法将数据发送到API,并相应地处理响应。

import 'dart:convert';

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

class MyForm extends StatefulWidget {
@override
_MyFormState createState() => _MyFormState();
}

class _MyFormState extends State<MyForm> {
final _formKey = GlobalKey<FormState>();
final _nameController = TextEditingController();
final _latController = TextEditingController();
final _longController = TextEditingController();

@override
Widget build(BuildContext context) {
return Scaffold(
  appBar: AppBar(
    title: Text('Post new data'),
  ),
  body: Padding(
    padding: EdgeInsets.all(16.0),
    child: Form(
      key: _formKey,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          TextFormField(
            controller: _nameController,
            decoration: InputDecoration(labelText: 'Name'),
            validator: (value) {
              if (value.isEmpty) {
                return 'Please enter a name';
              }
              return null;
            },
          ),
          TextFormField(
            controller: _latController,
            decoration: InputDecoration(labelText: 'Latitude'),
            validator: (value) {
              if (value.isEmpty) {
                return 'Please enter a latitude';
              }
              return null;
            },
          ),
          TextFormField(
            controller: _longController,
            decoration: InputDecoration(labelText: 'Longitude'),
            validator: (value) {
              if (value.isEmpty) {
                return 'Please enter a longitude';
              }
              return null;
            },
          ),
          SizedBox(height: 16.0),
          RaisedButton(
            onPressed: () async {
              if (_formKey.currentState.validate()) {
                // create a BuildingSiteVisits instance
                final data = BuildingSiteVisits(
                  name: _nameController.text,
                  lat: double.parse(_latController.text),
                  long: double.parse(_longController.text),
                );
                final jsonEncoded = json.encode(data.toJson());

                // send the data to your API
                final response = await http.post(
                  'https://your-api-endpoint.com/new-data',
                  headers: {'Content-Type': 'application/json'},
                  body: jsonEncoded,
                );

                // handle the response from your API
                if (response.statusCode == 200) {
                  // success
                  print('Data posted successfully');
                } else {
                  // error
                  print('Error posting data: ${response.statusCode}');
                 }
               }
             },
             child: Text('Post data'),
           ),
         ],
       ),
     ),
   ),
  );
 }
}

相关问题