【发布时间】:2019-01-05 03:55:45
【问题描述】:
例如,这是第一个下拉按钮 For Example This is the First Dropdown对不起,我没有足够的声誉来发布图片
标签所在的位置 选择区域 另一个将显示哪些城市将是城市 下面列出的取决于上面选择的区域。
【问题讨论】:
例如,这是第一个下拉按钮 For Example This is the First Dropdown对不起,我没有足够的声誉来发布图片
标签所在的位置 选择区域 另一个将显示哪些城市将是城市 下面列出的取决于上面选择的区域。
【问题讨论】:
每次调用setState 时,都会调用小部件的build 方法,并在需要时重建可视化树。因此,在DropdownButton 的onChanged 处理程序中,将选择保存在setState 中并有条件地添加第二个DropdownButton。这是一个工作示例(边缘可能有点粗糙:)):
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
String _selectedRegion;
String _selectedSecond;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text('Something before'),
DropdownButton<String>(
value: _selectedRegion,
items: ['Arizona', 'California']
.map((region) => DropdownMenuItem<String>(
child: Text(region), value: region))
.toList(),
onChanged: (newValue) {
setState(() {
_selectedRegion = newValue;
});
},
),
_addSecondDropdown(),
Text('Something after'),
],
),
),
);
}
Widget _addSecondDropdown() {
return _selectedRegion != null
? DropdownButton<String>(
value: _selectedSecond,
items: ['First', 'Second']
.map((region) => DropdownMenuItem<String>(
child: Text(region), value: region))
.toList(),
onChanged: (newValue) {
setState(() {
_selectedSecond = newValue;
});
})
: Container(); // Return an empty Container instead.
}
}
Luke Freeman 有一篇关于 Managing visibility in Flutter 的精彩博文,如果您需要更广泛/可重用的方式。
【讨论】:
onChanged 处理程序中,我会调用 setState 以在您获取数据时将 UI 更改为“忙碌”状态。网络调用完成后,再次调用 setState 将 UI 更改为最终状态。
build 方法中为该繁忙状态创建所需的 UI。网络调用完成后,调用setState并清除flag。