Build a Todo App with Flutter(2)
If we want to pass the arguments using RoutingSettings, we need to extract the arguments and pass the arguments to the specific widget.
Extract the arguments
We will create a detail screen that extracts and displays the title and description from the Todo.
To access the Todo, use the ModalRoute.of() method. This method returns the current route with the arguments.
before:
classDetailScreenextendsStatelessWidget{ const DetailScreen({super.key, required this.todo}); final Todo todo; @override Widget build(BuildContext context) {return Scaffold( appBar: AppBar(title: Text(todo.title)), body: Padding( padding: const EdgeInsets.all(16), child: Text(todo.description), ), ); }}
after:
classDetailScreenextendsStatelessWidget{ const DetailScreen({super.key}); @override Widget build(BuildContext context) {final todo = ModalRoute.of(context)!.settings.arguments as Todo;return Scaffold( appBar: AppBar(title: Text(todo.title)), body: Padding( padding: const EdgeInsets.all(16), child: Text(todo.description), ), ); }}
Pass the arguments
When navigate to the DetailScreen when a user taps a ListTile widget using Navigator.push(), it will pass the arguments as part of the RouteSettings. The DetailScreen extracts these arguments.
before:
classTodosScreenextendsStatelessWidget{ const TodosScreen({super.key, required this.todos}); final List<Todo> todos; @override Widget build(BuildContext context) {return Scaffold( appBar: AppBar(title: const Text('Todos')), body: ListView.builder( itemCount: todos.length, itemBuilder: (context, index) {return ListTile( title: Text(todos[index].title), onTap: () { Navigator.push( context, MaterialPageRoute<void>( builder: (context) => DetailScreen(todo: todos[index]), ), ); }, ); }, ), ); }}
after:
classTodosScreenextendsStatelessWidget{ const TodosScreen({super.key, required this.todos}); final List<Todo> todos; @override Widget build(BuildContext context) {return Scaffold( appBar: AppBar(title: const Text('Todos')), body: ListView.builder( itemCount: todos.length, itemBuilder: (context, index) {return ListTile( title: Text(todos[index].title), onTap: () { Navigator.push( context, MaterialPageRoute<void>( builder: (context) => const DetailScreen(), settings: RouteSettings(arguments: todos[index]), ), ); }, ); }, ), ); }}
夜雨聆风