Flutter page returns data transfer

Problem Description

After jumping from page A to page B, after the operation on page B, return some data to page A when exiting page B and returning to page A

Jump under page A

ElevatedButton(
    child: const Text("载入设置"),
    onPressed: () {
    
    
        // List<Task>  data = await _dbProvider.getAll();
        _dbProvider.getAll().then((value) => {
    
    
        // 跳转到新页面
        Navigator.push(context, MaterialPageRoute(builder: (context) {
    
    
        return TaskListPage(value,(index){
    
    
            // Navigator.push(context, ...) // 根据 index 跳转
            print("index=$index");
        }); // 传入 Task 列表
        }))
        });
    },
),

new page

// 新页面
class TaskListPage extends StatelessWidget {
    
    
  final List<Task> tasks;

  // TaskListPage(this.tasks);
  TaskListPage(this.tasks, this.onTaskTap);

  final Function onTaskTap;

  
  Widget build(BuildContext context) {
    
    
    // 根据 Task 数量动态生成 ElevatedButton
    List<Widget> buttons = tasks.map((task) {
    
    
      return ElevatedButton(
          style: ElevatedButton.styleFrom(
            backgroundColor: Colors.blue,
            shape: CircleBorder(),
          ),
          child: Column(
              mainAxisAlignment: MainAxisAlignment.center, //居中对齐
              children: [
                Icon(Icons.people),
                Text(task.title)
              ]
          ),
          onPressed: () {
    
    
            // 点击事件
            onTaskTap(tasks.indexOf(task));
            Navigator.of(context).pop();
          }
      );
    }).toList();

    // 使用 GridView 实现网格布局
    return Scaffold(
        body: GridView.count(
            crossAxisCount: 3,
            children: buttons,
            padding: EdgeInsets.fromLTRB(10,40,20,10), // 添加 20 的内边距
            // padding: EdgeInsets.symmetric(horizontal: 20),
            crossAxisSpacing: 20 ,     // 设置行列间距为 20
        )
    );
  }
}

Description of main steps

1. In page B, add the constructor TaskListPage(this.tasks, this.onTaskTap);
final Function onTaskTap to the TaskListPage class;
2. When page A jumps to page B, pass in the variable to receive data

        return TaskListPage(value,(index){
    
    
            // Navigator.push(context, ...) // 根据 index 跳转
            print("index=$index");
        }); // 传入 Task 列表

result

After clicking on the data read from the database on page B, it will return to inform page A, which number is clicked
image.png

This is just a simple way. It is recommended to use Provider. Provider is a state management solution officially recommended by Flutter. It is mainly used to transfer data in the Widget tree.

Guess you like

Origin blog.csdn.net/yikezhuixun/article/details/130586034