[flutter] Flutter에서 약간의 지연 후 코드를 실행하는 방법은 무엇입니까?

위젯이 빌드 된 후 일정 지연 후 함수를 실행하고 싶습니다. Flutter에서이를 수행하는 관용적 인 방법은 무엇입니까?

내가 달성하려는 것 : 기본 FlutterLogo위젯으로 시작한 다음 style일정 기간 후에 속성 을 변경하고 싶습니다 .



답변

Future.delayed잠시 후 코드를 실행 하는 데 사용할 수 있습니다 . 예 :

Future.delayed(const Duration(milliseconds: 500), () {

// Here you can write your code

  setState(() {
    // Here you can write your code for open new view
  });

});

setState 함수에서는 화면 데이터 새로 고침, 레이블 텍스트 변경 등과 같은 앱 UI와 관련된 코드를 작성할 수 있습니다.


답변

알아 냈어요 ?

class AnimatedFlutterLogo extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => new _AnimatedFlutterLogoState();
}

class _AnimatedFlutterLogoState extends State<AnimatedFlutterLogo> {
  Timer _timer;
  FlutterLogoStyle _logoStyle = FlutterLogoStyle.markOnly;

  _AnimatedFlutterLogoState() {
    _timer = new Timer(const Duration(milliseconds: 400), () {
      setState(() {
        _logoStyle = FlutterLogoStyle.horizontal;
      });
    });
  }

  @override
  void dispose() {
    super.dispose();
    _timer.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return new FlutterLogo(
      size: 200.0,
      textColor: Palette.white,
      style: _logoStyle,
    );
  }
}


답변

카운트 다운 후 작업 트리거

Timer(Duration(seconds: 3), () {
  print("Yeah, this line is printed after 3 seconds");
});

반복 동작

Timer.periodic(Duration(seconds: 5), (timer) {
  print(DateTime.now());
});

즉시 타이머 트리거

Timer(Duration(seconds: 0), () {
  print("Yeah, this line is printed immediately");
});


답변

위의 답변에 더 많은 설명을 추가하십시오.

타이머 기능은 아래의 지속 시간에서도 작동합니다.

const Duration(
      {int days = 0,
      int hours = 0,
      int minutes = 0,
      int seconds = 0,
      int milliseconds = 0,
      int microseconds = 0})

예:

  Timer(Duration(seconds: 3), () {
    print("print after every 3 seconds");
  });


답변

(구글의 최상위 결과이므로 이전 q에 대한 응답 추가)

블록 내의 콜백에서 새로운 상태를 생성하려고 시도했지만 작동하지 않았습니다. Timer 및 Future.delayed로 시도했습니다.

하지만 효과가 있었던 것은 …

await Future.delayed(const Duration(milliseconds: 500));

yield newState;

빈 미래를 기다렸다가 나중에 함수를 실행합니다.


답변

Future.delayed(Duration(seconds: 3) , your_function)


답변

1 Future.delayed과 2는 두 가지 방법으로 할 수 있습니다.Timer

타이머 사용

Timer 시간의 끝에 도달하면 작업을 트리거하도록 구성된 카운트 다운 타이머를 나타내는 클래스이며 한 번 또는 반복적으로 실행할 수 있습니다.

dart:async 사용할 프로그램을 시작 하려면 패키지 를 가져와야  합니다. Timer

Timer(Duration(seconds: 5), () {
  print(" This line is execute after 5 seconds");
});

Future.delayed 사용

Future.delayed 지연 후 계산을 실행하는 미래를 만듭니다.

import "dart:async"; 사용할 프로그램을 시작 하기 위해 패키지화  했는지 확인하십시오. Future.delayed

Future.delayed(Duration(seconds: 5), () {
   print(" This line is execute after 5 seconds");
});