跳到主內容

向新螢幕傳送資料

如何將資料傳遞到新路由。

通常,你不僅想導航到新螢幕,還想將資料傳遞到螢幕上。例如,你可能想傳遞被點選的條目的資訊。

請記住:螢幕只是小部件。在這個例子中,建立一個待辦事項列表。當點選一個待辦事項時,導航到一個新螢幕(小部件),該螢幕顯示關於該待辦事項的資訊。此配方使用以下步驟

  1. 定義一個待辦事項類。
  2. 顯示一個待辦事項列表。
  3. 建立一個可以顯示待辦事項資訊的詳情螢幕。
  4. 導航並向詳情螢幕傳遞資料。

1. 定義一個待辦事項類

#

首先,你需要一種簡單的方法來表示待辦事項。在這個例子中,建立一個包含兩個資料片段的類:標題和描述。

dart
class Todo {
  final String title;
  final String description;

  const Todo(this.title, this.description);
}

2. 建立一個待辦事項列表

#

其次,顯示一個待辦事項列表。在這個例子中,生成 20 個待辦事項並使用 ListView 顯示它們。有關使用列表的更多資訊,請參閱 使用列表 配方。

生成待辦事項列表

#
dart
final todos = List.generate(
  20,
  (i) => Todo(
    'Todo $i',
    'A description of what needs to be done for Todo $i',
  ),
);

使用 ListView 顯示待辦事項列表

#
dart
ListView.builder(
  itemCount: todos.length,
  itemBuilder: (context, index) {
    return ListTile(title: Text(todos[index].title));
  },
)

到目前為止,一切順利。這生成了 20 個待辦事項並在 ListView 中顯示它們。

3. 建立一個待辦事項螢幕來顯示列表

#

為此,我們建立一個 StatelessWidget。我們稱它為 TodosScreen。由於此頁面的內容在執行時不會更改,因此我們必須在小部件的範圍內需要待辦事項列表。

我們將 ListView.builder 作為要返回的小部件的 body 傳遞給 build()。這將把列表渲染到螢幕上,讓你開始使用!

dart
class TodosScreen extends StatelessWidget {
  // Requiring the list of todos.
  const TodosScreen({super.key, required this.todos});

  final List<Todo> todos;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Todos')),
      //passing in the ListView.builder
      body: ListView.builder(
        itemCount: todos.length,
        itemBuilder: (context, index) {
          return ListTile(title: Text(todos[index].title));
        },
      ),
    );
  }
}

使用 Flutter 的預設樣式,你無需擔心稍後想要做的事情即可順利進行!

4. 建立一個詳情螢幕來顯示待辦事項的資訊

#

現在,建立第二個螢幕。螢幕的標題包含待辦事項的標題,螢幕的 body 顯示描述。

由於詳情螢幕是一個普通的 StatelessWidget,請要求使用者在 UI 中輸入一個 Todo。然後,使用給定的 todo 構建 UI。

dart
class DetailScreen extends StatelessWidget {
  // In the constructor, require a Todo.
  const DetailScreen({super.key, required this.todo});

  // Declare a field that holds the Todo.
  final Todo todo;

  @override
  Widget build(BuildContext context) {
    // Use the Todo to create the UI.
    return Scaffold(
      appBar: AppBar(title: Text(todo.title)),
      body: Padding(
        padding: const EdgeInsets.all(16),
        child: Text(todo.description),
      ),
    );
  }
}

5. 導航並向詳情螢幕傳遞資料

#

有了 DetailScreen 之後,你就可以執行導航了。在這個例子中,當用戶點選列表中的待辦事項時,導航到 DetailScreen。將 todo 傳遞給 DetailScreen

要在 TodosScreen 中捕獲使用者的點選,為 ListTile 小部件編寫一個 onTap() 回撥函式。在 onTap() 回撥函式中,使用 Navigator.push() 方法。

dart
body: ListView.builder(
  itemCount: todos.length,
  itemBuilder: (context, index) {
    return ListTile(
      title: Text(todos[index].title),
      // When a user taps the ListTile, navigate to the DetailScreen.
      // Notice that you're not only creating a DetailScreen, you're
      // also passing the current todo through to it.
      onTap: () {
        Navigator.push(
          context,
          MaterialPageRoute<void>(
            builder: (context) => DetailScreen(todo: todos[index]),
          ),
        );
      },
    );
  },
),

互動示例

#
import 'package:flutter/material.dart';

