future_builder.0.dart 2.61 KB
Newer Older
1 2 3 4 5 6
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'package:flutter/material.dart';

7
/// Flutter code sample for [FutureBuilder].
8

9
void main() => runApp(const FutureBuilderExampleApp());
10

11 12
class FutureBuilderExampleApp extends StatelessWidget {
  const FutureBuilderExampleApp({super.key});
13 14 15 16

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
17
      home: FutureBuilderExample(),
18 19 20 21
    );
  }
}

22 23
class FutureBuilderExample extends StatefulWidget {
  const FutureBuilderExample({super.key});
24 25

  @override
26
  State<FutureBuilderExample> createState() => _FutureBuilderExampleState();
27 28
}

29
class _FutureBuilderExampleState extends State<FutureBuilderExample> {
30 31 32 33 34 35 36 37
  final Future<String> _calculation = Future<String>.delayed(
    const Duration(seconds: 2),
    () => 'Data Loaded',
  );

  @override
  Widget build(BuildContext context) {
    return DefaultTextStyle(
38
      style: Theme.of(context).textTheme.displayMedium!,
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
      textAlign: TextAlign.center,
      child: FutureBuilder<String>(
        future: _calculation, // a previously-obtained Future<String> or null
        builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
          List<Widget> children;
          if (snapshot.hasData) {
            children = <Widget>[
              const Icon(
                Icons.check_circle_outline,
                color: Colors.green,
                size: 60,
              ),
              Padding(
                padding: const EdgeInsets.only(top: 16),
                child: Text('Result: ${snapshot.data}'),
54
              ),
55 56 57 58 59 60 61 62 63 64 65
            ];
          } else if (snapshot.hasError) {
            children = <Widget>[
              const Icon(
                Icons.error_outline,
                color: Colors.red,
                size: 60,
              ),
              Padding(
                padding: const EdgeInsets.only(top: 16),
                child: Text('Error: ${snapshot.error}'),
66
              ),
67 68 69 70 71 72
            ];
          } else {
            children = const <Widget>[
              SizedBox(
                width: 60,
                height: 60,
73
                child: CircularProgressIndicator(),
74 75 76 77
              ),
              Padding(
                padding: EdgeInsets.only(top: 16),
                child: Text('Awaiting result...'),
78
              ),
79 80 81 82 83 84 85 86 87 88 89 90 91
            ];
          }
          return Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: children,
            ),
          );
        },
      ),
    );
  }
}