setState不会更改如何将StatefulWidget设置为StatefulWidget?

时间:2019-02-13 14:57:45

标签: dart flutter

StatefulWidget到StatefulWidget 如何在类Test2 setstate中更改字符串TimeSetdata

   class Test1 extends StatefulWidget {
      @override
      _Test1State createState() => _Test1State();
    }

    class _Test1State extends State<Test1> {
      String TimeSetdata = "9.00 AM";
      @override
      Widget build(BuildContext context) {
       ...
       Text(TimeSetdata);
      }
    }
    class Test2 extends StatefulWidget {
      @override
      _Test2State createState() => _Test2State();
    }

    class _Test2State extends State<Test2> {
      @override
      Widget build(BuildContext context) {
        ...
        onPressed: () {
          setState(() {
            TimeSetdata = "11.00 AM";
          });
        };
      }
    }

如何在类Test2中设置setState,将小部件文本(TimeSetdata)中的字符串TimeSetdata更改为“ 11.00 AM”;

1 个答案:

答案 0 :(得分:0)

允许父级将回调函数传递给子级,并在从子级调用时传递回调,以更新父级中的值。

这假设Test2Test1的子代(您并未在问题中明确指出这一点)

typedef StringCallback = void Function(String);

class Test2 extends StatefulWidget {
  Test2({@required this.onPressed});

  final StringCallback onPressed;

  @override
  _Test2State createState() => _Test2State(onPressed: onPressed);
}

class _Test2State extends State<Test2> {
  _Test2State({@required this.onPressed});

  final StringCallback onPressed;

  @override
  Widget build(BuildContext context) {
    ...
    onPressed: () => onPressed(),
  }
}

class _Test1State extends State<Test1> {
  String TimeSetdata = "9.00 AM";
  @override
  Widget build(BuildContext context) {
   ...
   Test2(onPressed: (s) => setState(() => TimeSetdata = s),
   ...
   Text(TimeSetdata);
  }
}