在Flutter中一个接一个地更改多个按钮的颜色 [英] Change color of multiple buttons one after the other in Flutter

查看:35
本文介绍了在Flutter中一个接一个地更改多个按钮的颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在单击执行"按钮时,我希望按钮1变为红色.然后转回白色.然后,按钮2应该变成红色& ;;然后恢复为白色.然后是3、4,依此类推.

On clicking the Go button I want button 1 to turn red. Then turn back white. Then button 2 should turn red & then reverts back to white. Then 3, 4 and so on.

我可以设计回叫按钮,使按钮1变为红色.我不确定,如何在2秒后将其恢复为白色?然后将下一个按钮变成红色&等等.

I can design my callback button such that button 1 turns red. I am not sure, how to turn it back to white after 2 second & then turn the next button red & so on.

main.dart

main.dart

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  final String apptitle = 'Test';

  Widget _goButtonClickCallback() {
    print("hello world. go tapped");
    // How do I control animation inside numListBuilder() from here? 
  }

  @override
  Widget build(BuildContext context) {
    var numList = [
      "1",
      "2",
      "3",
      "4",
      "5",
      "6",
      "7",
      "8",
    ];

    return MaterialApp(
      title: apptitle,
      theme: ThemeData(
        primarySwatch: Colors.deepOrange,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: Scaffold(
          appBar: AppBar(
            title: Text(apptitle),
          ),
          body: Column(
            children: [
              NumberListBuilder(numList),
              SizedBox(height: 110),
              GoButton(_goButtonClickCallback)
            ],
          )),
    );
  }
}

NumberListBuilder.dart

NumberListBuilder.dart

import 'package:flutter/material.dart';

class NumberListBuilder extends StatefulWidget {
  final List<String> numberList;
  const NumberListBuilder(this.numberList);

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

class _NumberListBuilderState extends State<NumberListBuilder> {
  List<TableRow> getButtonRows() {
    // list for all rows
    List<TableRow> rows = [];
    int numCols = 2;
    int numberListLength = widget.numberList.length;
    int numRows = 4

    var k = 0;
    for (var i = 0; i < numRows; i++) {
      List<Widget> rowChildren = [];
      for (var j = 0; j < numCols; j++) {
        rowChildren.add(Container(
            height: 80.0,
            child: FlatButton(
              color: Colors.white70,
              onPressed: () {},
              child: Text(
                widget.numberList[k++],
                style: TextStyle(
                  fontSize: 20.0,
                ),
              ),
            )));
      }
      rows.add(new TableRow(children: rowChildren));
    }
    return rows;
  }

  @override
  Widget build(BuildContext context) {
    return new Container(
      child: new Table(
        border: TableBorder.all(),
        children: getButtonRows(),
      ),
    );
  }
}

推荐答案

因此,为了简单地解释这一点,您需要每2秒重新绘制一次整个网格,并在该build方法中,设置一个条件,确定要绘制的框用红色涂成白色.

So to explain this simply, you need to redraw your entire grid every 2 seconds, and in that build method, put a condition as to which box it will paint in red and which to paint white.

问题是您有另一个类来绘制框,但是您想从主类中控制它的绘制方式.可以这样做,但是很麻烦,最好将它们放在同一个类中.我为你做了.

The problem is that you have another class drawing your boxes, but you want to control how it does so from the main class. This can be done but its messy, better to put them into same class. I have done this for you.

免责声明:有更好的更有效的方法来执行此操作,但这应该使您入门,因为我所做的更改尽可能少.

Disclaimer: There are better more efficient ways of doing this, but this should get you started since I changed as little as possible.

我更改的内容:

  1. 盒子绘图类我添加了条件 color:k == numberToHighlight-1吗?Colors.red:Colors.white70 ,这只是检查该框是否应突出显示为红色,否则应突出显示为白色.

  1. Box drawing class I added conditional color: k == numberToHighlight-1 ? Colors.red : Colors.white70, this just checks if the box should be highlighted red otherwise its white.

将框的整个内部版本移到主类中,以便可以轻松修改状态.我基本上只是用与您的类相同的名称创建了一个框的方法.

Moved the entire build of boxes into main class so that the state can be modified easily. I basically just made a method with same name as your class that built boxes.

添加的状态 int numberToHighlight = 0;

添加了一个方法,该方法会在延迟一段时间后调用自身,直到将所有框涂上颜色,然后停止自行调用并将其值重置为0.

Added a method that calls itself after a delay until its colored all the boxes, then stops calling itself and resets the value to 0.

将GoButton更改为FlatButton(因为您尚未共享该代码),这不是问题.

Changed GoButton into FlatButton (because you have not shared that code) this isn't a problem.

这是所有有效的代码(对您的代码进行的最小更改):

Here is the entire code that works (minimal changes to yours):

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {

      final String apptitle = 'Test';
    
      int numberToHighlight = 0;
    
      var numList = [
          "1",
          "2",
          "3",
          "4",
          "5",
          "6",
          "7",
          "8",
        ];
    
      void _goButtonClickCallback() {
        print("hello world. go tapped setting ${numberToHighlight}");
            
        if(numberToHighlight < numList.length)
        {
          setState(() {
            numberToHighlight++;
          });
          Future.delayed(const Duration(seconds: 2), _goButtonClickCallback);
        }
        else
        {
          setState(() {
            numberToHighlight = 0;
          });
        }
      }
    
      @override
      Widget build(BuildContext context) {
    
        List<TableRow> getButtonRows() {
          // list for all rows
          List<TableRow> rows = [];
          int numCols = 2;
          int numberListLength = numList.length;
          int numRows = 4;
    
          var k = 0;
          for (var i = 0; i < numRows; i++) {
            List<Widget> rowChildren = [];
            for (var j = 0; j < numCols; j++) {
              rowChildren.add(Container(
                  height: 80.0,
                  child: FlatButton(
                    color: k == numberToHighlight-1 ? Colors.red : Colors.white70,
                    onPressed: () {},
                    child: Text(
                      numList[k++],
                      style: TextStyle(
                        fontSize: 20.0,
                      ),
                    ),
                  )));
            }
            rows.add(new TableRow(children: rowChildren));
          }
          return rows;
        }
    
        Widget numberListbuilder()
        {
          return new Container(
          child: new Table(
            border: TableBorder.all(),
            children: getButtonRows(),
          ),
        );
        }
    
        return MaterialApp(
          title: apptitle,
          theme: ThemeData(
            primarySwatch: Colors.deepOrange,
            visualDensity: VisualDensity.adaptivePlatformDensity,
          ),
          home: Scaffold(
              appBar: AppBar(
                title: Text(apptitle),
              ),
              body: Column(
                children: [
                  numberListbuilder(),
                  SizedBox(height: 110),
                  FlatButton(
                    onPressed: _goButtonClickCallback,
                    child: Text("GO!"),
                    color: Colors.blue,
                  )
                ],
              )),
        );
    }
}

这篇关于在Flutter中一个接一个地更改多个按钮的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