如何在函数或类中传递变量引用?

时间:2019-08-24 14:58:30

标签: flutter dart

我想在程序中更新一些不同类的变量。 通过下面给出的示例,您将获得更好的主意:

class ABC{
int a;
int b;
int c;
int d;
}
ABC abc =new ABC();


 class Widget1 extends StatelessWidget {
   @override
   Widget build(BuildContext context) {
       return Container(
    child:Widget2(a:abc.a)//want to pass abc.a here and also update its value through widget 2
   );
   }
 }

 class Widget2 extends StatelessWidget {
int a;
  Widget2(this.a);


void update(){
.....this update must also reflect in 
}

   @override
   Widget build(BuildContext context) {
     return Container();
   }
 }

2 个答案:

答案 0 :(得分:2)

class ABC {
  int a;
  int b;
  int c;
  int d;
}

ABC abc = new ABC();

class Widget1 extends StatefulWidget {
  @override
  _Widget1State createState() => _Widget1State();
}

class _Widget1State extends State<Widget1> {
  int _a; // make it instance variable

  @override
  void initState() {
    super.initState();
    _a = ABC().a; // give it initial value here
  }

  // make a new method, which will update the value of _a
  void _update (int newValue) {
    setState(() {
      _a = newValue; // when Widget2 calls update, this method assigns new value to _a
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Widget2(
        a: abc.a,
        update: _update, // passing above method to Widget2
      ),
    );
  }
}

class Widget2 extends StatefulWidget {
  final int a;
  final Function update;

  Widget2({this.a, this.update});

  @override
  _Widget2State createState() => _Widget2State();
}

class _Widget2State extends State<Widget2> {
  void update() {
   widget.update(10); // updating the _a value in above widget with 10
  }

  @override
  Widget build(BuildContext context) {
    return Container();
  }
}

答案 1 :(得分:2)

有多种方式,例如单例:


class AppData {
  static final AppData _appData = new AppData._internal();
  String text;  
  factory AppData() {
    return _appData;
  }  
  AppData._internal();
}

final appData = AppData();

然后您可以使用“ appData.text”

对于复杂的项目,您可以使用“ inheritWidget”,“ redux”,“ async_redux”

这里有一篇很棒的文章: https://medium.com/flutter-community/simple-ways-to-pass-to-and-share-data-with-widgets-pages-f8988534bd5b