【问题标题】:Flutter - How to expand a widget with animation?Flutter - 如何用动画扩展小部件?
【发布时间】:2021-08-18 03:32:19
【问题描述】:

所以我有以下代码

Row(
  children: [
    IconButton(), // IconButton1
    Expanded(
      child: Container(
        child: Textfield(),
      ),
    ),
    IconButton(), // IconButton2
  ]
)

当我在文本字段中输入内容时,我希望删除 IconButton1,并且文本字段容器或文本字段本身通过动画展开以占用该 IconButton1 的空间。我可以做到这一点,但我不能用动画做到这一点。

我尝试了 AnimatedContainer 和 AnimatedSwitcher,但它们没有按预期工作。

【问题讨论】:

    标签: android flutter user-interface dart


    【解决方案1】:

    如果它是一个简单的容器,你应该使用 AnimatedContainer。 否则你应该使用scale transition

    import 'package:flutter/material.dart';
    
    class TestScreen extends StatefulWidget {
      @override
      _TestScreenState createState() => _TestScreenState();
    }
    
    class _TestScreenState extends State<TestScreen> {
      final items = List<int>.generate(20, (i) => i + 1);
    
      @override
      Widget build(BuildContext context) {
        final title = 'Dismissing Items';
    
        return MaterialApp(
          title: title,
          theme: ThemeData(
            primarySwatch: Colors.blue,
          ),
          home: Scaffold(
            appBar: AppBar(
              title: Text(title),
            ),
            body: ListView.builder(
              itemCount: items.length,
              itemBuilder: (context, index) {
                final item = items[index];
                return Dismissible(
                  key: Key(item.toString()),
                  onDismissed: (direction) {
                    setState(() {
                      items.removeAt(index);
                    });
    
                    ScaffoldMessenger.of(context).showSnackBar(
                      SnackBar(
                        content: Text('$item dismissed'),
                      ),
                    );
                  },
                  background: Container(color: Colors.yellow),
                  child: AnimatedContainer(
                    height: 1200 / items.length,
                    width: MediaQuery.of(context).size.width,
                    duration: Duration(milliseconds: 300),
                    child: Text('$item'),
                    color: (items[index] % 2 == 0) ? Colors.green : Colors.red,
                  ),
                );
              },
            ),
          ),
        );
      }
    }
    

    【讨论】:

    • 问题是Containerwidth没有在Container里面定义。 Container 被放入 Expanded 小部件中,以便它采用它可以的宽度。现在的事情是,当我删除行中的一个组件时,“扩展”会扩展容器。这是我想要某种动画的地方,因为到目前为止,它只是在没有任何预期的动画的情况下扩展。
    • 检查代码,我已经用代码 sn-p 编辑了我的答案。
    • 谢谢,但这不是我要找的。如果您阅读我的问题,您会看到我想要 2 个 IconButtons、一个文本字段、另外 1 个 IconButton,这 4 个元素连续。当我在文本字段中输入内容时,前 2 个 IconButtons 应该消失,并且文本字段应该水平扩展以占用被删除的那些 2 IconButtons 的空间。您还可以查看我提供的代码,以便您了解我要构建的 Widget 树。
    猜你喜欢
    • 2019-06-10
    • 1970-01-01
    • 1970-01-01
    • 2021-11-11
    • 2019-07-15
    • 2020-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多