我想把状态返回到 FutureBuilder
在async任务运行时,从它的。任务是 carProvider.run()
.
目前,在等待任务完成的过程中,出现了一个。CircularProgressIndicator
与下面的文字,显示消息字符串。而且我想不断更新这个消息字符串。
class CarDealerStatefulWidgetState extends State<CarDealerStatefulWidget> {
String _message = "Initialising database and fetching data...";
set setMessage(String message) => setState(() {
_message = message;
});
String get getMessage => _message;
static CarDataProvider carProvider = CarDataProvider();
Future<List<Car>> _requestResult = carProvider.run();
List<Car> items;
String path;
var currentPage;
Widget build(BuildContext context) {
PageController controller;
return DefaultTextStyle(
style: Theme.of(context).textTheme.headline2,
textAlign: TextAlign.center,
child: FutureBuilder<List<Car>>(
future: _requestResult,
builder: (BuildContext context, AsyncSnapshot<List<Car>> snapshot) {
Widget child;
if (snapshot.hasData) {
//
} else if (snapshot.hasError) {
child = Icon(
Icons.error_outline,
color: Colors.red,
size: 60,
);
} else {
child = Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
CircularProgressIndicator(
valueColor: AlwaysStoppedAnimation<Color>(Colors.green),
),
Padding(
padding: const EdgeInsets.only(top: 20.0),
),
Text(getMessage,
style: TextStyle(
fontSize: 13,
))
我会在不使用FutureProvider的情况下解决你的问题,而使用setState来代替。
查看这个工作示例。
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
bool _ready = false;
String _text = "";
void changeText(String text) {
setState(() {
_text = text;
});
}
void setReady(bool ready) {
setState(() {
_ready = ready;
});
}
@override
void initState() {
super.initState();
loadData();
}
Future loadData() async {
changeText("initializing...");
await Future.delayed(const Duration(milliseconds: 2000), () => {});
changeText("load settings...");
await Future.delayed(const Duration(milliseconds: 2000), () => {});
changeText("connect to database...");
await Future.delayed(const Duration(milliseconds: 2000), () => {});
changeText("init GUI...");
await Future.delayed(const Duration(milliseconds: 2000), () => {});
setReady(true);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: !_ready
? Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
CircularProgressIndicator(),
Text(_text),
],
)
: Text("OK ready!"),
));
}
}