【问题标题】:How to make button change color when go to page?转到页面时如何使按钮更改颜色?
【发布时间】:2022-08-19 15:59:36
【问题描述】:

这是我想要的设计:

这是我目前的设计:

您好,如何使按钮在按下时更改颜色并转到按下的页面。例如,当您按下配置文件按钮时,颜色会发生变化。当您转到另一个页面时,按钮的颜色将变为白色。谁能帮我?

这是我的代码:

ElevatedButton(
  style: ButtonStyle(
    padding: MaterialStateProperty.all(
      EdgeInsets.fromLTRB(30, 20, 30, 20),
    ),
    // overlayColor: MaterialStateProperty.all(Colors.red),
    backgroundColor: MaterialStateProperty.resolveWith<Color>(
      (Set<MaterialState> states) {
        if (states.contains(MaterialState.pressed))
          return Colors.blue;
        return Color.fromARGB(255, 0, 79, 143);
      }
    ),
  ),
  onPressed: () {},
  child: new Text(
    \'Profile\', 
    style: TextStyle(
      fontSize: 16,
      fontWeight: FontWeight.normal
    )
  ),
),

    标签: flutter dart


    【解决方案1】:
    class MyApp extends StatefulWidget {
      MyApp({Key? key}) : super(key: key);
    
      @override
      State<MyApp> createState() => _MyAppState();
    }
    
    class _MyAppState extends State<MyApp> {
      bool change = false;
    
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          home: Scaffold(
            body: Center(
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: [
                  ElevatedButton(
                    style: ElevatedButton.styleFrom(
                      primary: change ? Colors.blue : Colors.white,
                    ),
                    onPressed: () {
                      setState(() {
                        change = true;
                      });
                    },
                    child: Text('Profile',
                        style: TextStyle(
                            fontSize: 16,
                            fontWeight: FontWeight.normal,
                            color: change ? Colors.white : Colors.black)),
                  ),
                  ElevatedButton(
                    style: ElevatedButton.styleFrom(
                      primary: !change ? Colors.blue : Colors.white,
                    ),
                    onPressed: () {
                      setState(() {
                        change = false;
                      });
                    },
                    child: Text('Home',
                        style: TextStyle(
                            fontSize: 16,
                            fontWeight: FontWeight.normal,
                            color: !change ? Colors.white : Colors.black)),
                  ),
                ],
              ),
            ),
          ),
        );
      }
    }
    

    【讨论】:

    • 它不工作。
    • 获取我的代码并运行它,它将工作:)
    【解决方案2】:

    您可以考虑使用TabBar,它是为这些类型的导航而设计的。

    【讨论】:

      猜你喜欢
      • 2021-06-01
      • 2017-04-11
      • 2013-03-27
      • 2019-10-13
      • 1970-01-01
      • 1970-01-01
      • 2020-01-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多