How to Create a Download Button in Flutter?



Apps are brimming with buttons that carry out long-running actions. A button, for example, could initiate a download, which initiates the download process, receives data over time, and ultimately grants access to the downloaded content.


talented Flutter developers for hire


The steps involved in the process of creating a download button in the flutter development app are mentioned below:


Defining a new Stateful widget

Defining the possible visual states of the button

Display the shape of the button

Creating the display of the button’s text

Display a spinner while fetching the download

Display the progress percentage and a stop button while downloading

Add callbacks to button taps

1. Defining a new stateful widget


stateless widget

class DownloadButton extends StatelessWidget {
const DownloadButton({
super.key,
});
@override
Widget build(BuildContext context) {
// TODO:
return const SizedBox();
}
}

2. Defining the possible visual states of the button


The current download status determines the visual display of the download button. After Defining the download’s possible states, update DownloadButton to accept a DownloadStatus and specify the duration for how long the button should fly from one visual state to the next.


When designing a custom widget, you must select whether it receives all necessary information from its parent or if the Widget orchestrates the application’s activity internally. DownloadButton, for example, might get the existing DownloadStatus from its parent, or it may coordinate the download process within its State object.


Rather than managing behavior within the Widget, the ideal solution for most widgets is to transfer relevant information into it from its parent. You assure increased utility for the Widget, simpler testing, and future modifications to application behavior by handing in all essential information.

enum DownloadStatus {
notDownloaded,
fetchingDownload,
downloading,
downloaded,
}

3. Display the shape of the button

The form of the download button varies depending on the download state. During the notDownloaded and downloaded phases, the button shows a gray, rounded rectangle. During the fetchingDownload and downloading stages, the button shows a translucent circle.


In the next step, Create an AnimatedContainer with a ShapeDecoration that shows a rounded rectangle or a circle based on the current DownloadStatus.


create a StatelessWidget or a StatefulWidget


Now, the AnimatedContainer appears to be just a SizedBox child, but you don’t need to worry; we will resolve this state in another step.

@immutable
classButtonShapeWidget extends StatelessWidget {
constButtonShapeWidget({
super.key,
requiredthis.isDownloading,
requiredthis.isDownloaded,
requiredthis.isFetching,
requiredthis.transitionDuration,
});
final bool isDownloading;
final bool isDownloaded;
final bool isFetching;
final Duration transitionDuration;
@override
Widget build(BuildContext context) {
var shape = constShapeDecoration(
shape: StadiumBorder(),
color: CupertinoColors.lightBackgroundGray,
);
if (isDownloading || isFetching) {
shape = ShapeDecoration(
shape: constCircleBorder(),
color: Colors.white.withOpacity(0.0),
);
}
return AnimatedContainer(
duration: transitionDuration,
curve: Curves.ease,
width: double.infinity,
decoration: shape,
child: constSizedBox(),
);
}
}

4. Creating the display of the button’s text


Different messages are displayed through the Download button in its different phases. The notDownloaded phase displays the GET option. The downloaded phases display the OPEN option for the users, while no text is displayed in the intermediate process.


opacitywrapper widget

return AnimatedContainer(
duration: transitionDuration,
curve: Curves.ease,
width: double.infinity,
decoration: shape,
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 6),
child: AnimatedOpacity(
duration: transitionDuration,
opacity: isDownloading || isFetching ? 0.0 : 1.0,
curve: Curves.ease,
child: Text(
isDownloaded ?'OPEN' : 'GET',
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.button?.copyWith(
fontWeight: FontWeight.bold,
color: CupertinoColors.activBlue,
),
),
),
),
);

5. Display a spinner while fetching the download

The DownloadButton shows a radial spinner while fetchingDownload is in progress. This spinner transitions from notDownloaded to fetchingDownload.

Install a radial spinner on top of the button form that fades in and out at appropriate intervals.

ButtonShapeWidgetStack widget

@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: _onPressed,
child: Stack(
children: [
ButtonShapeWidget(
transitionDuration: transitionDuration,
isDownloaded: _isDownloaded,
isDownloading: _isDownloading,
isFetching: _isFetching,
),
Positioned.fill(
child: AnimatedOpacity(
duration: transitionDuration,
opacity: _isDownloading || _isFetching ? 1.0 : 0.0,
curve: Curves.ease,
child: ProgressIndicatorWidget(
downloadProgress: downloadProgress,
isDownloading: _isDownloading,
isFetching: _isFetching,
),
),
),
],
),
);
}

6. Display the progress percentage and a stop button while downloading


Following the retrieval, the downloading step is exactly that. The DownloadButton transforms the radial progress spinner with a rising radial progress bar during the downloading period. A stop button symbol is also displayed on the DownloadButton, allowing the user to halt an ongoing download.


After adding an advancement property to the DownloadButton plugin, change the progress display to a radial toolbar during the downloading phase. Then, place a stop button icon in the center of the radial progress bar.

