gpt4 book ai didi

flutter - SimpleDialog 中的项目

转载 作者:IT王子 更新时间:2023-10-29 07:13:54 24 4
gpt4 key购买 nike

我创建了 SimpleDialog 和许多由数据列表生成的 SimpleDialogOptions ,是否可以检测到该 SimpleDialogOption 的索引?如果不是,我正在尝试在对话框中使用列表,但它只显示一个空对话框,那么我如何在对话框中使用列表?

最佳答案

我想到了两个办法1.Map和indexOf方法2.用简单的for循环

结果:

demo

代码:

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 ] "),
)
],
),
],
),
),
);
}
}

关于flutter - SimpleDialog 中的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50808326/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com