Flutter: выпадающее значение не выбирается - PullRequest
0 голосов
/ 27 января 2020

Я занимаюсь разработкой приложения с dropdown. Ниже мой код. Я удалил код дизайна пользовательского интерфейса, чтобы изолировать сам раздел dropdown.

class ShoppingCartUIState extends State<ShoppingCartUI> {
  final _formKey = GlobalKey<FormState>();
  String _checkoutDropdownValue=null;

//**UI design Code Removed**//

  _showCheckoutPopup() {
    String date=DateTime.now().toString();


    return Dialog(
        shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(20.0)), //this right here
        child: Container(
          height: MediaQuery.of(context).size.height/3,
          child: Column(

            children: <Widget>[
              Row(
                children: <Widget>[
                  Container(
                    margin: EdgeInsets.all(10),
                    child: Text(
                    "What is Your Required Delivery Date?",
                    style: Theme.of(context).textTheme.subtitle,
                  ),)

                ],
              ),
              Row(
                children: <Widget>[
                  IconButton(
                    icon: Icon(Icons.calendar_today),
                    color: Colors.green,
                    onPressed: () {
                      date = "111";
                    },
                  ),
                  Text(date)
                ],
              ),
              Row(
                children: <Widget>[
                  Container(
                    margin: EdgeInsets.only(top:20, left:10),
                    child: Text(
                    "What is your Airport of delivery?",
                    style: Theme.of(context).textTheme.subtitle,
                  ),)

                ],
              ),
              Row(
                children: <Widget>[
                  Container(
                    margin: EdgeInsets.only(top:5, left:10),
                    child: DropdownButton(
                    hint: Text(
                      "Please Select          ",
                      style: TextStyle(
                        fontSize: 14,
                      ),
                    ),
                    items: <String>[
                      'Skinless Boneless, Full Loins',
                      'brown',
                      'silver'
                    ].map((data) {
                      return DropdownMenuItem(
                        child: new Text(data,
                            style: Theme.of(context).textTheme.body1),
                        value: data,
                      );
                    }).toList(),
                    onChanged: (String newValue) {
                      setState(() {
                        _checkoutDropdownValue = newValue;
                        print(newValue);
                      });
                    },
                    value: _checkoutDropdownValue),
                    )

                ],
              ),
            ],
          ),
        ));
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }
}

Проблема заключается в том, что при изменении выпадающего элемента новое значение никогда не выбирается. Ранее выбранное значение всегда отображается. Однако, так как я использую print, когда выпадающий список готов, я вижу, что элемент изменился.

Как я могу решить эту проблему?

Ответы [ 2 ]

1 голос
/ 27 января 2020

Оберните ваш Dialog виджет с помощью StatefulBuilder, чтобы перестроить диалоговое окно.

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyPage(), //TODO: Add Scaffold
    );
  }
}

class MyPage extends StatefulWidget {
  @override
  _MyPageState createState() => _MyPageState();
}

class _MyPageState extends State<MyPage> {
  String date = "";
  String _checkoutDropdownValue;

  _showCheckoutPopup() {
    return StatefulBuilder(
      builder: (context, setState){
        return Dialog(
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(20.0),
          ), //this r// ight here
          child: Padding(
            padding: const EdgeInsets.all(8.0),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                Container(
                  margin: EdgeInsets.all(10),
                  alignment: Alignment.centerLeft,
                  child: Text(
                    "What is Your Required Delivery Date?",
                    style: Theme.of(context).textTheme.subtitle,
                  ),
                ),
                Row(
                  children: <Widget>[
                    IconButton(
                      icon: Icon(Icons.calendar_today),
                      color: Colors.green,
                      onPressed: () {
                        setState(() {
                          date = "111";
                        });
                      },
                    ),
                    Text(date)
                  ],
                ),
                Container(
                  margin: EdgeInsets.only(top: 20, left: 10),
                  alignment: Alignment.centerLeft,
                  child: Text(
                    "What is your Airport of delivery?",
                    style: Theme.of(context).textTheme.subtitle,
                  ),
                ),
                Row(
                  children: <Widget>[
                    Container(
                      margin: EdgeInsets.only(top: 5, left: 10),
                      child: DropdownButton<String>(
                        hint: Text(
                          "Please Select          ",
                          style: TextStyle(
                            fontSize: 14,
                          ),
                        ),
                        items: <String>[
                          'Skinless Boneless, Full Loins',
                          'brown',
                          'silver'
                        ].map((data) {
                          return DropdownMenuItem(
                            child: new Text(data,
                                style: Theme.of(context).textTheme.body1),
                            value: data,
                          );
                        }).toList(),
                        onChanged: (String newValue) {
                          setState(() {
                            _checkoutDropdownValue = newValue;
                          });
                        },
                        value: _checkoutDropdownValue,
                      ),
                    )
                  ],
                ),
              ],
            ),
          ),
        );
      },

    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: RaisedButton(
          child: Text("Click Here"),
          onPressed: () {
            showDialog(
              context: context,
              builder: (context) => _showCheckoutPopup(),
            );
          },
        ),
      ),
    );
  }
}
0 голосов
/ 27 января 2020

можете ли вы изменить свой onPressed для печати (_checkoutDropdownValue); вместо print (newValue); таким образом, мы можем видеть, есть ли проблема с назначением

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...