skip to Main Content

how do I send data/values that are dropped to the server/API, I want to make it but I can’t find the appropriate article/video.

2

Answers


  1. Here’s an example app that does just that:

    import 'dart:convert';
    
    import 'package:flutter/material.dart';
    import 'package:http/http.dart' as http;
    
    void main() => runApp(MyApp());
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'Dropdown Example',
          theme: ThemeData(
            primarySwatch: Colors.blue,
          ),
          home: MyHomePage(title: 'Dropdown Example Home Page'),
        );
      }
    }
    
    class MyHomePage extends StatefulWidget {
      MyHomePage({Key? key, required this.title}) : super(key: key);
    
      final String title;
    
      @override
      _MyHomePageState createState() => _MyHomePageState();
    }
    
    class _MyHomePageState extends State<MyHomePage> {
      String _dropdownValue = 'Select an option';
    
      Future<void> sendDataToServer() async {
        // set up the request
        var url = 'https://your-server-url.com/api';
        var headers = {'Content-Type': 'application/json'}; 
        var data = _dropdownValue;
        var body = jsonEncode(data); // configure this based on your payload structure
    
        // make the request
        var response = await http.post(
          Uri.parse(url),
          headers: headers,
          body: body,
        );
    
        // handle the response
        if (response.statusCode == 200) {
          print('Data sent successfully!');
        } else {
          print('Error sending data: ${response.statusCode}');
        }
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text(widget.title),
          ),
          body: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                DropdownButton<String>(
                  value: _dropdownValue,
                  onChanged: (String? newValue) {
                    setState(() {
                      _dropdownValue = newValue!;
                    });
                  },
                  items: <String>['Option 1', 'Option 2', 'Option 3']
                      .map<DropdownMenuItem<String>>((String value) {
                    return DropdownMenuItem<String>(
                      value: value,
                      child: Text(value),
                    );
                  }).toList(),
                ),
                ElevatedButton(
                  onPressed: () {
                    sendDataToServer();
                  },
                  child: Text('Send Data to Server'),
                ),
              ],
            ),
          ),
        );
      }
    }
    

    Ensure that you have added http package in your pubspec.yaml

    Login or Signup to reply.
  2. To send data from a dropdown value to a server in Flutter, you can follow these general steps:
    Create a DropdownButton widget and define its items and value properties:

    String dropdownValue = 'Item 1';
    
    DropdownButton<String>(
      value: dropdownValue,
      onChanged: (String newValue) {
        setState(() {
          dropdownValue = newValue;
        });
      },
      items: <String>['Item 1', 'Item 2', 'Item 3', 'Item 4']
          .map<DropdownMenuItem<String>>((String value) {
        return DropdownMenuItem<String>(
          value: value,
          child: Text(value),
        );
      }).toList(),
    )
    

    Add a Button widget to the same StatefulWidget where you defined the DropdownButton. This button will be used to send the selected value to the server:

    TextButton(
      onPressed: () {
        sendValueToServer(dropdownValue);
      },
      child: Text('Send Value'),
    ),
    

    Implement the sendValueToServer function, which will use a network library such as http to send a POST request to the server with the selected value:

    import ‘package:http/http.dart’ as http;

    Future<void> sendValueToServer(String value) async {
      final response = await http.post(
        Uri.parse('https://example.com/send-value'),
        body: {'value': value},
      );
    
      if (response.statusCode == 200) {
        print('Value sent successfully');
      } else {
        print('Failed to send value');
      }
    }
    

    This code sends a POST request to the URL https://example.com/send-value with a body containing the selected value as a key-value pair. You can replace the URL with the actual URL of your server, and adjust the key-value pair as needed.

    Note: that the http library requires you to add the http package to your pubspec.yaml file, and import it as http. Also, you should handle errors and exceptions that might occur during the network call.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search