【问题标题】:Change color and icon with provider使用提供者更改颜色和图标
【发布时间】:2020-04-24 11:06:52
【问题描述】:

我有一个有状态的小部件,它包含一个容器,我已经描述了它的颜色,它有一个图标。 我们如何通过提供者改变容器和图标的颜色?

Container(
      child: Icon(Icons.trash,
        size: 27,
      ),
      color: Colors.green[500],
    ),

这里我有单选按钮,其中我想要在容器中的颜色名称标题

RadioListTile(
title: Text('red'),
),
RadioListTile(
title: Text('green[500]'),
),
RadioListTile(
title: Text('blue'),
)

当用户点击这些图块时,我希望容器的颜色随着图标而相应改变。

我的实际代码。

background: Container(
      padding: EdgeInsets.only(top: 5, right: 380, bottom: 5),
      child: Icon(LineIcons.trash_o,
        size: 27,
      ),
      color: Colors.green[400],
    ),

下面的代码与上面的容器代码在不同的小部件中。

RadioButtonGroup(
            labels: <String>[
              'Delete',
              'Archive',
              'Mark as read/unread',
              'Move to',
              'None'
            ],
            orientation: GroupedButtonsOrientation.VERTICAL,
            itemBuilder: (radio, text, index){
              return Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: <Widget>[
                  text, radio,
                ],
              );
              },
            onSelected: (selected){
              setState(() {
                rightSwipeSelected = selected;

              });
              },
            picked: rightSwipeSelected,
          ),

我需要为所有不同的单选按钮设置不同的颜色。

【问题讨论】:

  • 你必须像这样调用 setState() :stackoverflow.com/questions/51904495/…
  • 请查看以下解决方案,如有疑问请告知
  • @codekls ,请检查以下更新的解决方案,如果有问题请告诉我
  • @codekls,您是否检查了以下更新的解决方案,如果有问题请告诉我

标签: flutter dart


【解决方案1】:

给你 确保从https://pub.dev/packages/provider#-installing-tab- 安装提供程序

Github上的源代码https://github.com/santoshanand/flutter-color-change-radio

演示https://www.loom.com/share/7edc6d5d2d6e45d9addb59ce3a63fc72

代码

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider(create: (_) => ChangeColorModel()),
      ],
      child: MaterialApp(
        title: 'Flutter Demo',
        theme: ThemeData(
          primarySwatch: Colors.blue,
        ),
        home: HomePage(),
      ),
    );
  }
}

class ChangeColorModel with ChangeNotifier {
  RadioListValue _value = new RadioListValue(0, Colors.green[500], "Green");
  RadioListValue get currentValue => _value;

  void chageModel(RadioListValue m) {
    _value = m;
    notifyListeners();
  }
}

class RadioListValue {
  final int key;
  final Color color;
  final String label;
  RadioListValue(this.key, this.color, this.label);
}

class HomePage extends StatelessWidget {
  final _buttonOptions = [
    RadioListValue(0, Colors.green[100], "Green"),
    RadioListValue(1, Colors.red, "Red"),
    RadioListValue(2, Colors.pink, "Pink"),
    RadioListValue(3, Colors.black38, "Black"),
    RadioListValue(4, Colors.yellow, "Yellow"),
    RadioListValue(5, Colors.brown, "Brown"),
  ];
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Home Page"),
      ),
      body: Consumer<ChangeColorModel>(builder: (context, model, _) {
        return Container(
          color: model.currentValue.color,
          child: ListView(
            padding: EdgeInsets.all(8.0),
            children: _buttonOptions
                .map(
                  (timeValue) => RadioListTile(
                    groupValue: model.currentValue.key,
                    title: Text(timeValue.label),
                    value: timeValue.key,
                    onChanged: (val) {
                      model.chageModel(_buttonOptions[val]);
                    },
                  ),
                )
                .toList(),
          ),
        );
      }),
    );
  }
}

【讨论】:

  • 谢谢,我正在寻找类似的东西,但对于新手来说,我遇到了一个复杂的问题。 RadioButtons 在一些有状态的小部件中,而容器在另一个小部件中。如何链接它们?
  • 类似于从设置页面更改颜色。
  • 为此,您需要在该类中使用Consumer&lt;ChangeColorModel&gt;(builder: (context, model, _) {}
【解决方案2】:

您可以只使用setState() 管理容器的颜色,并使用两个变量作为颜色和选中的复选框位置,在下面的代码中,我使用了“1”、“2”和“3”字符串值作为选择RadioListTile从中获取价值,请检查下面的代码

import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:image_picker/image_picker.dart';

class HomeScreen extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _HomeScreen();
  }
}

class _HomeScreen extends State<HomeScreen> {


  var selectedColor = Colors.grey;
  var selectedCheckBox = "";

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          backgroundColor: Colors.blue,
          title: Text(
            "HomeScreen",
            textAlign: TextAlign.center,
          ),
        ),
        body: SafeArea(
          top: true,
          bottom: true,
          child: Align(
            alignment: Alignment.center,
            child: Column(
              children: <Widget>[
                SizedBox(height: 20,),
                Container(
                  height: MediaQuery.of(context).size.height*0.2,
                  width: MediaQuery.of(context).size.width*0.4,
                  child: Icon(Icons.train,
                    size: 50,
                  ),
                  color: selectedColor,
                ),
                SizedBox(
                  height: 10.0,
                ),
                RadioListTile(
                  groupValue: selectedCheckBox == "" ? 0 :
                  selectedCheckBox == "1" ? true : false,
                  title: Text('Red'),
                  value: true,
                  onChanged: (val) {
                    setState(() {
                      selectedColor = Colors.red;
                      selectedCheckBox ="1";
                    });
                  },
                ),
                RadioListTile(
                  groupValue: selectedCheckBox == "" ? 0 :
                  selectedCheckBox == "2" ? true : false,
                  title: Text('Green'),
                  value: true,
                  onChanged: (val) {
                    setState(() {
                      selectedColor = Colors.green;
                      selectedCheckBox ="2";
                    });
                  },
                ), RadioListTile(
                  groupValue: selectedCheckBox == "" ? 0 :
                  selectedCheckBox == "3" ? true : false,
                  title: Text('Blue'),
                  value: true,
                  onChanged: (val) {
                    setState(() {
                      selectedColor = Colors.blue;
                      selectedCheckBox ="3";
                    });
                  },
                ),
              ],
            ),
          ),
        ));
  }
}

输出将在后面

【讨论】:

  • 我提到提供者是因为单选按钮和容器位于 2 个不同的小部件中。
  • 好的,给我点时间,早上会做
  • 谢谢,我已经用我的实际代码更新了这个问题,我希望这能更好地解决这个问题。我正在为单选按钮使用grouped_buttons 包,但如果需要,我也可以使用本机语法。
  • 好的,给我一些时间,今天会回复你
  • @codekls 我理解您的要求是您想要更改所选单选按钮的 RadioButtonGroup 的颜色以及容器颜色
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-08-22
  • 2021-08-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-25
相关资源
最近更新 更多