颤振|如何从不同的小部件更改小部件的颜色?

时间:2021-04-03 00:42:40

标签: flutter dart

我是 Flutter 新手,我什至不知道如何提问,希望您能理解我的问题。

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

我有 2 个小部件:

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

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

这是我的代码:

  • onItemTap() 方法用于 BottomNavigationBar

      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,
        ),
      );
  }
}

MultiChildLyoutDelegate 中的 CustomMultichildLayout 扩展 Svg.dart 的类

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;
  }   
}

2 个答案:

答案 0 :(得分:1)

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

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

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

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

Container 小部件具有 color 属性。

Container(
  color: colorParent,
)

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

ChildWidget(
  colorChild: colorParent,
)

当您想访问 colorChildStatefulWidget 属性时,您使用 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'),
    );
  }
}

答案 1 :(得分:0)

请更改默认选择器颜色值,请为包含任何颜色值的变量赋值,而 onTabItem 更改变量的值。

颜色_color = Colors.red;

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