来自其他子组件的子集状态

时间:2019-03-28 13:04:49

标签: dart flutter

比方说,我们有Car(Stateless)类,现在在它里面有两个类,它将是Wheel(Statefull)和Mask(Statefull),我的工作是每当改变Wheel类的状态时,调用class Mask来对其进行更改还要使用Wheel的特定数据声明状态,但父级也应该有权访问子级数据。我该如何实现?

import 'package:flutter/material.dart';

void main() {
  runApp(Car());
}

class Car extends StatelessWidget {
 int childMaskVal = ..??????

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Scaffold(
        appBar: AppBar(
          title: Text('App bar'),
        ),
        body: Column(
          children: <Widget>[
            Wheel(),
            Mask(),
          ],
        ),
      ),
    );
  }
}


class Wheel extends StatefulWidget {

  _WheelState createState() => _WheelState();
}

class _WheelState extends State<Wheel> {
 int _value = 0;

  @override
  Widget build(BuildContext context) {
    return Container(
       child: Column(
         children: <Widget>[
           RaisedButton(
           onPressed: () {
             setState(() {
              _value++; 
             });
           },
         ),
         Text(_value.toString()),
         ],
       ),
    );
  }
}

class Mask extends StatefulWidget {

  _MaskState createState() => _MaskState();
}

class _MaskState extends State<Mask> {
  int _value = 13;

  @override
  Widget build(BuildContext context) {
    return Container(
       child: Text((_value * Wheel._value).toString()),???????
    );
  }
}

1 个答案:

答案 0 :(得分:0)

您可以将回调传递给孩子。

在您提供的示例中,父级应该是statefulWidget,子级应该是无状态小部件。您应该在父级中初始化状态,然后将其传递给子级。

如果您发现父级需要访问子级中的数据,则意味着您需要将状态上移。

请参见以下示例:

import 'package:flutter/material.dart';

void main() {
  runApp(Car());
}

class Car extends StatefulWidget{
@override
  _CarState createState() => _CarState();
}

class _CarState extends State<Car> {
 int childMaskVal = ..??????
 int _value = 1;

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Scaffold(
        appBar: AppBar(
          title: Text('App bar'),
        ),
        body: Column(
          children: <Widget>[
            Wheel(
              value: _value,
              onPressed: () {
               setState(() {
                  _value++;
                  // update state here
               })
            }),
            Mask(),
          ],
        ),
      ),
    );
  }
}

class Wheel extends Stateless {
  int value;
  Function onPressed;
  Wheel({this.value, this.onPresed})

  @override
  Widget build(BuildContext context) {
    return Container(
       child: Column(
         children: <Widget>[
           RaisedButton(
           onPressed: onPressed
         ),
         Text(value.toString()),
         ],
       ),
    );
  }
}

您也可以查看此帖子How to pass data from child widget to its parent