将数据从另一个类传递到另一个类 onPressed Flutter

Posted

技术标签:

【中文标题】将数据从另一个类传递到另一个类 onPressed Flutter【英文标题】:Passing data from another class to another's class onPressed Flutter 【发布时间】:2020-07-17 05:03:54 【问题描述】:

我正在尝试将数据从 A 类传递到另一个 B 类。B 类会接受它并通过 onPressed(在 B 类中)将数据传递到屏幕 C。

以下是我如何传递和检索数据。目前,我在屏幕 C 中的输出为“null”,它应该显示来自 A 类的数据

从 A 类传递数据
class SelectAccount extends StatefulWidget 
  @override
  _SelectAccountState createState() => _SelectAccountState();


class _SelectAccountState extends State<SelectAccount> 

  var dropdownValue = 'one';

  @override
  Widget build(BuildContext context) 
    return Container(
      child: Padding(
        padding: EdgeInsets.only(right: 10, left: 10),
        child: Container(
          constraints: BoxConstraints.expand(width: 375.0, height: 100.0),
          decoration: BoxDecoration(
            color: Colors.white,
            border: Border.all(color: Colors.grey),
            borderRadius: BorderRadius.circular(5.0),
          ),
          child: Container(
            child: Padding(
              padding: const EdgeInsets.only(
                  right: 12.0, left: 12.0, top: 5.0, bottom: 5.0),
              child: DropdownButtonHideUnderline(
                child: DropdownButton<String>(
                  itemHeight: 120,
                  isExpanded: true,
                  value: dropdownValue,
                  onChanged: (String value) 
                    setState(() 
                      dropdownValue = value;
                    );
                  ,
                  items: [
                    DropdownMenuItem<String>(
                      child: Column(
                        children: <Widget>[
                          Card(
                            //margin: EdgeInsets.symmetric(vertical: 20.0, horizontal: 20.0),
                            child: Container(
                              padding: EdgeInsets.only(left: 10.0),
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: <Widget>[
                                  Text(
                                    'Saving Account',
                                    style: TextStyle(
                                      fontSize: 15.0,
                                      fontWeight: FontWeight.bold,
                                      color: Colors.black,
                                    ),
                                  ),
                                  SizedBox(
                                    height: 5.0,
                                  ),
                                  Text(
                                    'Savings XXX-X-XX563-9',
                                    style: TextStyle(
                                      fontSize: 10.0,
                                      color: Colors.grey[900],
                                    ),
                                  ),
                                  SizedBox(
                                    height: 15.0,
                                  ),
                                  Container(
                                    child: Row(
                                      children: <Widget>[
                                        RichText(
                                          text: TextSpan(
                                            text: '56,302.56',
                                            style: TextStyle(
                                              fontSize: 25.0,
                                              fontWeight: FontWeight.bold,
                                              color: Colors.black,
                                            ),
                                            children: <TextSpan>[
                                              TextSpan(
                                                text: ' THB',
                                                style: TextStyle(
                                                    fontSize: 15.0,
                                                    fontWeight:
                                                    FontWeight.bold),
                                              ),
                                            ],
                                          ),
                                        ),
                                      ],
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          ),
                        ],
                      ),
                      value: 'one',
                    ),
                    DropdownMenuItem<String>(
                      child: Column(
                        children: <Widget>[
                          Card(
                            //margin: EdgeInsets.symmetric(vertical: 20.0, horizontal: 20.0),
                            child: Container(
                              padding: EdgeInsets.only(left: 10.0),
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: <Widget>[
                                  Text(
                                    'Saving Account 2',
                                    style: TextStyle(
                                      fontSize: 15.0,
                                      fontWeight: FontWeight.bold,
                                      color: Colors.black,
                                    ),
                                  ),
                                  SizedBox(
                                    height: 5.0,
                                  ),
                                  Text(
                                    'Savings XXX-X-XX563-9',
                                    style: TextStyle(
                                      fontSize: 10.0,
                                      color: Colors.grey[900],
                                    ),
                                  ),
                                  SizedBox(
                                    height: 15.0,
                                  ),
                                  Container(
                                    child: Row(
                                      children: <Widget>[
                                        RichText(
                                          text: TextSpan(
                                            text: '89,302.56',
                                            style: TextStyle(
                                              fontSize: 25.0,
                                              fontWeight: FontWeight.bold,
                                              color: Colors.black,
                                            ),
                                            children: <TextSpan>[
                                              TextSpan(
                                                text: ' THB',
                                                style: TextStyle(
                                                    fontSize: 15.0,
                                                    fontWeight:
                                                    FontWeight.bold),
                                              ),
                                            ],
                                          ),
                                        ),
                                      ],
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          ),
                        ],
                      ),
                      value: 'two',
                    ),
                    //DropdownMenuItem<String>(),
                  ],
                ),
              ),
            ),
          ),
        ),
      ),
    );
  


class PassAccount 

  static String dropdownValue;


接受 B 类中的数据
class ToContainer extends StatefulWidget 
  
  final PassAccount dropdownValue;

  ToContainer(Key key, this.dropdownValue) : super(key: key);

  @override
  _ToContainerState createState() => _ToContainerState();

通过 onPressed() 将 B 类接受的数据传递到屏幕 C
class _ToContainerState extends State<ToContainer> 

  var AccountSelected = PassAccount.dropdownValue;

  @override
  Widget build(BuildContext context) 
    return Container(
      color: Colors.white,
      child: Column(
        children: <Widget>[
          Container(
            padding: EdgeInsets.only(
                top: 5.0, left: 10.0, right: 10.0, bottom: 10.0),
            child: SafeArea(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Row(
                    children: <Widget>[
                      Expanded(
                        child: CupertinoButton(
                          child: Text(
                            'Next',
                            style: style.clickButton,
                          ),
                          onPressed: () 
                            var route = new MaterialPageRoute(
                              builder: (BuildContext context) =>
                                  new DirectedScreen(
                                      value: PassData(
                                account: AccountSelected,
                              )),
                            );
                            Navigator.of(context).push(route);
                          ,
                          color: Colors.blue[600],
                          borderRadius: BorderRadius.circular(200.0),
                          disabledColor: Colors.grey,
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  




class PassData 

  final String account;

  const PassData(
      
        this.account
      );

在屏幕 C 中显示数据
class DirectedScreen extends StatefulWidget 
  final PassData value;

  DirectedScreen(Key key, this.value) : super(key: key);

  @override
  _DirectedScreenState createState() => _DirectedScreenState();


class _DirectedScreenState extends State<DirectedScreen> 
  @override
  Widget build(BuildContext context) 
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: Text('Transfer Summary'),
      ),
      body: Container(
        child: new Center(
          child: Column(
            children: <Widget>[
              Padding(
                child: new Text(
                  'PASSED VALUES',
                  style: new TextStyle(
                      fontWeight: FontWeight.bold, fontSize: 20.0),
                  textAlign: TextAlign.center,
                ),
                padding: EdgeInsets.only(bottom: 20.0),
              ),
              Padding(
                child: new Text(
                  'Bank : $widget.value.account',
                  style: new TextStyle(fontWeight: FontWeight.bold),
                  textAlign: TextAlign.left,
                ),
                padding: EdgeInsets.all(10.0),
              ),
            ],
          ),
        ),
      ),
    );
  


感谢您的帮助!

【问题讨论】:

因为dropdownvalue 没有设置? @BillionShiferaw 实际上是这样。 dropdownValue 是从下拉菜单中选择的项目的值。我已经编辑了上面的代码。 【参考方案1】:

您应该能够使用arguments 将数据从 B 传递到屏幕 C。您可以查看指南以获取示例。

【讨论】:

【参考方案2】:

不要为每个小部件创建单独的数据类。而是仅使用现有的。使用widget.dropdownValue 使用状态类中的参数,该参数在有状态小部件类中定义。见以下代码:

onPressed: () 
  var route = new MaterialPageRoute(
    builder: (BuildContext context) =>
        new DirectedScreen(value: widget.dropdownValue),
  );
  Navigator.of(context).push(route);
,

并且在 DirectedScreen 中使用 PassAccount 仅捕获值。

【讨论】:

感谢您的回复。我正在使用一个单独的类,因为“dropdownValue”的值来自下拉菜单项。代码很长,所以我把它分开了。您认为按照您的建议将它们编译成一个类更好吗? 是的,最好将所有数据类分开并尽可能重用每个类【参考方案3】:

您可以在下面复制粘贴运行完整代码 您需要将var AccountSelected = PassAccount.dropdownValue; 移动到build

代码 sn-p

@override
  Widget build(BuildContext context) 
    var AccountSelected = PassAccount.dropdownValue;
    return Container(

工作演示,初始化为 456,点击浮动操作按钮后变为 789

完整代码

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

class PassAccount 
  static String dropdownValue;


class ToContainer extends StatefulWidget 
  final PassAccount dropdownValue;

  ToContainer(Key key, this.dropdownValue) : super(key: key);

  @override
  _ToContainerState createState() => _ToContainerState();


class _ToContainerState extends State<ToContainer> 
  //var AccountSelected = PassAccount.dropdownValue;

  @override
  Widget build(BuildContext context) 
    var AccountSelected = PassAccount.dropdownValue;
    return Container(
      color: Colors.white,
      child: Column(
        children: <Widget>[
          Container(
            padding: EdgeInsets.only(
                top: 5.0, left: 10.0, right: 10.0, bottom: 10.0),
            child: SafeArea(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Row(
                    children: <Widget>[
                      Expanded(
                        child: CupertinoButton(
                          child: Text(
                            'Next',
                            //style: style.clickButton,
                          ),
                          onPressed: () 
                            var route = new MaterialPageRoute(
                              builder: (BuildContext context) =>
                                  new DirectedScreen(
                                      value: PassData(
                                account: AccountSelected,
                              )),
                            );
                            Navigator.of(context).push(route);
                          ,
                          color: Colors.blue[600],
                          borderRadius: BorderRadius.circular(200.0),
                          disabledColor: Colors.grey,
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  


class PassData 
  final String account;

  const PassData(this.account);


class DirectedScreen extends StatefulWidget 
  final PassData value;

  DirectedScreen(Key key, this.value) : super(key: key);

  @override
  _DirectedScreenState createState() => _DirectedScreenState();


class _DirectedScreenState extends State<DirectedScreen> 
  @override
  Widget build(BuildContext context) 
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: Text('Transfer Summary'),
      ),
      body: Container(
        child: new Center(
          child: Column(
            children: <Widget>[
              Padding(
                child: new Text(
                  'PASSED VALUES',
                  style: new TextStyle(
                      fontWeight: FontWeight.bold, fontSize: 20.0),
                  textAlign: TextAlign.center,
                ),
                padding: EdgeInsets.only(bottom: 20.0),
              ),
              Padding(
                child: new Text(
                  'Bank : $widget.value.account',
                  style: new TextStyle(fontWeight: FontWeight.bold),
                  textAlign: TextAlign.left,
                ),
                padding: EdgeInsets.all(10.0),
              ),
            ],
          ),
        ),
      ),
    );
  


void main() 
  runApp(MyApp());


class MyApp extends StatelessWidget 
  @override
  Widget build(BuildContext context) 
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  


class MyHomePage extends StatefulWidget 
  MyHomePage(Key key, this.title) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();


class _MyHomePageState extends State<MyHomePage> 
  int _counter = 0;

  @override
  void initState() 
    PassAccount.dropdownValue = "456";
    super.initState();
  

  void _incrementCounter() 
    PassAccount.dropdownValue = "789";
    setState(() 
      _counter++;
    );
  

  @override
  Widget build(BuildContext context) 
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            ToContainer(),
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  

【讨论】:

感谢您的回复。根据您的代码,银行的价值是硬编码的,对。我的 dropdownValue 实际上是下拉菜单项中的值。你认为我仍然可以解决代码吗?谢谢! 它可以正常工作。获得下拉值后。只需设置 PassAccount.dropdownValue = "yourvalue"。就像单击浮动操作按钮并更改值一样。 AccountSelected 是您原始代码中的固定值。 其实不需要AccountSelected。你可以直接使用 DirectedScreen(value: PassData(account: PassAccount.dropdownValue 我可以知道为什么我不需要 AccountSelected 吗?因为,点击按钮时会传递 dropdownValue。

以上是关于将数据从另一个类传递到另一个类 onPressed Flutter的主要内容,如果未能解决你的问题,请参考以下文章

c#将事件的参数从另一个类传递到主类

React 无法使用 Link 将数据从一个类组件传递到另一个类组件

如何将 React 中的状态从一个类传递到另一个类?

如何将数据从一个实体传递到另一个实体类?

如何通过意图将数据从静态方法发送到另一个类?

反应将 onClick 值从一个类传递到另一个类