class Todo {
  final String title;
  final String description;

  const Todo(this.title, this.description);
}

void main() {
  runApp(
    MaterialApp(
      title: 'Passing Data',
      home: TodosScreen(
        todos: List.generate(
          20,
          (i) => Todo(
            'Todo $i',
            'A description of what needs to be done for Todo $i',
          ),
        ),
      ),
    ),
  );
}

class TodosScreen extends StatelessWidget {
  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),
            // When a user taps the ListTile, navigate to the DetailScreen.
            // Notice that you're not only creating a DetailScreen, you're
            // also passing the current todo through to it.
            onTap: () {
              Navigator.push(
                context,
                MaterialPageRoute<void>(
                  builder: (context) => DetailScreen(todo: todos[index]),
                ),
              );
            },
          );
        },
      ),
    );
  }
}

class DetailScreen extends StatelessWidget {
  // In the constructor, require a Todo.
  const DetailScreen({super.key, required this.todo});

  // Declare a field that holds the Todo.
  final Todo todo;

  @override
  Widget build(BuildContext context) {
    // Use the Todo to create the UI.
    return Scaffold(
      appBar: AppBar(title: Text(todo.title)),
      body: Padding(
        padding: const EdgeInsets.all(16),
        child: Text(todo.description),
      ),
    );
  }
}

或者,使用 RouteSettings 傳遞引數

#

重複前兩個步驟。

建立一個詳情螢幕來提取引數

#

接下來,建立一個詳情螢幕,該螢幕提取並顯示來自 Todo 的標題和描述。要訪問 Todo,請使用 ModalRoute.of() 方法。此方法返回當前路由及其引數。

dart
class DetailScreen extends StatelessWidget {
  const DetailScreen({super.key});

  @override
  Widget build(BuildContext context) {
    final todo = ModalRoute.of(context)!.settings.arguments as Todo;

    // Use the Todo to create the UI.
    return Scaffold(
      appBar: AppBar(title: Text(todo.title)),
      body: Padding(
        padding: const EdgeInsets.all(16),
        child: Text(todo.description),
      ),
    );
  }
}
#

最後,當用戶點選 ListTile 小部件時,使用 Navigator.push() 導航到 DetailScreen。將引數作為 RouteSettings 的一部分傳遞。DetailScreen 提取這些引數。

dart
ListView.builder(
  itemCount: todos.length,
  itemBuilder: (context, index) {
    return ListTile(
      title: Text(todos[index].title),
      // When a user taps the ListTile, navigate to the DetailScreen.
      // Notice that you're not only creating a DetailScreen, you're
      // also passing the current todo through to it.
      onTap: () {
        Navigator.push(
          context,
          MaterialPageRoute<void>(
            builder: (context) => const DetailScreen(),
            // Pass the arguments as part of the RouteSettings. The
            // DetailScreen reads the arguments from these settings.
            settings: RouteSettings(arguments: todos[index]),
          ),
        );
      },
    );
  },
)

完整示例

#
dart
import 'package:flutter/material.dart';

class Todo {
  final String title;
  final String description;

  const Todo(this.title, this.description);
}

void main() {
  runApp(
    MaterialApp(
      title: 'Passing Data',
      home: TodosScreen(
        todos: List.generate(
          20,
          (i) => Todo(
            'Todo $i',
            'A description of what needs to be done for Todo $i',
          ),
        ),
      ),
    ),
  );
}

class TodosScreen extends StatelessWidget {
  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),
            // When a user taps the ListTile, navigate to the DetailScreen.
            // Notice that you're not only creating a DetailScreen, you're
            // also passing the current todo through to it.
            onTap: () {
              Navigator.push(
                context,
                MaterialPageRoute<void>(
                  builder: (context) => const DetailScreen(),
                  // Pass the arguments as part of the RouteSettings. The
                  // DetailScreen reads the arguments from these settings.
                  settings: RouteSettings(arguments: todos[index]),
                ),
              );
            },
          );
        },
      ),
    );
  }
}

class DetailScreen extends StatelessWidget {
  const DetailScreen({super.key});

  @override
  Widget build(BuildContext context) {
    final todo = ModalRoute.of(context)!.settings.arguments as Todo;

    // Use the Todo to create the UI.
    return Scaffold(
      appBar: AppBar(title: Text(todo.title)),
      body: Padding(
        padding: const EdgeInsets.all(16),
        child: Text(todo.description),
      ),
    );
  }
}