Search code examples
flutterflutter-animation

Flutter - How to Make floating action button animation like gmail?


I am able to make quite a similar floating action button animation like Gmail app, but I am getting a little bit of margin when I isExpanded is false. Any solution?

Here is my code

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

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  bool isExpanded = false;

  Widget build(context) {
    return Scaffold(
        floatingActionButton: AnimatedContainer(
          width: isExpanded ? 150 : 56,
          height: 56,
          duration: Duration(milliseconds: 300),
          child: FloatingActionButton.extended(
            onPressed: () {},
            icon: Icon(Icons.ac_unit),
            label: isExpanded ? Text("Start chat") : SizedBox(),
          ),
        ),
        appBar: AppBar(),
        body: FlatButton(
            onPressed: () {
              setState(() {
                isExpanded = !isExpanded;
              });
            },
            child: Text('Press here to change FAB')));
  }
}

Solution

  • Looks like FloatingActionButton has some hardcoded padding set for an icon. To fix that, you could do the following:

    FloatingActionButton.extended(
      onPressed: () {},
      icon: isExpanded ? Icon(Icons.ac_unit) : null,
      label: isExpanded ? Text("Start chat") : Icon(Icons.ac_unit),
    )