簡體   English   中英

Flutter:AppBar 中的旋轉同步圖標

[英]Flutter: Spinning sync icon in AppBar

如何為放置在 AppBar 中的 IconButton 設置動畫? 同步圖標應該在數據庫同步運行時旋轉。

class _HomePageState extends State<HomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Dashboard"),
        actions: <Widget>[
          IconButton(
            icon: Icon(Icons.sync), // <-- Icon
            onPressed: () {
              print("sync");
              // start spinning
              syncDatabaseFull(); // Returns future and resolves when sync is finish
            },
          )
        ],
      ),
      body: Center(
        child: RaisedButton(
          child: Text('HOME screen'),
          onPressed: () {
          },
        ),
      ),
    );
  }
}

您可以在下面復制粘貼運行完整代碼
您可以擴展AnimatedWidget並傳遞callback
下面的示例代碼模擬syncDatabaseFull運行 5 秒

代碼片段

class AnimatedSync extends AnimatedWidget {
  VoidCallback callback;
  AnimatedSync({Key key, Animation<double> animation, this.callback})
      : super(key: key, listenable: animation);

  Widget build(BuildContext context) {
    final Animation<double> animation = listenable;
    return Transform.rotate(
      angle: animation.value,
      child: IconButton(
          icon: Icon(Icons.sync), // <-- Icon
          onPressed: () => callback()),
    );
  }
}

actions: <Widget>[
      AnimatedSync(
        animation: rotateAnimation,
        callback: () async{
          controller.forward();
          await syncDatabaseFull();
          controller.stop();
          controller.reset(); 
        },
      ),
    ],

工作演示

在此處輸入圖像描述

完整代碼

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class AnimatedSync extends AnimatedWidget {
  VoidCallback callback;
  AnimatedSync({Key key, Animation<double> animation, this.callback})
      : super(key: key, listenable: animation);

  Widget build(BuildContext context) {
    final Animation<double> animation = listenable;
    return Transform.rotate(
      angle: animation.value,
      child: IconButton(
          icon: Icon(Icons.sync), // <-- Icon
          onPressed: () => callback()),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

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

class _MyHomePageState extends State<MyHomePage>
    with SingleTickerProviderStateMixin {
  AnimationController controller;
  Animation colorAnimation;
  Animation rotateAnimation;

  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  Future<bool> syncDatabaseFull() async{
    await Future.delayed(Duration(seconds: 5), () {

    });
    return Future.value(true);
  }

  @override
  void initState() {
    controller =
        AnimationController(vsync: this, duration: Duration(seconds: 200));
    rotateAnimation = Tween<double>(begin: 0.0, end: 360.0).animate(controller);

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
        actions: <Widget>[
          AnimatedSync(
            animation: rotateAnimation,
            callback: () async{
              controller.forward();
              await syncDatabaseFull();
              controller.stop();
              controller.reset();
            },
          ),
        ],
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}

定制SpinningIconButton class

import 'package:flutter/material.dart';

class SpinningIconButton extends AnimatedWidget {
  final VoidCallback onPressed;
  final IconData iconData;
  final AnimationController controller;
  SpinningIconButton({Key key, this.controller, this.iconData, this.onPressed})
      : super(key: key, listenable: controller);

  Widget build(BuildContext context) {
    final Animation<double> _animation = CurvedAnimation(
      parent: controller,
      // Use whatever curve you would like, for more details refer to the Curves class
      curve: Curves.linearToEaseOut,
    );

    return RotationTransition(
      turns: _animation,
      child: IconButton(
        icon: Icon(iconData),
        onPressed: onPressed,
      ),
    );
  }
}

如何使用它:

class _HomePageState extends State<HomePage> with SingleTickerProviderStateMixin {
  AnimationController _animationController;

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

    _animationController = AnimationController(
      vsync: this,
      duration: const Duration(seconds: 1)
    );
  }

  @override
  Widget build(BuildContext context) {
    ...
        actions: <Widget>[
          SpinningIconButton(
            controller: _animationController,
            iconData: Icons.sync,
            onPressed: () async {
              // Play the animation infinitely
              _animationController.repeat();

              // Sleep 1.5 seconds or await the Async method
              print('Something has finished.');

              // Complete current cycle of the animation
              _animationController.forward(from: _animationController.value);
            },
          )
        ],
    ...
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM