flutter 更改在扑动中按下的升高按钮的背景颜色

pgvzfuti  于 2022-12-19  发布在  Flutter
关注(0)|答案(1)|浏览(126)

我需要改变背景颜色的高架按钮,点击,以表明它作为选定的。我已经尝试了这一点。

class _MyState extends State<MyPage> {
  bool _flag = true;
    @override
      Widget build(BuildContext context) {
        return Scaffold(
          body: Center(
            child: ElevatedButton(
              onPressed: () => setState(() => _flag = !_flag),
              child: Text(_flag ? 'Red' : 'Green'),
              style: ElevatedButton.styleFrom(
                backgroundColor: _flag ? Colors.red : Colors.teal, 
              ),
            ),
          ),
        );
      }
    }

此处为onPressed():颜色没有变化

ssm49v7z

ssm49v7z1#

在DartPad上,您的代码可以Link to dartpad工作。
确保正确实现了有状态小部件:

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {

  const MyHomePage({
    Key? key,
  }) : super(key: key);

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
   bool _flag = true;
    @override
      Widget build(BuildContext context) {
        return Scaffold(
          body: Center(
            child: ElevatedButton(
              onPressed: () => setState(() => _flag = !_flag),
              child: Text(_flag ? 'Red' : 'Green'),
              style: ElevatedButton.styleFrom(
                backgroundColor: _flag ? Colors.red : Colors.teal, 
              ),
            ),
          ),
        );
      }
}

相关问题