gpt4 book ai didi

dart - 如何在 onTap 中使用条件语句

转载 作者:IT王子 更新时间:2023-10-29 07:23:26 27 4
gpt4 key购买 nike

我对 dart 中的 if 语句有疑问,我希望用户点击城市转到新屏幕。这段代码工作得很好


class citySec extends StatelessWidget {
Widget getListView(BuildContext context) {
var listView = ListView(
children: <Widget>[
Text(
"choose ur city:",
textDirection: TextDirection.rtl,
textAlign: TextAlign.center,
),
ListTile(
leading: Icon(Icons.location_city),
title: Text("Toronto ", textDirection: TextDirection.rtl),

onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => TorontoUniversitySection(),
),
);
},
),
],
);
return listView;
}

@override
Widget build(BuildContext context) {
return Scaffold(body: getListView(context));
}
}

由于我有很长的城市列表,而以前的代码会使我的代码很长,所以我不得不更改我的代码。但是,我在 if 语句中遇到了一些错误,这是我目前所做的。


import 'package:flutter/material.dart';
import 'package:rate/screens/firstScreen.dart';

void main() {
runApp(MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Rate',
home: Scaffold(
appBar: AppBar(
title: Text("jgfnjfnj ", textDirection: TextDirection.rtl),
),
body: ListDisplay(),
),
));
}
class ListDisplay extends StatelessWidget {
List<String> litems = ["Toronto","NewYork","London","Riyadh","Dubai","Istanbul"];

@override
Widget build (BuildContext ctxt) {
return new Scaffold(
appBar: AppBar(title: Text("Please Choose your city: ", textDirection: TextDirection.ltr,),
),

body: new ListView.builder
(
itemCount: litems.length,

itemBuilder: (BuildContext ctxt, int index) {

return new ListTile(
leading: Icon(Icons.location_city),
title: Text(litems[index], textDirection: TextDirection.rtl),

onTap: () {
// begin of all IF statements

if (litems.contains("Totonto")){
Navigator.push(
ctxt,
MaterialPageRoute(

builder: (ctxt) => TorontoUniversitySection()
),
);

}
if (litems.contains("London")){
Navigator.push(
ctxt,
MaterialPageRoute(

builder: (ctxt) => LondonUniversitySection()
),
);

}

// end of all If statements

},
);

}
)
);
}
}

最佳答案

for example, when I press Toronto it will take me to LondonUniversitySection()

那是因为在您的 if 语句中,您检查您的列表是否包含 Toronto/London 而不是当前按下的是 Toronto/London。将 litems.contains("x") 更改为 litems[index] == "x" 即可。这是经过编辑的片段:

    return new ListTile(
leading: Icon(Icons.location_city),
title: Text(litems[index], textDirection: TextDirection.rtl),
onTap: () {
if (litems[index] == "Toronto") {
Navigator.push(
ctxt,
MaterialPageRoute(builder: (ctxt) => TorontoUniversitySection()),
);
} else if (litems[index] == "London") {
Navigator.push(
ctxt,
MaterialPageRoute(builder: (ctxt) => LondonUniversitySection()));
}
},
);

此外,我建议为此使用 switchelse-if,而不是一堆 ifs。

关于dart - 如何在 onTap 中使用条件语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54348646/

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