Home > Enterprise >  Change Background Color of Elevated Button OnPressed in Flutter
Change Background Color of Elevated Button OnPressed in Flutter

Time:12-16

I need to change background color of elevated button, on click to indicate it as selected. I have tried this.

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

Here on onPressed(): The color is not changing

CodePudding user response:

On DartPad your code works Link to dartpad.
Be sure you implemented correctly the stateful widget:

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