In this example, I'm going to share the code which will show a CircularProgressIndicator when a Button is clicked and return the results to the screen once the operations are completed.
This is how the final output is going to look.
Below is an example code of how to Show CircularProgressIndicator on Button Click in Flutter. Code from Main.dart file. In order to run this project locally, all you need to do is to create a Project and copy paste the below code to Lib\main.dart file.
import 'dart:async'; import 'package:flutter/material.dart'; Future<string> fetchStr(int vi) async { if (vi >= 1) { await new Future.delayed(const Duration(seconds: 1), () {}); return 'Hello World ' + vi.toString(); } return null; } void main() => runApp(MyApp()); class MyApp extends StatefulWidget { @override _MyAppState createState() => _MyAppState(); } class _MyAppState extends State<myapp> { int visible = 0; @override Widget build(BuildContext context) { return MaterialApp( title: 'Loader Example', theme: ThemeData( primarySwatch: Colors.blue, ), home: Scaffold( appBar: AppBar( title: Text('Fetch Data Example'), ), body: Center( child: Column( children: <widget>[ Padding( padding: EdgeInsets.symmetric(vertical: 100.0), ), RaisedButton( onPressed: () { setState(() { visible++; }); }, child: Text('Click here to Load'), ), Padding( padding: EdgeInsets.symmetric(vertical: 10.0), ), StringWidget(str: fetchStr(visible), vi: visible), ], ), ), ), ); } } class StringWidget extends StatelessWidget { final Future<string> str; final int vi; const StringWidget({Key key, this.str, this.vi}) : super(key: key); @override Widget build(BuildContext context) { return Center( child: FutureBuilder<string>( future: str, builder: (context, AsyncSnapshot<string> snapshot) { switch (snapshot.connectionState) { case ConnectionState.none: return Text('Press button to start.'); case ConnectionState.active: case ConnectionState.waiting: return CircularProgressIndicator(); case ConnectionState.done: if (snapshot.hasError) return Text('Error: ${snapshot.error}'); else if (snapshot.hasData) return Text('${snapshot.data}'); else return Text('Press button to start.'); } return Text('Press button to start.'); // unreachable }, ), ); } }Hope this is helpful to you.
Thanks,
Srikanth