How to Change Floating Action Button Color in Flutter?
Last Updated :
31 Oct, 2022
Every Android application has the floatingActionButton in it. There is a possibility that there are multiple screens in the application and have floatingActionButton on that screens, then we need to give the colors property to every floatingActionButton. But Flutter resolves this by changing the themeData class in the materialApp widget. Now we can set the properties globally of the floatingActionButton and these changes are reflected in every FloatingActionButton in the Flutter application. A sample video is given below to get an idea about what we are going to do in this article.
Step By Step Implementation
Step 1: Create a New Project in Android Studio
To set up Flutter Development on Android Studio please refer to Android Studio Setup for Flutter Development, and then create a new project in Android Studio please refer to Creating a Simple Application in Flutter.
Step 2: Locate the MaterialApp widget
Dart
class runMyApp extends StatefulWidget {
const runMyApp({super.key});
@override
State<runMyApp> createState() => _runMyAppState();
}
class _runMyAppState extends State<runMyApp> {
@override
Widget build(BuildContext context) {
return MaterialApp(
useMaterial3: true ,
),
title: 'FAB' ,
);
}
}
|
Step 3: Inside that, Locate the themeData class.
Dart
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false ,
theme: ThemeData(),
useMaterial3: true ,
),
title: 'FAB' ,
);
}
}
|
Step 4: Inside that, Add the floatingActionButtonTheme parameter and then assign FloatingActionButtonThemeData. And then add the properties of the color.
Dart
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false ,
theme: ThemeData(
primarySwatch: Colors.green,
floatingActionButtonTheme: const FloatingActionButtonThemeData(
backgroundColor: Colors.green,
foregroundColor: Colors.black,
hoverColor: Colors.red,
splashColor: Colors.white,
),
useMaterial3: true ,
),
title: 'FAB' ,
);
}
}
|
Code Example:
Dart
import 'package:flutter/material.dart' ;
void main() {
runApp( const runMyApp());
}
class runMyApp extends StatefulWidget {
const runMyApp({super.key});
@override
State<runMyApp> createState() => _runMyAppState();
}
class _runMyAppState extends State<runMyApp> {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false ,
theme: ThemeData(
primarySwatch: Colors.green,
floatingActionButtonTheme: const FloatingActionButtonThemeData(
backgroundColor: Colors.green,
foregroundColor: Colors.black,
hoverColor: Colors.red,
splashColor: Colors.white,
),
useMaterial3: true ,
),
title: 'FAB' ,
home: Scaffold(
appBar: AppBar(
title: Text( 'Floating Action Button' ),
),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.menu),
onPressed: (() {}),
),
),
);
}
}
|
Output:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...