Как отправить массив JSON, заполненный данными из Flutter, в API, созданный с помощью phpPhp

Кемеровские программисты php общаются здесь
Ответить
Anonymous
 Как отправить массив JSON, заполненный данными из Flutter, в API, созданный с помощью php

Сообщение Anonymous »

В настоящее время я работаю над проектом и столкнулся с проблемой отправки массива JSON в PHP API.
Вот код, который я написал для приложения flutter:

Код: Выделить всё

class AddDeviceFormScreen extends StatelessWidget {
final TextEditingController deviceNameController = TextEditingController();
final TextEditingController deviceDescriptionController = TextEditingController();
final TextEditingController deviceClusterController = TextEditingController();
final TextEditingController deviceGeolocation1Controller = TextEditingController();
final TextEditingController deviceGeolocation2Controller = TextEditingController();
final TextEditingController sensorWater1LevelController = TextEditingController();
final TextEditingController sensorWater2LevelController = TextEditingController();
final TextEditingController sensorWater3LevelController = TextEditingController();
final TextEditingController sensorLevel1AlertLevelController = TextEditingController();
final TextEditingController deviceWiFiNameController = TextEditingController();
final TextEditingController deviceWiFiPasswordController = TextEditingController();
final TextEditingController deviceMACController = TextEditingController();

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Страница за добавяне на устройсво'),
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: SingleChildScrollView(
child: Form(
autovalidateMode: AutovalidateMode.onUserInteraction,
child: Column(
children: [
TextFormField(
controller: deviceNameController,
decoration: InputDecoration(labelText: 'Име на устройство'),
validator: (value) {
if (value == null || value.trim().isEmpty) {
return 'Полето е задължително';
}
return null;
},
),
TextFormField(
controller: deviceDescriptionController,
decoration: InputDecoration(labelText: 'Описание на устройство'),
),
TextFormField(
controller: deviceClusterController,
decoration: InputDecoration(labelText: 'Принадлежност към клъстер'),
validator: (value) {
if (value == null || value.trim().isEmpty) {
return 'Полето е задължително';
}
return null;
},
),
TextFormField(
controller: deviceGeolocation1Controller,
decoration: InputDecoration(labelText: 'Геолокация / Географска ширина'),
validator: (value) {
if (value == null || !RegExp(r"[+-]?\d+(\.\d+)?").hasMatch(value.trim())) {
return 'Невалидна стойност';
}
return null;
},
),
TextFormField(
controller: deviceGeolocation2Controller,
decoration: InputDecoration(labelText: 'Геолокация / Географска дължина'),
validator: (value) {
if (value == null || !RegExp(r"[+-]?\d+(\.\d+)?").hasMatch(value.trim())) {
return 'Невалидна стойност';
}
return null;
},
),
TextFormField(
controller: sensorWater1LevelController,
decoration: InputDecoration(labelText: 'Критично ниво за известяване на сензор 1'),
validator: (value) {
if (value == null || !RegExp(r"[+-]?\d+").hasMatch(value.trim())) {
return 'Невалидна стойност';
}
return null;
},
),
TextFormField(
controller: sensorWater2LevelController,
decoration: InputDecoration(labelText: 'Критично ниво за известяване на сензор 2'),
validator:  (value) {
if (value == null || !RegExp(r"[+-]?\d+").hasMatch(value.trim())) {
return 'Невалидна стойност';
}
return null;
},
),
TextFormField(
controller: sensorWater3LevelController,
decoration: InputDecoration(labelText: 'Критично ниво за известяване на сензор 3'),
validator: (value) {
if (value == null || !RegExp(r"[+-]?\d+").hasMatch(value.trim())) {
return 'Невалидна стойност';
}
return null;
},
),
TextFormField(
controller: sensorLevel1AlertLevelController,
decoration: InputDecoration(labelText: 'Критично ниво за известяване на ултразвуков сензор(в метри)'),
validator: (value) {
if (value == null || !RegExp(r"[+-]?\d+").hasMatch(value.trim())) {
return 'Невалидна стойност';
}
return null;
},
),
TextFormField(
controller: deviceWiFiNameController,
decoration: InputDecoration(labelText: 'Име на безжичната мрежа'),
validator: (value) {
if (value == null || value.trim().isEmpty) {
return 'Полето е задължително';
}
return null;
},
),
TextFormField(
controller: deviceWiFiPasswordController,
decoration: InputDecoration(labelText: 'Парола за безжичната мрежа'),
validator: (value) {
if (value == null || value.trim().isEmpty) {
return 'Полето е задължително';
}
return null;
},
),
TextFormField(
controller: deviceMACController,
decoration: InputDecoration(labelText: 'MAC адрес / сериен номер на устройството'),
validator: (value) {
if (value == null || !RegExp(r"([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})").hasMatch(value.trim())) {
return 'Невалидна стойност';
}
return null;
},
),
SizedBox(height: 16),
ElevatedButton(
onPressed: () async {
print('Button pressed');
if (Form.of(context).validate()) {
// Collect form data
Map  formData = {
'device_name1': deviceNameController.text,
'device_description1': deviceDescriptionController.text,
'device_cluster1': deviceClusterController.text,
'device_geolocation11': deviceGeolocation1Controller.text,
'device_geolocation21': deviceGeolocation2Controller.text,
'sensor_water_1_level_1': sensorWater1LevelController.text,
'sensor_water_2_level_1': sensorWater2LevelController.text,
'sensor_water_3_level_1': sensorWater3LevelController.text,
'sensor_level_1_alert_level_1': sensorLevel1AlertLevelController.text,
'device_wifi_network_name1': deviceWiFiNameController.text,
'device_wifi_network_password1': deviceWiFiPasswordController.text,
'device_mac1': deviceMACController.text,
};

// Print the collected form data (for debugging purposes)
print('Form Data: $formData');

// Send data to the PHP backend
await sendFormDataToApi(formData);

// Navigate back to the previous screen
Navigator.pop(context);
}
},
child: Text('Добави устройство'),
),
SizedBox(height: 16),
ElevatedButton(
onPressed: () {
// Reset form fields
deviceNameController.clear();
deviceDescriptionController.clear();
deviceClusterController.clear();
deviceGeolocation1Controller.clear();
deviceGeolocation2Controller.clear();
sensorWater1LevelController.clear();
sensorWater2LevelController.clear();
sensorWater3LevelController.clear();
sensorLevel1AlertLevelController.clear();
deviceWiFiNameController.clear();
deviceWiFiPasswordController.clear();
deviceMACController.clear();
},
child: Text('Отказ'),
),
],
),
),
),
),
);
}

Future sendFormDataToApi(Map  formData) async {
final apiUrl = 'http://kvb-bg.com/Sirena/test_api_adding_devices.php';

try {
final response = await http.post(
Uri.parse(apiUrl),
body: formData,
);

if (response.statusCode == 200) {
// Handle the response if needed
} else {
throw Exception('Failed to add device');
}
} catch (e) {
throw Exception('Error: $e');
}
}
}

а вот код API на PHP:

Код: Выделить всё


Подробнее здесь: [url]https://stackoverflow.com/questions/78297729/how-to-send-json-array-filled-with-data-from-flutter-to-api-made-with-php[/url]
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Php»