dda*_*ang 2 flutter flutter-layout
我创建了 SimpleDialog 和许多由数据列表生成的 SimpleDialogOptions,是否可以检测到 SimpleDialogOption 的索引?如果没有,我正在尝试在对话框中使用列表,但它只是显示一个空对话框,那么我如何在对话框中使用列表?
我可以想到两种方法 1.Map 和 indexOf 方法 2.使用简单的 for 循环
结果:
编码:
import 'dart:async';
import 'package:flutter/material.dart';
void main() => runApp(
new MaterialApp(
home: new MyApp(),
),
);
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => new _MyAppState();
}
class _MyAppState extends State<MyApp> {
int index = 0;
List<String> myList = new List();
@override
void initState() {
super.initState();
/*Adding elements to data list*/
for (int i = 0; i < 5; i++) myList.add("Title $i");
}
/*First Way*/
Future<Null> _showList1() async {
int selected = await showDialog<int>(
context: context,
builder: (BuildContext context) {
return new SimpleDialog(
title: const Text('Select'),
children: myList.map((value) {
return new SimpleDialogOption(
onPressed: () {
Navigator.pop(context, myList.indexOf(value));//here passing the index to be return on item selection
},
child: new Text(value),//item value
);
}).toList(),
);
});
setState(() {
index = selected;
});
}
/*Second Way*/
Future<Null> _showList2() async {
int selected = await showDialog<int>(
context: context,
builder: (BuildContext context) {
return new SimpleDialog(
title: const Text('Select'),
children: getOption(),
);
});
setState(() {
index = selected;
});
}
List<Widget> getOption() {
List<Widget> options = new List();
for (int i = 0; i < myList.length; i++)
options.add(new SimpleDialogOption(
onPressed: () {
Navigator.pop(context, i);//here passing the index to be return on item selection
},
child: new Text(myList[i]),//item value
));
return options;
}
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text("NonStopIO"),
),
body: new Center(
child: new Column(
children: <Widget>[
new Padding(
padding: const EdgeInsets.all(100.0),
),
new Text(
"Selected Index : $index",
style: new TextStyle(fontSize: 30.0),
),
new Padding(
padding: const EdgeInsets.all(18.0),
),
new Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
new RaisedButton(
onPressed: () async {
_showList1();
},
child: new Text("Show List [ First Way ] "),
),
new RaisedButton(
onPressed: () async {
_showList2();
},
child: new Text("Show List [ Second Way ] "),
)
],
),
],
),
),
);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2653 次 |
| 最近记录: |