flutter:动画&状态管理 (十三)

简介: 本文档介绍了Flutter中`animatedList`的使用方法和状态管理的示例。`animatedList`用于创建带有动画效果的列表,示例代码展示了如何添加、删除列表项,并执行相应的动画效果。状态管理部分通过一个简单的点击切换颜色的示例,演示了如何在Flutter中管理组件的状态。

前言

在构建现代用户界面的应用中,流畅的动画和有效的状态管理是提升用户体验的重要因素。Flutter提供了强大的工具来实现这些功能,其中AnimatedList是一个用于创建带有动画效果的动态列表的组件。本文档将详细介绍AnimatedList的使用方法,并通过示例代码展示如何添加和删除列表项,同时实现相应的动画效果。

此外,状态管理在Flutter中也至关重要,能够帮助我们在用户交互时保持界面的响应性和一致性。本文还将提供一个简单的示例,演示如何通过点击事件切换组件的颜色,展现Flutter中状态管理的基本思路。

动画

animatedList

bool flag = true;
  final _globalkey = GlobalKey<AnimatedListState>();
  List<String> list = ["第一条", "第二条"];
  Widget _buildItem(index) {
    return ListTile(
      key: ValueKey(index),
      trailing: IconButton(
        icon: Icon(Icons.delete),
        onPressed: () {
          //  调用 删除
          _deleteItem(index);
        },
      ),
      title: Text(list[index]),
    );
// 删除 方法
  _deleteItem(index) {
    if (flag) {
      flag = false;
      //    通过 全局 变量 来 操作
      _globalkey.currentState!.removeItem(index, (context, animation) {
        var removeItem = _buildItem(index);
        list.removeAt(index);
        //  执行 动画
        return FadeTransition(
          opacity: animation,
          // 执行 动画 的元素
          child: removeItem,
        );
      });
    }
Timer.periodic(Duration(milliseconds: 500), (timer) {
      //  当 为 false  时  无法 删除
      flag = true;
      timer.cancel();
    });
@override
  Widget build(BuildContext context) {
    return Scaffold(
        floatingActionButton: FloatingActionButton(
          child: Icon(Icons.add),
          onPressed: () {
            setState(() {
              list.add("我是新增的数据");
              //  向后 加 值
              _globalkey.currentState!.insertItem(list.length - 1);
            });
          },
        ),
        appBar: AppBar(
          title: Text("title"),
        ),
        body: AnimatedList(
          key: _globalkey,
          //  初始化 的 长度 为  list.length
          initialItemCount: list.length,
          itemBuilder:
              (BuildContext context, int index, Animation<double> animation) {
            return FadeTransition(
              opacity: animation,
              child: _buildItem(index),
            );
          },
        ));
  }
import 'dart:async';
import 'package:flutter/material.dart';
class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);
  @override
  State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: test(),
    );
  }
}
class test extends StatefulWidget {
  const test({Key? key}) : super(key: key);
  @override
  State<test> createState() => _testState();
}
class _testState extends State<test> {
  //  防抖
  bool flag = true;
  final _globalkey = GlobalKey<AnimatedListState>();
  List<String> list = ["第一条", "第二条"];
  Widget _buildItem(index) {
    return ListTile(
      key: ValueKey(index),
      trailing: IconButton(
        icon: Icon(Icons.delete),
        onPressed: () {
          //  调用 删除
          _deleteItem(index);
        },
      ),
      title: Text(list[index]),
    );
  }
  // 删除 方法
  _deleteItem(index) {
    if (flag) {
      flag = false;
      //    通过 全局 变量 来 操作
      _globalkey.currentState!.removeItem(index, (context, animation) {
        var removeItem = _buildItem(index);
        list.removeAt(index);
        //  执行 动画
        return FadeTransition(
          opacity: animation,
          // 执行 动画 的元素
          child: removeItem,
        );
      });
    }
    Timer.periodic(Duration(milliseconds: 500), (timer) {
      //  当 为 false  时  无法 删除
      flag = true;
      timer.cancel();
    });
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        floatingActionButton: FloatingActionButton(
          child: Icon(Icons.add),
          onPressed: () {
            setState(() {
              list.add("我是新增的数据");
              //  向后 加 值
              _globalkey.currentState!.insertItem(list.length - 1);
            });
          },
        ),
        appBar: AppBar(
          title: Text("title"),
        ),
        body: AnimatedList(
          key: _globalkey,
          //  初始化 的 长度 为  list.length
          initialItemCount: list.length,
          itemBuilder:
              (BuildContext context, int index, Animation<double> animation) {
            return FadeTransition(
              opacity: animation,
              child: _buildItem(index),
            );
          },
        ));
  }
}
void main() {
  runApp(const MyApp());
}

状态管理

一个简单的Flutter应用,其中定义了一个状态管理的组件TapBoxA。该组件使用StatefulWidget来管理其内部状态,通过GestureDetector检测用户的点击操作。当用户点击方块时,_active状态会在true和false之间切换,从而改变方块的背景颜色:如果处于激活状态,方块的颜色为灰色;否则为浅绿色。同时,方块中间显示了文本“active”。该应用通过main函数运行,展示了如何在Flutter中创建交互式组件并管理其状态。

import 'package:flutter/material.dart';
class TapBoxA extends StatefulWidget{
  const TapBoxA({super.key});
  @override
  State<StatefulWidget> createState() =>_TapBoxAState();
}
class _TapBoxAState extends State<TapBoxA>{
  bool _active=false;
  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: (()=>
        setState(()=> _active = !_active)),
      child: Container(
        width: 200,
        height: 200,
        decoration: const BoxDecoration(
          // color: Colors.grey,
      color: _active ? Colors.grey : Colors.lightGreen,
        ),
        child: const Center(
          child: Text(
          // _active?'Active':'InActive',
            'active',
            style: TextStyle(fontSize: 32,color:Colors.white,),),
        ),
      ),
    );
  }
}
void main(List<String> args){
  runApp(const MaterialApp(
    title: 'myApp',
    home:TapBoxA(),
  ));
}
相关文章
|
5月前
|
存储 JavaScript 前端开发
盘点主流 Flutter 状态管理库2024
状态管理是每个应用不可缺少的,本文将会盘点下主流的状态管理包。
331 2
盘点主流 Flutter 状态管理库2024
|
2月前
|
前端开发
Flutter快速实现自定义折线图,支持数据改变过渡动画
Flutter快速实现自定义折线图,支持数据改变过渡动画
61 4
Flutter快速实现自定义折线图,支持数据改变过渡动画
|
2月前
Flutter 状态管理新境界:多Provider并行驱动UI
Flutter 状态管理新境界:多Provider并行驱动UI
56 0
|
2月前
|
Dart API
状态管理的艺术:探索Flutter的Provider库
状态管理的艺术:探索Flutter的Provider库
40 0
|
3月前
Flutter-实现头像叠加动画效果
Flutter-实现头像叠加动画效果
49 0
|
3月前
Flutter-加载中动画
Flutter-加载中动画
35 0
|
3月前
Flutter-自定义表情雨下落动画
Flutter-自定义表情雨下落动画
30 0
|
3月前
Flutter-数字切换动画
Flutter-数字切换动画
23 0
|
3月前
flutter的状态管理学习
flutter的状态管理学习
|
3月前
|
开发者
Flutter 动画学习
Flutter 动画学习