在 Flutter 中在屏幕之间传递数据 [英] Passing data between screens in Flutter

查看:22
本文介绍了在 Flutter 中在屏幕之间传递数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我学习 Flutter 时,我开始学习导航.我想在屏幕之间传递数据类似于

要将数据发送到下一个屏幕,您需要执行以下操作:

  1. 使 SecondScreen 构造函数接受您要发送给它的数据类型的参数.在这个特定示例中,数据被定义为一个 String 值,并在此处使用 this.text 进行设置.

    class SecondScreen 扩展 StatelessWidget {最终字符串文本;SecondScreen({Key key, @required this.text}) : super(key: key);...

  2. 然后使用 FirstScreen 小部件中的 Navigator 将路由推送到 SecondScreen 小部件.您将要作为参数发送的数据放入其构造函数中.

    Navigator.push(语境,材质页面路由(构建器:(上下文)=>SecondScreen(text: '你好',),));

main.dart 的完整代码在这里:

import 'package:flutter/material.dart';无效主(){运行应用程序(材料应用程序(title: '颤动',主页:FirstScreen(),));}class FirstScreen 扩展了 StatefulWidget {@覆盖_FirstScreenState createState() {返回_FirstScreenState();}}class _FirstScreenState 扩展 State{//这允许我们访问 TextField 文本TextEditingController textFieldController = TextEditingController();@覆盖小部件构建(BuildContext 上下文){返回脚手架(appBar: AppBar(title: Text('First screen')),正文:列(mainAxisAlignment: MainAxisAlignment.center,孩子们: [填充(填充:const EdgeInsets.all(32.0),孩子:文本字段(控制器:textFieldController,风格:文字风格(字体大小:24,颜色:Colors.black,),),),凸起按钮(孩子:文本('转到第二个屏幕',样式:TextStyle(字体大小:24),),按下: () {_sendDataToSecondScreen(上下文);},)],),);}//获取 TextField 中的文本并启动第二个屏幕无效_sendDataToSecondScreen(构建上下文上下文){String textToSend = textFieldController.text;导航器.push(语境,材质页面路由(构建器:(上下文)=>SecondScreen(文本:textToSend,),));}}class SecondScreen 扩展了 StatelessWidget {最终字符串文本;//从 FirstScreen 接收数据作为参数SecondScreen({Key key, @required this.text}) : super(key: key);@覆盖小部件构建(BuildContext 上下文){返回脚手架(appBar: AppBar(title: Text('第二屏')),身体:中心(孩子:文本(文本,样式:TextStyle(字体大小:24),),),);}}

将数据传回上一屏

回传数据时需要做以下几件事:

  1. FirstScreen 中,使用 Navigatorasync 中推送(启动)SecondScreen> 方法并等待它完成时返回的结果.

    final result = await Navigator.push(语境,材质页面路由(构建器:(上下文)=>第二屏(),));

  2. SecondScreen 中,包含您想要在弹出 Navigator 时作为参数传回的数据.

    Navigator.pop(context, 'Hello');

  3. 然后在 FirstScreenawait 将完成,您可以使用结果.

    setState(() {文字 = 结果;});

这里是 main.dart 的完整代码,供大家参考.

import 'package:flutter/material.dart';无效主(){运行应用程序(材料应用程序(title: '颤动',主页:FirstScreen(),));}class FirstScreen 扩展了 StatefulWidget {@覆盖_FirstScreenState createState() {返回_FirstScreenState();}}class _FirstScreenState 扩展 State{字符串文本 = '文本';@覆盖小部件构建(BuildContext 上下文){返回脚手架(appBar: AppBar(title: Text('First screen')),身体:中心(孩子:列(mainAxisAlignment: MainAxisAlignment.center,孩子们: [填充(填充:const EdgeInsets.all(32.0),孩子:文本(文本,样式:TextStyle(字体大小:24),),),凸起按钮(孩子:文本('转到第二个屏幕',样式:TextStyle(字体大小:24),),按下: () {_awaitReturnValueFromSecondScreen(上下文);},)],),),);}void _awaitReturnValueFromSecondScreen(BuildContext context) async {//启动 SecondScreen 并等待它以结果结束最终结果 = 等待 Navigator.push(语境,材质页面路由(构建器:(上下文)=>第二屏(),));//在 SecondScreen 结果回来后,用它更新 Text 小部件设置状态((){文字 = 结果;});}}class SecondScreen 扩展了 StatefulWidget {@覆盖_SecondScreenState createState() {返回 _SecondScreenState();}}class _SecondScreenState 扩展 State{//这允许我们访问 TextField 文本TextEditingController textFieldController = TextEditingController();@覆盖小部件构建(BuildContext 上下文){返回脚手架(appBar: AppBar(title: Text('第二屏')),正文:列(mainAxisAlignment: MainAxisAlignment.center,孩子们: [填充(填充:const EdgeInsets.all(32.0),孩子:文本字段(控制器:textFieldController,风格:文字风格(字体大小:24,颜色:Colors.black,),),),凸起按钮(孩子:文本('发回文本',样式:TextStyle(字体大小:24),),按下: () {_sendDataBack(上下文);},)],),);}//获取 TextField 中的文本并将其发送回 FirstScreenvoid _sendDataBack(BuildContext 上下文) {String textToSendBack = textFieldController.text;Navigator.pop(context, textToSendBack);}}

As I'm learning Flutter I've come to navigation. I want to pass data between screens similarly to passing data between Activities in Android and passing data between View Controllers in iOS. How do I do it in Flutter?

Related questions:

解决方案

This answer will cover both passing data forward and passing data back. Unlike Android Activities and iOS ViewControllers, different screens in Flutter are just widgets. Navigating between them involves creating something called a route and using the Navigator to push and pop the routes on and off the stack.

Passing data forward to the next screen

To send data to the next screen you do the following things:

  1. Make the SecondScreen constructor take a parameter for the type of data that you want to send to it. In this particular example, the data is defined to be a String value and is set here with this.text.

    class SecondScreen extends StatelessWidget {
      final String text;
      SecondScreen({Key key, @required this.text}) : super(key: key);
    
      ...
    

  2. Then use the Navigator in the FirstScreen widget to push a route to the SecondScreen widget. You put the data that you want to send as a parameter in its constructor.

    Navigator.push(
        context,
        MaterialPageRoute(
          builder: (context) => SecondScreen(text: 'Hello',),
        ));
    

The full code for main.dart is here:

import 'package:flutter/material.dart';

void main() {
  runApp(MaterialApp(
    title: 'Flutter',
    home: FirstScreen(),
  ));
}

class FirstScreen extends StatefulWidget {
  @override
  _FirstScreenState createState() {
    return _FirstScreenState();
  }
}

class _FirstScreenState extends State<FirstScreen> {

  // this allows us to access the TextField text
  TextEditingController textFieldController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('First screen')),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [

          Padding(
            padding: const EdgeInsets.all(32.0),
            child: TextField(
              controller: textFieldController,
              style: TextStyle(
                fontSize: 24,
                color: Colors.black,
              ),
            ),
          ),

          RaisedButton(
            child: Text(
              'Go to second screen',
              style: TextStyle(fontSize: 24),
            ),
            onPressed: () {
              _sendDataToSecondScreen(context);
            },
          )

        ],
      ),
    );
  }

  // get the text in the TextField and start the Second Screen
  void _sendDataToSecondScreen(BuildContext context) {
    String textToSend = textFieldController.text;
    Navigator.push(
        context,
        MaterialPageRoute(
          builder: (context) => SecondScreen(text: textToSend,),
        ));
  }
}

class SecondScreen extends StatelessWidget {
  final String text;

  // receive data from the FirstScreen as a parameter
  SecondScreen({Key key, @required this.text}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Second screen')),
      body: Center(
        child: Text(
          text,
          style: TextStyle(fontSize: 24),
        ),
      ),
    );
  }
}

