【问题标题】:How to change the color of a Widget based on a different Widget?如何根据不同的 Widget 改变 Widget 的颜色?
【发布时间】:2021-06-29 18:21:24
【问题描述】:

我正在尝试制作显示SvgPicture.assets() 的简单应用程序,用户可以使用颜色选择器更改SvgPicture() 的颜色。

我有 2 个小部件:

  1. 用于显示 SvgPicture() 将其称为 Svg.dart
  2. main.dart 包含 BottomNavigationView,其中一个选项卡打开颜色选择器,Svg.dart

我在使用setState(() {}) 时遇到了一些错误,但我设法以某种方式修复了错误,但它并没有改变颜色,当我尝试更改main.dart 的背景颜色时,它工作得很好。

这是我的代码:

  • BottomNavigationBaronItemTap() 方法

      void _onItemTap(int index) {
      setState(() {
        if (index == 0) {
        // First Tab
        }
        if (index == 1) {
        // SecondTab
        }
        if (index == 2) {
        // Third Tab
        }
        if (index == 3) {
          showDialog(
            context: context,
            builder: (BuildContext context){
              return AlertDialog(
                content:
                SingleChildScrollView(
                  child: new ColorPicker(
                    pickerColor: Colors.red,
                    onColorChanged: (Color colorChanged) {
                      color = colorChanged;
               // (color) is assigned default value of Colors.red
               // here I'm trying to assign new value to (color)
                    },
                  ),//ColorPicker
                ),//SingleChildScrollView
              );//AlertDialog
            });
        }
      });
    }
    
  • 然后在Svg.dart 中我创建了另一个变量Color picked = Colors.red 并将红色指定为默认值。这就是Svg.dart 小部件代码的样子:

      Widget build(BuildContext context) {
      setState(() {
        picked = main().createState().color;
      });
      return CustomMultiChildLayout(
        delegate: TempDelegate(
            position: Offset.zero
        ),
        children: [
          buildLayoutId(ids.shirtId, MyConstants.shirt, picked)
        ],
      );
    }
    LayoutId buildLayoutId(Object id, String item, Color color) {
      return LayoutId(
          id: id,
          child: SvgPicture.asset(
            item,
            color: color,
          ),
        );
    }
    

我尝试寻找颤振文档,但我真的不知道问题是如何/在哪里,也没有找到教程,请帮助

编辑

这是main.dart

    class Main extends StatefulWidget{
      @override
      _MainState createState() => _MainState();
    }
    
    class _Main extends State<Main> {
      int _slectedIndex = 0;
      Color color = MyConstants.darkWhite;
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          backgroundColor: Colors.black,
          body: Center(
            child: Svg(),
          ),
          bottomNavigationBar: BottomNavigationBar(
            items: const<BottomNavigationBarItem>[
              BottomNavigationBarItem(
                label: "",
                icon: Icon(Icons.home),
              ),
              BottomNavigationBarItem(
                label: "",
                icon: Icon(Icons.home),
              ),
              BottomNavigationBarItem(
                label: "",
                icon: Icon(Icons.home),
              ),
              BottomNavigationBarItem(
                label: "",
                icon: Icon(Icons.home),
              ),
            ],
            onTap: _onItemTap,
          ),
        );
      }
    
      void _onItemTap(int index) {
        setState(() {
          if (index == 0) {
    // do something
          }
          if (index == 1) {
    // do something
          }
    
          if (index == 2) {
    // do something
          }
    
          if (index == 3) {
            showDialog(
              context: context,
              builder: (BuildContext context){
                return AlertDialog(
                  content:
                  SingleChildScrollView(
                    child: new ColorPicker(
                      pickerColor: Colors.red,
                      onColorChanged: (Color colorChanged) {
                        setState(() {
                          color = colorChanged;
                        });
                      },
                    ),
                  ),
                );
              });
          }
        });
      }
    }

Svg.dart

class Svg extends StatefulWidget{
  //Color picked;
  @override
  SvgState createState() => Svg();
}

class SvgState extends State<Svg> {
  @override
  Widget build(BuildContext context) {
    return CustomMultiChildLayout(
      delegate: SvgDelegate(
          position: Offset.zero
      ),
      children: [
        buildLayoutId(ids.shirtId, MyConstants.shirt, CreateKit().createState().color)
      ],
    );
  }
  LayoutId buildLayoutId(Object id, String item, Color color) {
    return LayoutId(
        id: id,
        child: SvgPicture.asset(
          item,
          color: color,
        ),
      );
  }
}

Svg.dart 中为CustomMultichildLayout 扩展MultiChildLyoutDelegate 的类

class SvgDelegate extends MultiChildLayoutDelegate{
  final Offset position;
  SvgDelegate({
    this.position
});
  @override
  void performLayout(Size size) {

    Size leadSize = Size.zero;
    itemLayout(leadSize, size, ids.shirtId);
  }    
  void itemLayout(Size leadSize, Size size, Object id) {
    if(hasChild(id)){
      leadSize = layoutChild(
        id,
        BoxConstraints.loose(size),
      );
    }
  }    
  @override
  bool shouldRelayout(TempDelegate oldDelegate) {
    return oldDelegate.position != position;
  }   
}

