从Flutter中的DropDownButton捕获数据并将其发送到数据库

时间:2020-07-07 16:54:15

标签: flutter

我不熟悉应用程序开发,想寻求您的帮助

我已经学会了捕获TextFormField的数据,但是使用DropDownButtons我不知道它是如何尝试使用控制器来输入名称的,但是出现错误

我有一个DropDownButton,它对我有用,它正在成功加载列表,我想知道如何捕获在DropDownButton中选择的数据并将其发送到我的数据库

这是我正在使用的代码:

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

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key}) : super(key: key);

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  String _mySelection;
  final String url = "http://webmyls.com/php/getdata.php";
  List data = List();

  Future<String> getSWData() async {
    var res = await http
        .get(Uri.encodeFull(url), headers: {"Accept": "application/json"});
    var resBody = json.decode(res.body);
    setState(() {
      data = resBody;
    });

    print(data);
    return "Sucess";
  }

  @override
  void initState() {
    super.initState();
    this.getSWData();
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      body: new Center(
        child: new DropdownButton(
          //data != null,
          isDense: true,
          hint: new Text("Select"),
          items: data.map((item) {
            return new DropdownMenuItem(
              child: new Text(item['item_name']),
              value: item['id'].toString(),
            );
          }).toList(),
          onChanged: (newVal) {
            setState(() {
              _mySelection = newVal;
            });
          },
          value: _mySelection,
        ),
      ),
    );
  }
}

希望您能帮助我。

1 个答案:

答案 0 :(得分:0)

最新的下拉值始终存储在您的_mySelection中。因此,您唯一要做的就是将_mySelection保存在数据库中。