通常,你不僅想導航到新螢幕,還想向螢幕傳遞資料。例如,你可能想傳遞關於被點選專案的資訊。

記住:螢幕只是小部件。在這個例子中,建立一個 Todo 列表。當一個 Todo 被點選時,導航到一個新螢幕(小部件),該螢幕顯示關於該 Todo 的資訊。本指南使用以下步驟:

  1. 定義一個 Todo 類。
  2. 顯示一個 Todo 列表。
  3. 建立一個詳細資訊螢幕,可以顯示關於 Todo 的資訊。
  4. 導航並傳遞資料到詳細資訊螢幕。

1. 定義一個 Todo 類

#

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

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

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

2. 建立一個 Todo 列表

#

其次,顯示一個 Todo 列表。在這個例子中,生成 20 個 Todo 並使用 ListView 顯示它們。有關列表的更多資訊,請參閱使用列表指南。

生成 Todo 列表

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

使用 ListView 顯示 Todo 列表

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

到目前為止,一切順利。這將生成 20 個 Todo 並將它們顯示在 ListView 中。

3. 建立一個 Todo 螢幕來顯示列表

#

為此,我們建立一個 StatelessWidget。我們稱之為 TodosScreen。由於此頁面的內容在執行時不會改變,我們將在此小部件的範圍內要求 Todo 列表。

我們將 ListView.builder 作為我們返回給 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. 建立一個詳細資訊螢幕來顯示 Todo 的資訊

#

現在,建立第二個螢幕。螢幕的標題包含 Todo 的標題,螢幕的主體顯示描述。

由於詳細資訊螢幕是一個普通的 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,你就可以執行導航了。在這個例子中,當用戶點選列表中的一個 Todo 時,導航到 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),
      ),
    );
  }
}