Sobes.tech
Junior — Middle

Kā pārvaldīt animāciju, izmantojot AnimationController jūsu lietotnē?

sobes.tech AI

Atbilde no AI

Flutter tiek, animācijas pārvaldībai tiek izmantota klase AnimationController. Tā ļauj sākt, apturēt, atkārtot un kontrolēt animācijas progresu.

Galvenie soļi:

  1. Izveidojiet AnimationController widgeta stāvoklī (parasti initState metodē), norādot animācijas ilgumu un vsync (resursu optimizācijai).
  2. Izmantojiet kontroliera metodes: forward(), reverse(), repeat(), stop() animācijas pārvaldībai.
  3. Pierakstieties izmaiņām animācijas vērtībā, izmantojot addListener, lai atjauninātu UI.
  4. Neaizmirstiet atbrīvot resursus, izsaucot dispose() widgeta dispose metodē.

Piemērs:

class MyAnimatedWidgetState extends State<MyAnimatedWidget> with SingleTickerProviderStateMixin {
  late AnimationController _controller;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
      duration: const Duration(seconds: 2),
      vsync: this,
    )..addListener(() {
        setState(() {}); // atjaunina UI, kad mainās animācija
      });
    _controller.forward(); // sāk animāciju
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Opacity(
      opacity: _controller.value, // vērtība no 0.0 līdz 1.0
      child: YourWidget(),
    );
  }
}