How to Change Button Background Color in Flutter

The sample Google flutter code below illustrate how to change button background color in flutter.

The code is based on flutter version 1.0.0

Main.dart (App entry point)

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

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: Colors.blue,
      ),
      //home: MyHomePage(title: 'Flutter Demo Home Page'),
      home: ChangeButtonBackground(),
    );
  }
}
change_button_background.dart
import 'package:flutter/material.dart';

class ChangeButtonBackground extends StatefulWidget {
  @override
  ChangeButtonBackgroundState createState() {
    return new ChangeButtonBackgroundState();
  }
}

class ChangeButtonBackgroundState extends State<ChangeButtonBackground> {
  List<Color> _colors = [ //Get list of colors
    Colors.red,
    Colors.blue,
    Colors.brown,
    Colors.teal,
    Colors.purple
  ];

  int _currentIndex = 0;

  _onChanged() { //update with a new color when the user taps button
    int _colorCount = _colors.length;

    setState(() {
      if (_currentIndex == _colorCount - 1) {
        _currentIndex = 0;
      } else {
        _currentIndex += 1;
      }
    });

    //setState(() => (_currentIndex == _colorCount - 1) ? _currentIndex = 1 : _currentIndex += 1);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('Change Button Background color'),
        ),
        body: Center(
          child: RaisedButton(
            child: Text('Tap to change color'),
            onPressed: _onChanged,
            color: _colors[_currentIndex], //specify background color  of button from our list of colors
          ),
        ));
  }
}

flutter button background color

If you have any questions or suggestions kindly use the comment box or you can contact us directly through our contact page below.

 

Add a Comment