Flutter异步编程详解,GitHub标星过万
Flutter中的异步编程通常涉及到Future
和async/await
。以下是一个简单的例子,展示了如何在Flutter中使用异步编程来获取网络数据:
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
home: AsyncHomePage(),
);
}
}
class AsyncHomePage extends StatefulWidget {
AsyncHomePage({Key key}) : super(key: key);
@override
_AsyncHomePageState createState() => _AsyncHomePageState();
}
class _AsyncHomePageState extends State<AsyncHomePage> {
String _data = "Loading...";
Future<void> _fetchData() async {
final response = await http.get(Uri.parse('https://example.com/api'));
if (response.statusCode == 200) {
setState(() {
_data = response.body;
});
} else {
setState(() {
_data = "Error: ${response.statusCode}";
});
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Async Programming Example"),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(_data),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _fetchData,
tooltip: 'Fetch Data',
child: Icon(Icons.update),
),
);
}
}
在这个例子中,_fetchData
方法被标记为async
,这意味着它可以使用await
关键字等待一个Future
完成。当按下FloatingActionButton时,将调用_fetchData
方法,它会异步获取数据,并在获取到数据后使用setState
更新用户界面。这是在Flutter中实现异步编程的一个常见模式。
评论已关闭