我正在尝试导航到名为contactView的页面。我已经列出了联系人列表,并且当我单击那里的名称时,我等待导航到该联系人。到目前为止,这就是我所拥有的。我一直在努力使导航正常工作。任何帮助都会很棒。
class ContactList extends StatelessWidget {
final List<Contact> _contacts;
ContactList(this._contacts);
@override
Widget build(BuildContext context) {
return new ListView.builder(
padding: new EdgeInsets.symmetric(vertical: 8.0),
itemBuilder: (context, index) {
return new _ContactListItem(_contacts[index]);
Navigator.push(context, MaterialPageRoute(builder: (context) => viewContact())
);
},
itemCount: _contacts.length,
);
}
}
答案 0 :(得分:1)
以下是我可以立即指出的几件事(问题):
onPressed
在ListView.builder()
上不可用,您可以检查
这里:
https://docs.flutter.io/flutter/widgets/ListView/ListView.builder.html Navigator.push(context, MaterialPageRoute(builder: (context) => viewContact())
不会执行,因为它是在return
之后建议:
_ContactListItem()
包装在
GestureDetector
并实现onTap
回调示例代码:
class ContactList extends StatelessWidget {
final List<Contact> _contacts;
ContactList(this._contacts);
@override
Widget build(BuildContext context) {
return ListView.builder(
padding: EdgeInsets.symmetric(vertical: 8.0),
itemBuilder: (context, index) {
return GestureDetector(
onTap: () {
//TODO: Insert your navigation logic here
Navigator.of(context).push(MaterialPageRoute(
builder: (BuildContext context) =>
ContactView(_contacts[index])));
},
child: _ContactListItem(_contacts[index]),
);
},
itemCount: _contacts.length,
);
}
}
_ContactListItem()
,并且可以使用ListTile
并在onTap
中实现ListTile
,您可以在这里找到它:https://docs.flutter.io/flutter/material/ListTile-class.html 我希望这在某种程度上有帮助,如果我误解了问题,请告诉我。
答案 1 :(得分:0)
看看下面是否是您想要的。
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Contact Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Contact Demo'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final _contacts = [
Contact(name: 'John'),
Contact(name: 'Mary'),
Contact(name: 'Suzy')
];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
leading: null,
title: const Text(
'Contact Demo',
style: const TextStyle(color: Colors.white),
),
),
body: ListView.builder(
itemCount: _contacts.length,
itemBuilder: (BuildContext context, int index) {
return ListTile(
title: Text('Contact #$index'),
onTap: () {
Navigator.of(context).push(MaterialPageRoute<void>(
builder: (BuildContext context) =>
ContactView(contact: _contacts[index]),
));
},
);
},
),
);
}
}
class Contact {
Contact({this.name});
final String name;
}
class ContactView extends StatelessWidget {
ContactView({this.contact});
final Contact contact;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(contact.name),
),
body: Center(
child: Text(contact.name),
),
);
}
}