【发布时间】:2019-09-07 18:18:57
【问题描述】:
我有这个颤振代码。
当我从下拉列表中选择新项目时,_selectedCurrency 的值会更新,但下拉按钮本身不会更新。显示的项目始终为 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;
});
},
);
}
}
但如果我在 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;
});
},
),
),
],
),
);
}
}
我正在努力使我的代码整洁,而不是在 build() 上创建所有内容。
在 initState() 上创建小部件是否正确?
谢谢
【问题讨论】: