Flutter学习 — 从新页面返回数据给上一个页面

效果图一:

点击按钮
Flutter学习 — 从新页面返回数据给上一个页面_第1张图片

效果图二:

点击YES后,返回上一级页面并传值

Flutter学习 — 从新页面返回数据给上一个页面_第2张图片

效果图三:

收到值,并用底部弹出框显示结果
Flutter学习 — 从新页面返回数据给上一个页面_第3张图片

注释+代码:

import 'package:flutter/material.dart';

void main() {
  runApp(new MaterialApp(
    title: 'Returning Data',
    home: new HomeScreen(),
  ));
}

class HomeScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text('Returning Data Demo'),
      ),
      body: new Center(child: new SelectionButton()),
    );
  }
}

class SelectionButton extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new RaisedButton(
      onPressed: () {
        _navigateAndDisplaySelection(context);
      },
      child: new Text('Pick an option, any option!'),
    );
  }

  // A method that launches the SelectionScreen and awaits the result from
  // Navigator.pop!
  /**
   * 一种启动SelectionScreen并等待以下结果的方法 Navigator.pop!
   */
  _navigateAndDisplaySelection(BuildContext context) async {
    // Navigator.push returns a Future that will complete after we call
    // Navigator.pop on the Selection Screen!
    /**
     * Navigator.push返回一个Future,它将在我们调用后完成选择屏幕上的Navigator.pop!
     */
    final result = await Navigator.push(
      context,
      new MaterialPageRoute(builder: (context) => new SelectionScreen()),
    );

    // After the Selection Screen returns a result, show it in a Snackbar!
    ///选择屏幕返回结果后,将其显示在小吃栏中!
    Scaffold
        .of(context)
        .showSnackBar(new SnackBar(content: new Text("$result")));
  }
}

class SelectionScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text('Pick an option'),
      ),
      body: new Center(
        child: new Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            new Padding(
              padding: const EdgeInsets.all(8.0),
              child: new RaisedButton(
                onPressed: () {
                  // Close the screen and return "Yep!" as the result
                  /// 关闭屏幕并返回“是!” 作为结果
                  Navigator.pop(context, 'Yep!');
                },
                child: new Text('Yep!'),
              ),
            ),
            new Padding(
              padding: const EdgeInsets.all(8.0),
              child: new RaisedButton(
                onPressed: () {
                  // Close the screen and return "Nope!" as the result
                  /// 关闭屏幕并返回“不!” 作为结果
                  Navigator.pop(context, 'Nope.');
                },
                child: new Text('Nope.'),
              ),
            )
          ],
        ),
      ),
    );
  }
}

喜欢记得点个赞哟,我是王睿,很高兴认识大家!

更多原理请参考谷歌官网:从新页面返回数据给上一个页面

你可能感兴趣的:(Flutter,学习)