flutter - 按钮单击添加从 API 获取的下拉小部件

标签 flutter flutter-layout

我的目标是: 我单击添加按钮,然后添加下拉按钮,它的项目是从 API 获取的。

这是我的问题:
我选择下拉值,但未选择任何值
我单击添加按钮,然后在新添加的下拉按钮上填充以前的值。

这是我的代码(完整)

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

class RepeatableSection extends StatefulWidget {
  @override
  _RepeatableSectionState createState() => _RepeatableSectionState();
}

class _RepeatableSectionState extends State<RepeatableSection> {
  List<Widget> extractedChildren = <Widget>[];
  int _index = 1;

  String _mySelection;
  List data = List();

  Future<void> fetchAPI() async {
    var url = "http://webmyls.com/php/getdata.php";
    Map<String, String> headers = {
      'Content-type': 'application/json',
      'Accept': 'application/json',
    };
    final response = await http.post(url, headers: headers);
    final responseJson = json.decode(response.body);

    if (response.statusCode == 200) {
      setState(() {
        data = responseJson;
      });
    } else {
      setState(() {});
      throw Exception('Failed to load internet');
    }
  }

  @override
  void initState() {
    this.fetchAPI();
  }

  Widget build(BuildContext context) {
    return Column(
      children: [
        Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: extractedChildren,
        ),
        RaisedButton(
          child: Text('Add'),
          onPressed: () {
            add();
          },
        ),
      ],
    );
  }

  void add() {
    int keyValue = _index;
    extractedChildren = List.from(extractedChildren)
      ..add(Column(
        key: Key("$keyValue"),
        children: <Widget>[
          Text(keyValue.toString()),
          DropdownButton(
            hint: Text('Choose..'),
            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,
          ),
        ],
      ));
    setState(() => ++_index);
  }
}

最佳答案

要为每个下拉按钮存储值,您必须创建一个可以存储的字符串列表。

下面的代码可以帮助您更好地理解。

class RepeatableSection extends StatefulWidget {
  @override
  _RepeatableSectionState createState() => _RepeatableSectionState();
}

class _RepeatableSectionState extends State<RepeatableSection> {
  Widget extractedChildren;
  int _index = 0;

  List<String> _mySelection = [];
  List data = List();

  Future<void> fetchAPI() async {
    var url = "http://webmyls.com/php/getdata.php";
    Map<String, String> headers = {
      'Content-type': 'application/json',
      'Accept': 'application/json',
    };
    final response = await http.post(url, headers: headers);
    final responseJson = json.decode(response.body);

    print(data);
    if (response.statusCode == 200) {
      setState(() {
        data = responseJson;
      });
    } else {
      setState(() {});
      throw Exception('Failed to load internet');
    }
  }

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

  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Expanded(
                    child: _index > 0
                        ? ListView.builder(
                            itemCount: _index,
                            shrinkWrap: true,
                            itemBuilder: (_, index) {
                              return Column(
                                key: Key("$index"),
                                children: <Widget>[
                                  Text(index.toString()),
                                  DropdownButton(
                                    hint: Text('Choose..'),
                                    items: data.map((item) {
                                      return new DropdownMenuItem(
                                        child: new Text(item['item_name']),
                                        value: item['id'].toString(),
                                      );
                                    }).toList(),
                                    onChanged: (newVal) {
                                      setState(() {
                                        print("object");
                                        _mySelection[index] = newVal;
                                      });
                                    },
                                    value: _mySelection[index],
                                  ),
                                ],
                              );
                            },
                          )
                        : Container())
              ],
            ),
          ),
          RaisedButton(
            child: Text('Add'),
            onPressed: () {
              setState(() {
                _index++;
                _mySelection.add(null);
              });
              // add();
            },
          ),
        ],
      ),
    );
  }
}

关于flutter - 按钮单击添加从 API 获取的下拉小部件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61666467/

相关文章:

Flutter 响应式文本字段匹配屏幕尺寸

flutter - 静态谷歌地图(禁用所有手势)

dart - 如何使抖动小部件适应不同的屏幕尺寸

flutter - 为什么我的复选框不起作用?即使设置了setState

flutter - FLUTTER隐藏式叠加菜单

flutter - 按 iOS 模拟器键盘上的输入/返回按钮不会存储 TextField onChanged 数据 为什么?

flutter - 如何在 Flutter 中的 IconButton 上添加 tintColor?

flutter - 我如何在 Flutter 中设计这样的布局背景?

flutter - 如何在 flutter 中扫描文档

dart - 使用 Swift 和 Kotlin 重新创建 Flutter 的 ios 和 android 文件夹