简体   繁体   English

Flutter DropdownButton未由setState更新

[英]Flutter DropdownButton not updated by setState

I have this flutter code. 我有这个颤动的代码。 When I select new item from dropdown list, the value of _selectedCurrency is updated, but the dropdown button itself not updated. 当我从下拉列表中选择新项目时, _selectedCurrency的值会更新,但下拉按钮本身不会更新。 The item shown is always USD . 显示的项目始终是USD

import 'package:flutter/material.dart';

import 'coin_data.dart' as coinData;

class PriceScreen extends StatefulWidget {
  @override
  _PriceScreenState createState() => _PriceScreenState();
}

class _PriceScreenState extends State<PriceScreen> {
  String _selectedCurrency = "USD";
  DropdownButton _currencyDropdownButton;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Coin Ticker'),
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: <Widget>[
          Container(
            height: 150.0,
            alignment: Alignment.center,
            padding: EdgeInsets.only(bottom: 30.0),
            color: Colors.lightBlue,
            child: _currencyDropdownButton,
          ),
        ],
      ),
    );
  }

  @override
  void initState() {
    super.initState();

    _currencyDropdownButton = DropdownButton<String>(
      value: _selectedCurrency,
      items:
          coinData.currenciesList.map<DropdownMenuItem<String>>((String value) {
        return DropdownMenuItem<String>(
          value: value,
          child: Text(value),
        );
      }).toList(),
      onChanged: (value) {
        setState(() {
          _selectedCurrency = value;
        });
      },
    );
  }
}

But if I created the DropdownButton widget inside build() then everything works fine, like this 但是,如果我在build()创建了DropdownButton小部件,则一切正常,像这样

import 'package:flutter/material.dart';

import 'coin_data.dart' as coinData;

class PriceScreen extends StatefulWidget {
  @override
  _PriceScreenState createState() => _PriceScreenState();
}

class _PriceScreenState extends State<PriceScreen> {
  String _selectedCurrency = "USD";
  DropdownButton _currencyDropdownButton;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Coin Ticker'),
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: <Widget>[
          Container(
            height: 150.0,
            alignment: Alignment.center,
            padding: EdgeInsets.only(bottom: 30.0),
            color: Colors.lightBlue,
            child: DropdownButton<String>(
              value: _selectedCurrency,
              items: coinData.currenciesList
                  .map<DropdownMenuItem<String>>((String value) {
                return DropdownMenuItem<String>(
                  value: value,
                  child: Text(value),
                );
              }).toList(),
              onChanged: (value) {
                setState(() {
                  _selectedCurrency = value;
                });
              },
            ),
          ),
        ],
      ),
    );
  }
}

I'm trying to make my code neat, by not create everything on build() . 我试图通过不在build()上创建所有内容来使代码更简洁。
Is creating the widget on initState() is correct way in flutter? initState()上创建窗口小部件是正确的方法吗?

Thanks 谢谢

why would you want to put your widget inside initState() ? 您为什么要将小部件放在initState() in rebuild progress, only widgets inside build() will get updated but you created an immutable widget inside init. 在重建过程中,只有build()内部的小部件会被更新,但是您在init中创建了一个不可变的小部件。 I offer you using the provider package. 我提供给您使用provider包。 create a new StatelessWidget class and use ChangeNotifierProvider<String>() in root to rebuild your widget on every change. 创建一个新的StatelessWidget类,并在根目录中使用ChangeNotifierProvider<String>()来在每次更改时重新ChangeNotifierProvider<String>()窗口小部件。

No initState is called only once, while building, you can not change if you declare inside, it might possible with GlobalKey only.try with GlobalKey . 没有initState只调用一次,同时建设,如果声明中你不能改变,它可能可能的GlobalKey only.try与GlobalKey and when setState(); 以及何时setState(); , is called build method get update. ,称为构建方法获取更新。 so we have to put widget inside build method only. 因此我们只需要将小部件放入build方法中即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM