flutter中如何向服务器发送数据下拉值

hfyxw5xn  于 2023-04-07  发布在  Flutter
关注(0)|答案(2)|浏览(97)

我如何发送数据/值被丢弃到服务器/API,我想让它,但我找不到适当的文章/视频。

xfb7svmp

xfb7svmp1#

下面是一个示例应用程序,它可以做到这一点:

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'),
            ),
          ],
        ),
      ),
    );
  }
}

确保已在pubspec.yaml中添加了http

bmp9r5qi

bmp9r5qi2#

要在Flutter中将数据从下拉列表发送到服务器,您可以遵循以下一般步骤:创建一个DropdownButton小部件并定义其项目和值属性:

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(),
)

在定义DropdownButton的StatefulWidget中添加一个Button小部件。此按钮将用于将所选值发送到服务器:

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

实现sendValueToServer函数,该函数将使用一个网络库(如http)向服务器发送一个POST请求,其中包含所选的值:
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');
  }
}

此代码向URL https://example.com/send-value发送POST请求,其中包含所选值作为键值对。您可以将URL替换为服务器的实际URL,并根据需要调整键值对。

**注意:**http库要求您将http包添加到您的pubspec.yaml文件中,并以http的形式导入,同时需要处理网络调用过程中可能出现的错误和异常。

相关问题