【问题标题】:Flutter: How to override opacity value inside a child widget?Flutter:如何覆盖子小部件内的不透明度值?
【发布时间】:2021-03-16 07:29:09
【问题描述】:

是否可以覆盖子小部件内的不透明度值?

我有一个项目列表,根据非活动状态,我将它们设置为部分透明。

ListView.builder(
  itemBuilder:(c,i) {
    if(status) return MyCard(active:status);
    else return Opacity(opacity: 0.5, child: MyCard(active: status);
  },
  itemCount: 5,
);

但是现在,所有的小部件,无论是活动的还是非活动的,都需要显示一个完全可见的下载按钮。

class MyCard extends StatelessWidget{
  ///
  Widget build(c){
    return Column(
      children:[
        WidgetA(),
        WidgetB(),

        // this should be always fully visible.
        // Can we override the parent's opacity property somehow?
        DownloadButton(), 
      ]
    );
  }
}

使用 Opacity 可以实现这种行为吗?还是我需要分别访问每个子项?

【问题讨论】:

    标签: flutter flutter-opacity


    【解决方案1】:

    WidgetAWidgetB 包装在Column 中,其父级为Opacity

    import 'package:flutter/material.dart';
    
    void main() => runApp(MyApp());
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          home: Scaffold(
            body: ListView(
              children: <Widget>[
                MyCard(false),
                MyCard(true),
                MyCard(false),
              ],
            ),
          ),
        );
      }
    }
    
    class MyCard extends StatelessWidget {
      MyCard(this.status);
    
      final bool status;
    
      @override
      Widget build(BuildContext context) {
        return Column(
          children: <Widget>[
            Opacity(
              opacity: status ? 1 : 0.3,
              child: Column(
                children: const <Widget>[
                  Text('Widget A'),
                  Text('Widget B'),
                ],
              ),
            ),
            TextButton(
              onPressed: () {},
              child: const Text('DL Button'),
            ),
          ],
        );
      }
    }
    

    【讨论】:

      【解决方案2】:

      使用 Opacity 可以实现这种行为吗?

      没有

      或者我需要分别访问每个子项吗?

      是的

      您可以拆分不包含 DownloadButtonMyCard 小部件,然后仅将 Opacity 拆分为 MyCard

      【讨论】:

        猜你喜欢
        • 2013-08-28
        • 2014-03-20
        • 2016-09-28
        • 2011-02-08
        • 2013-01-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-11-12
        相关资源
        最近更新 更多