如何将变量从一个类传递到另一个类

时间:2020-09-22 01:16:03

标签: flutter dart

我在此类中设置了numOfItems,并且我想在另一个类AddToCart中使用它,但是我无法成功传递变量。这是示例代码,请问如何执行此操作,我似乎无法弄清楚出来,我想知道的是将setState传递给另一个类之后传递数据的最佳方法。

  static int numOfItems = 1;
  @override
  Widget build(BuildContext context) {
    return Row(
      children: <Widget>[
        buildOutlineButton(
          icon: Icons.remove,
          press: () {
            if(numOfItems > 1){
              setState(() {
                numOfItems--;
              });
            }
          },
        ),
        Padding(
          padding: const EdgeInsets.symmetric(horizontal: kDefaultPaddin / 2),
          child: Text(
            //"01",
            numOfItems.toString().padLeft(2, "0"),
            style: Theme.of(context).textTheme.headline,
          ),
        ),
        buildOutlineButton(
            icon: Icons.add,
            press: () {
              setState(() {
                numOfItems++;
              });
            }),
      ],
    );
  }

  SizedBox buildOutlineButton({IconData icon, Function press}) {
    return SizedBox(
      width: 32,
      height: 32,
      child: OutlineButton(
        padding: EdgeInsets.zero,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(10),
        ),
        onPressed: press,
        child: Icon(icon),
      ),
    );
  }
}```


here is the second class where I want to use the numOfItems in the second class, how can I access the variable in this class.

```class AddToCart extends StatelessWidget {
  const AddToCart({
    Key key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    Size size = MediaQuery.of(context).size;
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: kDefaultPaddin),
      child: Row(
        children: <Widget>[
          Container(
            margin: EdgeInsets.only(right:kDefaultPaddin),
            height:50,
            width: size.width * 0.3,
            decoration: BoxDecoration(
              border: Border.all(color:primaryColorDark),
              borderRadius: BorderRadius.circular(18),
            ),
            child: IconButton(
              icon: SvgPicture.asset(
                "assets/icons/add_to_cart.svg", color: primaryColorDark,), //svgPicture.asser
              onPressed: () {
                // on press of the cart button
              },
            ),
          ),
          Expanded(
            child: SizedBox(
              height:50,
              child: FlatButton(
                shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(18)
                ),
                color: primaryColor,
                onPressed: (){
                  addProductToCart(context);

                },
                child: Text(
                    "Buy Now".toUpperCase(),
                    style: TextStyle(
                      fontSize: 17,
                      fontWeight: FontWeight.bold,
                      color: Colors.white,
                    )
                ),
              ),
            ),
          )
        ],
      ),
    );
  }

  void addProductToCart(BuildContext context) {
   
    String quantityToSend = numOfItems
  }
}
}```

What I want to know is the best way to pass data after I have setState to the other class.. 

2 个答案:

答案 0 :(得分:0)

如果仅需要此变量“ If it widget”,则只需使用类名x然后使用.然后使用the name of static variable

x.numOfItems

如果这是另一个屏幕,并且您要将数据传递到此屏幕,则可以这样操作

class SecondScreen{
var anyVariable;
XScreen(this.anyVariable);
.......
......
}

onTap: () {
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => SecondScreen(anyVariable :numOfItems),
          ),
        );
      },

答案 1 :(得分:0)

您可以使用constructor传递变量
示例:
屏幕1:

class _TabsPageState extends State<TabsPage> {
  int args = 3;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: FlatButton(
          color: Colors.blueAccent,
          child: Text('Navigate to home', style: TextStyle(color: Colors.white),),
          onPressed: () {
            print('123');
            Navigator.pushReplacement(context, MaterialPageRoute(builder: (_) => Tab2Page(args)));
          },
        ),
      ),
    );
  }
}

Screen2:

class Tab2Page extends StatelessWidget {
  final int args;

  Tab2Page(this.args);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Text(args.toString()),
      ),
    );
  }
}