@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: _onPressed,
child: Stack(
children: [
ButtonShapeWidget(
transitionDuration: transitionDuration,
isDownloaded: _isDownloaded,
isDownloading: _isDownloading,
isFetching: _isFetching,
),
Positioned.fill(
child: AnimatedOpacity(
duration: transitionDuration,
opacity: _isDownloading || _isFetching ? 1.0 : 0.0,
curve: Curves.ease,
child: Stack(
alignment: Alignment.center,
children: [
ProgressIndicatorWidget(
downloadProgress: downloadProgress,
isDownloading: _isDownloading,
isFetching: _isFetching,
),
if (_isDownloading)
const Icon(
Icons.stop,
size: 14.0,
color: CupertinoColors.activeBlue,
),
],
),
),
),
],
),
);
}

7. Add callbacks to button taps


The button behavior is the final thing that your DownloadButton requires. When the user clicks the button, it must do some action. Add callbacks for starting a download, canceling a download, and opening a download to the widget properties.

GestureDetector widget

void _onPressed() {
switch (status) {
case DownloadStatus.notDownloaded:
onDownload();
break;
case DownloadStatus.fetchingDownload:
// do nothing.
break;
case DownloadStatus.downloading:
onCancel();
break;
case DownloadStatus.downloaded:
onOpen();
break;
}
}

Now at the end of the process, you have a button that displays different information based on whatever phase it is in: not downloaded, seeking download, downloading phase, and downloaded completely. The user may tap to initiate a download, stop an ongoing download, and access a finished download by tapping.


