将状态从异步任务返回给FutureBuilder

时间:2020-05-26 20:05:56

标签: flutter dart flutter-layout

我想在异步任务运行时将状态从FutureBuilder返回。
任务为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,
                    ))

1 个答案:

答案 0 :(得分:0)

如果没有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!"),
        ));
  }
}