How to create animated loading button in Flutter

Mon, May 1, 2023

Read in 1 minutes

In this blog post we will learn how to create an animated loading button in flutter without any external package.

How to create animated loading button in Flutter

In our main.dart file we have the usual main function which runs MyApp widget that returns MaterialApp with theme and body widget. All of our code for loading button will be inside HomeScreen widget.

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

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      theme: ThemeData.light().copyWith(
        colorScheme: ColorScheme.fromSwatch(
          primarySwatch: Colors.amber,
        ),
      ),
      home: const HomeScreen(),
    );
  }
}

Let’s create another file with the name of home_screen.dart for our HomeScreen widget and put this code for the animated loading button.

import 'package:flutter/material.dart';
import 'package:widget_explore/loading_button.dart';

class HomeScreen extends StatefulWidget {
  const HomeScreen({super.key});

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  bool load = false;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Flutter Loading Button"),
      ),
      body: Center(
        child: ElevatedButton(
          style: ElevatedButton.styleFrom(
            disabledBackgroundColor: Colors.white,
            fixedSize: const Size(200.0, 50.0),
            shape: RoundedRectangleBorder(
              side: const BorderSide(color: Colors.amber),
              borderRadius: BorderRadius.circular(50),
            ),
          ),
          child: load
              ? const SizedBox(
                  height: 30,
                  width: 30,
                  child: CircularProgressIndicator(),
                )
              : Text("Load"),
          onPressed: load ? null : startLoad,
        ),
      ),
    );
  }

  startLoad() async {
    setState(() {
      load = true;
    });

    await Future.delayed(Duration(seconds: 3));
    setState(() {
      load = false;
    });
  }
}

Shohruh AK





See Also

How to publish Flutter app on Play Store: Beginner guide
How to Create Dotted Border Container in Flutter
FocusableActionDetector Flutter Widget: How to use it
How to Use 'sqflite_ffi' Database Package in Flutter
What Skills a Flutter Developer Should Have