Нажмите кнопку Добавить раскрывающийся виджет, извлекаемый из API - PullRequest
1 голос
/ 07 мая 2020

Моя цель - это Gere: я нажимаю кнопку добавления, затем добавляю кнопку раскрывающегося списка, элемент которой извлекается из 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);
  }
}

1 Ответ

0 голосов
/ 08 мая 2020

Чтобы сохранить значение для каждой раскрывающейся кнопки, вы должны создать список String, в котором вы можете хранить.

Следующий код поможет вам понять больше.

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