Как я могу изменить состояние виджета и внешний класс - PullRequest
0 голосов
/ 15 ноября 2018

Я создал класс кнопки виджета, который изменяет размеры и показывает кнопку прогресса при нажатии. Через некоторое время будет отображаться сообщение об ошибке или об успехе в зависимости от состояния в классе виджетов.

Это три разных состояния:

State Failure State Success State Loading

Это источник пользовательской кнопки прогресса:

class ProgressButton extends StatefulWidget {
  final VoidCallback onPressed;
  final int state;
  final String text;

  ProgressButton({
    Key key,
    this.text,
    this.state,
    this.onPressed,
  })  : assert(state >= 0),
        assert(text != null),
        super(key: key);

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

class _ProgressButtonState extends State<ProgressButton>
    with TickerProviderStateMixin {
  static _ProgressButtonState of(BuildContext context) =>
      context.ancestorStateOfType(const TypeMatcher<_ProgressButtonState>());

  int state = 0;
  Animation _animation;
  double width = double.infinity;

  double unchangedInit = 0.0;

  double initialWidth = 0.0;

  GlobalKey globalKey = GlobalKey();

  String btnText = "";

  @override
  void initState() {
    super.initState();

    btnText = widget.text;
    state = widget.state;
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      key: globalKey,
      height: 48.0,
      width: width,
      child: RaisedButton(
        padding: EdgeInsets.all(0.0),
        color:
            state == 2 ? Colors.green : state == 3 ? Colors.red : Colors.blue,
        shape: new RoundedRectangleBorder(
          borderRadius: new BorderRadius.circular(30.0),
        ),
        child: buildButtonChild(),
        onPressed: widget.onPressed,
      ),
    );
  }

  void animateButton() {
    unchangedInit = 411.42857142857144;

    initialWidth = globalKey.currentContext.size.width;

    var controller = AnimationController(
        duration: Duration(microseconds: 2000), vsync: this);
    _animation = Tween(begin: 0.0, end: 1.0).animate(controller)
      ..addListener(() {
        setState(() {
          width = initialWidth - ((initialWidth - 48.0) * _animation.value);
        });
      });

    controller.forward();

    setState(() {
      state = 1;
    });

    //Timer(Duration(milliseconds: 3300), () {
    //setState(() {
    //state = 3;
    //});
    //});
  }

  Widget buildButtonChild() {
    print(state);
    if (state == 0) {
      return Text(
        btnText,
        style: TextStyle(color: Colors.white, fontSize: 16.0),
      );
    } else if (state == 1) {
      return SizedBox(
        height: 36.0,
        width: 36.0,
        child: CircularProgressIndicator(
          value: null,
          valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
        ),
      );
    } else if (state == 2) {
      return Icon(Icons.check, color: Colors.white);
    } else {
      Timer(Duration(milliseconds: 5300), () {
        var controller = AnimationController(
            duration: Duration(microseconds: 2000), vsync: this);
        _animation = Tween(begin: 1.0, end: 0.0).animate(controller)
          ..addListener(() {
            setState(() {});
          });

        controller.forward();
      });

      return Icon(Icons.close, color: Colors.white);
    }
  }
}

Это еще один класс, где я вызвал кнопку прогресса:

class HomePage extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<HomePage> {
  int x = 3;
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      backgroundColor: Colors.white,
      body: new Center(
        child: ProgressButton(
          text: 'Bassey',
          state: x,
          onPressed: () {
            setState(() {
              x = 2;

              ProgressButton.of(context).state = 2;
            });
          },
        ),
      ),
    );
  }
}

В классе HomePage я попытался изменить состояние кнопки, добавив переменную с именем state и передав ее в свойство состояния ProgressButton, которое сработало, но проблема заключается в его изменении. при каждом нажатии кнопки ProgressButton я помещаю функцию setstate, которая изменяет номер переменных состояния на другое, но на этот раз оно не меняет визуальные элементы кнопки.

Как мне изменить состояние кнопки с внешнего класса?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...