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

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

问题描述

在学习Flutter时,我已经开始导航.我想在屏幕之间传递数据,类似于在两个屏幕之间传递数据Android中的活动在iOS中的视图控制器之间传递数据.如何在Flutter中做到这一点?

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?

相关问题:

  • The best way to passing data between widgets in Flutter
  • Flutter pass data between widgets?
  • Flutter/ How to pass and get data between Statefulwidget

推荐答案

此答案将涵盖向前传递数据和向后传递数据.与Android活动和iOS ViewController不同,Flutter中的不同屏幕只是小部件.在它们之间进行导航涉及创建一种称为路由的东西,并使用Navigator在堆栈上上下推路由.

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.

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

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

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

  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);

  ...

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

  • 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',),
        ));
    

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

    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),
            ),
          ),
        );
      }
    }
    

    将数据传递回上一屏幕

    将数据传回时,您需要执行以下操作:

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

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

    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(),
        ));
    

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

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

    Navigator.pop(context, 'Hello');
    

  • 然后在FirstScreen中的await中将完成操作,您可以使用结果.

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

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

  • 这是main.dart的完整代码,供您参考.

    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天全站免登陆