Passing data back to the previous screen

When passing data back you need to do the following things:

  1. In the FirstScreen, use the Navigator to push (start) the SecondScreen in an async method and wait for the result that it will return when it finishes.

    final result = await Navigator.push(
        context,
        MaterialPageRoute(
          builder: (context) => SecondScreen(),
        ));
    

  2. In the SecondScreen, include the data that you want to pass back as a parameter when you pop the Navigator.

    Navigator.pop(context, 'Hello');
    

  3. Then in the FirstScreen the await will finish and you can use the result.

    setState(() {
      text = result;
    });
    

Here is the complete code for main.dart for your reference.

import 'package:flutter/material.dart';

void main() {
  runApp(MaterialApp(
    title: 'Flutter',
    home: FirstScreen(),
  ));
}

class FirstScreen extends StatefulWidget {
  @override
  _FirstScreenState createState() {
    return _FirstScreenState();
  }
}

class _FirstScreenState extends State<FirstScreen> {

  String text = 'Text';

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('First screen')),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [

            Padding(
              padding: const EdgeInsets.all(32.0),
              child: Text(
                text,
                style: TextStyle(fontSize: 24),
              ),
            ),

            RaisedButton(
              child: Text(
                'Go to second screen',
                style: TextStyle(fontSize: 24),
              ),
              onPressed: () {
                _awaitReturnValueFromSecondScreen(context);
              },
            )

          ],
        ),
      ),
    );
  }

  void _awaitReturnValueFromSecondScreen(BuildContext context) async {

    // start the SecondScreen and wait for it to finish with a result
    final result = await Navigator.push(
        context,
        MaterialPageRoute(
          builder: (context) => SecondScreen(),
        ));

    // after the SecondScreen result comes back update the Text widget with it
    setState(() {
      text = result;
    });
  }
}

class SecondScreen extends StatefulWidget {
  @override
  _SecondScreenState createState() {
    return _SecondScreenState();
  }
}

class _SecondScreenState extends State<SecondScreen> {
  // this allows us to access the TextField text
  TextEditingController textFieldController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Second screen')),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [

          Padding(
            padding: const EdgeInsets.all(32.0),
            child: TextField(
              controller: textFieldController,
              style: TextStyle(
                fontSize: 24,
                color: Colors.black,
              ),
            ),
          ),

          RaisedButton(
            child: Text(
              'Send text back',
              style: TextStyle(fontSize: 24),
            ),
            onPressed: () {
              _sendDataBack(context);
            },
          )

        ],
      ),
    );
  }

  // get the text in the TextField and send it back to the FirstScreen
  void _sendDataBack(BuildContext context) {
    String textToSendBack = textFieldController.text;
    Navigator.pop(context, textToSendBack);
  }
}

这篇关于在 Flutter 中在屏幕之间传递数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