我正在制作一个书签应用程序,您可以添加标题和URL从一个对话框并列出在屏幕上.
我试图将对话框上两个文本字段的值传递到最后一个屏幕上的ListView,但未能成功.对话框上有两个文本字段(标题和URL),我想将这些文本传递给最后一个屏幕上的ListView.我试过用pop
的方法,但不起作用.有谁能帮帮我吗?
以下是全部代码.
main.dart个
void main() {
runApp(const BookmarkApp());
}
class BookmarkApp extends StatelessWidget {
const BookmarkApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Bookmark App',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.blue),
useMaterial3: true,
),
home: BookmarkListPage(text: '', url: '',),
);
}
}
class BookmarkListPage extends StatefulWidget {
BookmarkListPage({super.key, title, required this.text, required this.url});
String text;
String url;
final String title = 'Bookmark List';
@override
State<BookmarkListPage> createState() => _BookmarkListPageState();
}
class _BookmarkListPageState extends State<BookmarkListPage> {
List<String> bookmarkList = [];
List<String> bookmarkUrl = [];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.white,
title: Text(widget.title),
bottom: PreferredSize(
child: Container(
height: 1,
color: Colors.black,
),
preferredSize: Size.fromHeight(1),
),
),
body: ListView.builder(
itemCount: bookmarkList.length,
itemBuilder: (context, index) {
return Card(
child: ListTile(
title: Text(bookmarkList[index]),
subtitle: Text(bookmarkUrl[index]),
),
);
},
),
// show dialog to add a bookmark
floatingActionButton: FloatingActionButton(
shape: const CircleBorder(),
backgroundColor: Colors.blue,
onPressed: () async {
final newBookmarkList = await showDialog(
context: context,
builder: (_) {
return BookmarkDialog();
});
if (newBookmarkList != null) {
setState(() {
bookmarkList.add(newBookmarkList);
bookmarkUrl.add(newBookmarkList);
});
}
},
child: const Icon(
Icons.add,
color: Colors.white,
),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
dialog.dart个
class BookmarkDialog extends StatefulWidget {
const BookmarkDialog({super.key});
@override
BookMarkDialogState createState() => BookMarkDialogState();
}
class BookMarkDialogState extends State<BookmarkDialog> {
String bookmarkTitle = "";
String bookmarkUrl = "";
@override
Widget build(BuildContext context) {
return AlertDialog(
title: const Text('Add Bookmark'),
content: Column(
children: [
Text('Title'),
TextField(onChanged: (value) {
setState(() {
bookmarkTitle = value;
});
}),
Text('URL'),
TextField(
onChanged: (value) {
setState(() {
bookmarkUrl = value;
});
},
)
],
),
actions: <Widget>[
GestureDetector(
child: const Text('Cancel'),
onTap: () {
Navigator.pop(context);
},
),
GestureDetector(
child: const Text('Add'),
onTap: () {
Navigator.of(context).pop(bookmarkTitle);
},
)
],
);
}
}