Let’s see a full example of DownloadButton:

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
void main() {
runApp(
const MaterialApp(
home: ExampleDownloadButton(),
debugShowCheckedModeBanner: false,
),
);
}
@immutable
class ExampleDownloadButton extends StatefulWidget {
const ExampleDownloadButton();
@override
_ExampleDownloadButtonState createState() => _ExampleDownloadButtonState();
}
class _ExampleDownloadButtonState extends State<exampledownloadbutton> {
late final List<downloadcontroller> _downloadControllers;
@override
void initState() {
super.initState();
_downloadControllers = List<downloadcontroller>.generate(
10,
(index) => SimulatedDownloadController(onOpenDownload: () {
_openDownload(index);
}),
);
}
void _openDownload(int index) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Open PDF ${index + 1}'),
),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Download Button')),
body: ListView.separated(
itemCount: _downloadControllers.length,
separatorBuilder: (_, __) => const Divider(),
itemBuilder: _buildListItem,
),
);
}
Widget _buildListItem(BuildContext context, int index) {
final theme = Theme.of(context);
final downloadController = _downloadControllers[index];
return ListTile(
leading: const Icon(Icons.list_rounded),
title: Text(
'Pdf ${index + 1}',
overflow: TextOverflow.ellipsis,
style: theme.textTheme.headline6,
),
trailing: SizedBox(
width: 96,
child: AnimatedBuilder(
animation: downloadController,
builder: (context, child) {
return DownloadButton(
status: downloadController.downloadStatus,
downloadProgress: downloadController.progress,
onDownload: downloadController.startDownload,
onCancel: downloadController.stopDownload,
onOpen: downloadController.openDownload,
);
},
),
),
);
}
}
enum DownloadStatus {
notDownloaded,
fetchingDownload,
downloading,
downloaded,
}
abstract class DownloadController implements ChangeNotifier {
DownloadStatus get downloadStatus;
double get progress;
void startDownload();
void stopDownload();
void openDownload();
}
class SimulatedDownloadController extends DownloadController
with ChangeNotifier {
SimulatedDownloadController({
DownloadStatus downloadStatus = DownloadStatus.notDownloaded,
double progress = 0.0,
required VoidCallback onOpenDownload,
}) : _downloadStatus = downloadStatus,
_progress = progress,
_onOpenDownload = onOpenDownload;
DownloadStatus _downloadStatus;
@override
DownloadStatus get downloadStatus => _downloadStatus;
double _progress;
@override
double get progress => _progress;
final VoidCallback _onOpenDownload;
bool _isDownloading = false;
@override
void startDownload() {
if (downloadStatus == DownloadStatus.notDownloaded) {
_doSimulatedDownload();
}
}
@override
void stopDownload() {
if (_isDownloading) {
_isDownloading = false;
_downloadStatus = DownloadStatus.notDownloaded;
_progress = 0.0;
notifyListeners();
}
}
@override
void openDownload() {
if (downloadStatus == DownloadStatus.downloaded) {
_onOpenDownload();
}
}
Future<void> _doSimulatedDownload() async {
_isDownloading = true;
_downloadStatus = DownloadStatus.fetchingDownload;
notifyListeners();
// Wait a second to simulate fetch time.
await Future<void>.delayed(const Duration(seconds: 1));
// If the user chose to cancel the download, stop the simulation.
if (!_isDownloading) {
return;
}
// Shift to the downloading phase.
_downloadStatus = DownloadStatus.downloading;
notifyListeners();
const downloadProgressStops = [0.0, 0.15, 0.45, 0.8, 1.0];
for (final stop in downloadProgressStops) {
// Wait a second to simulate varying download speeds.
// await Future<void>.delayed(const Duration(seconds: 1));
if (!_isDownloading) {
return;
}
_progress = stop;
notifyListeners();
}
await Future<void>.delayed(const Duration(seconds: 1));
if (!_isDownloading) {
return;
}
_downloadStatus = DownloadStatus.downloaded;
_isDownloading = false;
notifyListeners();
}
}
@immutable
class DownloadButton extends StatelessWidget {
const DownloadButton({
required this.status,
this.downloadProgress = 0.0,
required this.onDownload,
required this.onCancel,
required this.onOpen,
this.transitionDuration = const Duration(milliseconds: 500),
});
final DownloadStatus status;
final double downloadProgress;
final VoidCallback onDownload;
final VoidCallback onCancel;
final VoidCallback onOpen;
final Duration transitionDuration;
bool get _isDownloading => status == DownloadStatus.downloading;
bool get _isFetching => status == DownloadStatus.fetchingDownload;
bool get _isDownloaded => status == DownloadStatus.downloaded;
void _onPressed() {
switch (status) {
case DownloadStatus.notDownloaded:
onDownload();
break;
case DownloadStatus.fetchingDownload:
// do nothing.
break;
case DownloadStatus.downloading:
onCancel();
break;
case DownloadStatus.downloaded:
onOpen();
break;
}
}
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: _onPressed,
child: Stack(
children: [
ButtonShapeWidget(
transitionDuration: transitionDuration,
isDownloaded: _isDownloaded,
isDownloading: _isDownloading,
isFetching: _isFetching,
),
Positioned.fill(
child: AnimatedOpacity(
duration: transitionDuration,
opacity: _isDownloading || _isFetching ? 1.0 : 0.0,
curve: Curves.ease,
child: Stack(
alignment: Alignment.center,
children: [
ProgressIndicatorWidget(
downloadProgress: downloadProgress,
isDownloading: _isDownloading,
isFetching: _isFetching,
),
if (_isDownloading)
const Icon(
Icons.stop,
size: 14,
color: CupertinoColors.activeBlue,
),
],
),
),
),
],
),
);
}
}
@immutable
class ButtonShapeWidget extends StatelessWidget {
const ButtonShapeWidget({
key,
required this.isDownloading,
required this.isDownloaded,
required this.isFetching,
required this.transitionDuration,
});
final bool isDownloading;
final bool isDownloaded;
final bool isFetching;
final Duration transitionDuration;
@override
Widget build(BuildContext context) {
var shape = const ShapeDecoration(
shape: StadiumBorder(),
color: CupertinoColors.lightBackgroundGray,
);
if (isDownloading || isFetching) {
shape = ShapeDecoration(
shape: const CircleBorder(),
color: Colors.white.withOpacity(0),
);
}
return AnimatedContainer(
duration: transitionDuration,
curve: Curves.ease,
width: double.infinity,
decoration: shape,
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 6),
child: AnimatedOpacity(
duration: transitionDuration,
opacity: isDownloading || isFetching ? 0.0 : 1.0,
curve: Curves.ease,
child: Text(
isDownloaded ? 'OPEN' : 'GET',
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.button?.copyWith(
fontWeight: FontWeight.bold,
color: CupertinoColors.activeBlue,
),
),
),
),
);
}
}
@immutable
class ProgressIndicatorWidget extends StatelessWidget {
const ProgressIndicatorWidget({
key,
required this.downloadProgress,
required this.isDownloading,
required this.isFetching,
});
final double downloadProgress;
final bool isDownloading;
final bool isFetching;
@override
Widget build(BuildContext context) {
return AspectRatio(
aspectRatio: 1,
child: TweenAnimationBuilder<double>(
tween: Tween(begin: 0, end: downloadProgress),
duration: const Duration(milliseconds: 200),
builder: (context, progress, child) {
return CircularProgressIndicator(
backgroundColor: isDownloading
? CupertinoColors.lightBackgroundGray
: Colors.white.withOpacity(0),
valueColor: AlwaysStoppedAnimation(isFetching
? CupertinoColors.lightBackgroundGray
: CupertinoColors.activeBlue),
strokeWidth: 2,
value: isFetching ? null : progress,
);
},
),
);
}
}</double></void></void></void></void></downloadcontroller></downloadcontroller></exampledownloadbutton>

Output

GIF




Conclusion

Flutter Agency for Flutter business app development


Source: https://flutteragency.com/create-download-button-flutter/

4.7 Star App Store Review!
Cpl.dev***uke
The Communities are great you rarely see anyone get in to an argument :)
king***ing
Love Love LOVE
Download

Select Collections