【问题讨论】:

  • 如果svgBottomNavigationBarmain 中,color = colorChanged; 应该被 setState 包围。我认为您不需要在svg 中使用picked,全局变量color 就可以了。你能分享main的代码吗?
  • 你能分享你完整的 StatefulWidget 代码吗?顺便说一句,在构建期间不要使用setState((){})
  • @EdwardLi 我应用了更改并分享了编辑后的代码,请查看。
  • @Gilang 我不确定是否理解你,我是 noop 哈哈

标签: flutter dart


【解决方案1】:

在 Flutter 中,一切都是小部件,您可以创建自己的自定义小部件。 同样,还有层次结构和状态等概念。

无状态小部件是 StatelessWidget,例如标签、背景、标题或其他任何东西。

有状态的小部件是 StatefulWidget,它是可以变化的东西,例如开关、动画背景、页面等。还有一个 InheritedWidget,但这是另一个主题。

setStateStatefulWidget 中用于更新that 小部件的状态,要从父级更新子级,可以使用子级的属性。 当setState 被调用时,它会在必要时重建小部件及其子部件。

Container 小部件具有 color 属性。

Container(
  color: colorParent,
)

您的自定义小部件还可以具有任何属性,例如 colorsizecolorChild

ChildWidget(
  colorChild: colorParent,
)

当你想访问StatefulWidgetcolorChild 属性时,你使用widget.colorChild,当它没有状态时,你可以简单地使用colorChild

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData.dark(),
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        appBar: AppBar(),
        body: Center(
          child: Parent(),
        ),
      ),
    );
  }
}

class Parent extends StatefulWidget {
  @override
  ParentState createState() => ParentState();
}

class ParentState extends State<Parent> {

  // Define the color in parent
  Color colorParent = Colors.red;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: Center(
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: [

            // Pass the color as a property

            ChildWidget(colorChild: colorParent),
            VerticalDivider(color: colorParent),
            Child2Widget(colorChild: colorParent),
          ],
        ),
      ),
      bottomNavigationBar: BottomNavigationBar(
        items: const <BottomNavigationBarItem>[
          BottomNavigationBarItem(
            label: "Tap to Blue",
            icon: Icon(Icons.home),
          ),
          BottomNavigationBarItem(
            label: "Tap to Orange",
            icon: Icon(Icons.dashboard),
          ),
          BottomNavigationBarItem(
            label: "Tap to Green",
            icon: Icon(Icons.palette),
          ),
          // ...
        ],
        onTap: _onItemTap,
      ),
    );
  }

  void _onItemTap(index) {
    // ...
    switch (index) {
      case 0:
        setState(() {
          
          // Update color in parent
          colorParent = Colors.blue;
        });
        break;
      case 1:
        setState(() {
          colorParent = Colors.orange;
        });
        break;
      case 2:
        setState(() {
          colorParent = Colors.green;
        });
        break;
    }
  }
}

class ChildWidget extends StatefulWidget {

  // Define color in child
  final Color colorChild;

  const ChildWidget({Key key, this.colorChild}) : super(key: key);

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

class ChildWidgetState extends State<ChildWidget> {
  @override
  Widget build(BuildContext context) {
    return Container(
      height: 100,
      width: 100,
      // Use it
      color: widget.colorChild,
      child: Text('Child 1'),
    );
  }
}

class Child2Widget extends StatelessWidget {

  // Define color in child
  final Color colorChild;

  const Child2Widget({Key key, this.colorChild}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return Container(
      height: 100,
      width: 100,

      // Use it
      color: colorChild,
      child: Text('Child 2'),
    );
  }
}

【讨论】:

  • 成功了!非常感谢你,现在我对颤振的工作原理有了更好的理解。我还有一个问题要了解无状态/完整,当 colorParent 更改时,无状态和有状态小部件颜色都会发生变化,是不是因为 Parent 在每次点击时都会以不同的颜色重建,因此子小部件会跟随父小部件并重建?因为我对它构建一次的无状态小部件的理解就是这样。再次感谢您的解释,这非常有帮助
  • 不客气!,是的,你是对的,statelessWidget 不会重建自己,也就是说,无状态的任何内部操作都不会重建它(这就是为什么 MyApp 是无状态的),但在这种情况下,有一个外部 parent 代理会杀死它(哎哟!)并创建一个新代理。但是,如果要创建不重新构建的小部件,可以在任何小部件之前添加const(这对性能非常有用),但您不能再在其参数中传递变量,只能传递常量。
【解决方案2】:

请更改默认选择器颜色值,请分配包含任何颜色值的变量,onTabItem 更改该变量的值。

颜色_color = Colors.red;

ColorPicker(pickerColor: _color, onColorChanged: (Color colorChanged) { setState(() => _color = colorChanged;},),

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-08
    • 1970-01-01
    • 2022-06-10
    • 2019-11-27
    • 1970-01-01
    • 2013-06-08
    相关资源
    最近更新 更多