現在 App 應用幾乎都會連線網路,於是非同步取得資料是必備的執行方式,在 Flutter 我們可以使用 FutureBuilder Widget。😎
這是個極其重要的 Widget,我們馬上來看怎麼實做~
/*
Author: HappyMan
Date: 2022/02/14
Topic: FutureBuilder<T> class
*/
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
final Future<String> _getData = Future<String>.delayed(
Duration(seconds: 5),
() => 'Data Loaded',
);
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Happy Future Builder'),
),
body: FutureBuilder<String>(
future: _getData,
builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
List<Widget> children;
if (snapshot.hasData) {
children = [
Icon(
Icons.check_circle,
color: Colors.green,
size: 60,
),
Padding(
padding: EdgeInsets.only(top: 26),
child: Text('Result: ${snapshot.data}'),
)
];
} else if (snapshot.hasError) {
children = [
Icon(
Icons.error_outline,
color: Colors.red,
size: 60,
),
Padding(
padding: EdgeInsets.only(top: 26),
child: Text('Error: ${snapshot.error}'),
)
];
} else {
children = [
SizedBox(
width: 60,
height: 60,
child: CircularProgressIndicator(),
),
Padding(
padding: EdgeInsets.only(top: 26),
child: Text('Awaiting result...'),
)
];
}
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: children,
),
);
}
),
),
);
}
}
我們先用 Future.delayed 的方式,來模擬從網路取得資料的過程,在此期間我設定為 5 秒。
執行結果,一開始是最上截圖的等待階段(設定字串:Awaiting result…),五秒後便轉變為成功階段(回傳字串:Data Loaded),如下截圖。
參考:
FutureBuilder (Flutter Widget of the Week)
隨意留個言吧:)~