Created
December 15, 2019 07:49
-
-
Save ysknsn/13bb6aa775dea88965cc20621a448b48 to your computer and use it in GitHub Desktop.
FutureBuilder Demo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:flutter/material.dart'; | |
void main() => runApp(MyApp()); | |
class MyApp extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
return MaterialApp( | |
title: 'FutureBuilder Demo', | |
theme: ThemeData( | |
primarySwatch: Colors.blue, | |
), | |
home: MyHomePage(), | |
); | |
} | |
} | |
class MyHomePage extends StatelessWidget { | |
MyHomePage({Key key}) : super(key: key); | |
Future<String> _getFutureValue() async { | |
// 擬似的に通信中を表現するために1秒遅らせる | |
await Future.delayed( | |
Duration(seconds: 1), | |
); | |
try { | |
/// 正常パターン | |
return Future.value("データの取得に成功しました"); | |
/// snapshot.hasDataがfalseになる | |
// return Future.value(null); | |
/// snapshot.hadErrorがtrueになる | |
// throw Exception("データの取得に失敗しました"); | |
} catch (error) { | |
return Future.error(error); | |
} | |
} | |
@override | |
Widget build(BuildContext context) { | |
return Scaffold( | |
appBar: AppBar( | |
title: Text('FutureBuilder Demo'), | |
), | |
body: Center( | |
child: FutureBuilder( | |
future: _getFutureValue(), | |
builder: (BuildContext context, AsyncSnapshot<String> snapshot) { | |
// 通信中はスピナーを表示 | |
if (snapshot.connectionState != ConnectionState.done) { | |
return CircularProgressIndicator(); | |
} | |
// エラー発生時はエラーメッセージを表示 | |
if (snapshot.hasError) { | |
return Text(snapshot.error.toString()); | |
} | |
// データがnullでないかチェック | |
if (snapshot.hasData) { | |
return Text(snapshot.data); | |
} else { | |
return Text("データが存在しません"); | |
} | |
}, | |
), | |
), | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment