Flutter项目中的变量太多

问题描述 投票:0回答:1

我对编程很陌生,我正在尝试在Flutter项目中创建一叠纸牌。每张卡包含不同的数据/信息,当我尝试使用虚拟数据进行可视化时,我必须使用很多变量,这几乎是每张卡重复使用的变量名称。有没有办法使可重复使用的卡组件变得扑朔迷离,因此我可以使其变得清晰和简单,因为将来使用真实数据时,我可能会在同一组中拥有2张以上的卡,并且它们也将具有不同的数据。任何建议将不胜感激。

class MyConstructor {


MyConstructor({this.jonathan1,this.jonathan2,this.jonathan3});
}


class StackedCardsState extends State<HomePage> {

  List<MyConstructor> cards = [
    MyConstructor(h1: "Hello", h2: "hello3")
  ];

/////
                  Padding(
                      padding: EdgeInsets.all(15.0),
                      child: Column(children: [
                        Text(MyConstructor.hey, style: TextStyle(fontWeight: FontWeight.bold),),
                        Text(MyConstructor.hey),
                        Text(MyConstructor.hey, style: TextStyle(color: Colors.red[500]),),
                        VerticalDivider(color: Colors.blue),
                      ])),

flutter flutter-layout flutter-dependencies flutter-animation flutter-test
1个回答
-1
投票

您可以构造卡的构造函数,并每次传递您想要的值。

构造函数示例

class MyConstructor extends StatefullWidget{
double data1;
String data2;
//you can do the same for any non-static variable 
MyConstructor(this.data1,this.data2)
//your card using the variables must be bellow 
}

现在,每次您要创建卡时,您都将放置值或什至变量

MyConstructor(22.0,'string')

我编辑了yoyr构造函数,我认为现在可以正常使用了,尽管我没有对其进行测试

   class MyConstructor extends StatefulWidget{
//I am using StatefulWidget so I can use my variables without needing to be static
String jonathan1;
String jonathan2;
String jonathan3;

MyConstructor({this.jonathan1,this.jonathan2,this.jonathan3});

 @override
  StackedCardsState createState() => MainClass();
 }
}



class StackedCardsState extends State<HomePage> with AfterLayoutMixin<MyConstructor>{

  List<MyConstructor> cards = [
    MyConstructor(jonathan1: "Hello", jonathan2: "hello3")
  ];


    @override
    void initState() {
    super.initState();
  }
     @override
     Widget build(BuildContext context) {
     return Padding(
      padding: EdgeInsets.all(15.0),
       child: Column(children: [
        Text(widget.jonathan1, 
         style: TextStyle(
          fontWeight: FontWeight.bold),
             ),
         Text(widget.jonathan2),
         Text(widget.jonathan3, 
          style: TextStyle(color: Colors.red[500]),
              ),
         VerticalDivider(color: Colors.blue),
  ]
 )
);
© www.soinside.com 2019 - 2024. All rights reserved.