2

在我的演示应用程序中,我需要从服务器加载一个 2 JSON 文件。两个 JSON 中都有大量数据。在我的 Flutter 应用程序中,我使用 Future + async + await 调用 json,而不是使用 runApp 创建小部件。在正文中,我尝试激活 CircularProgressIndicator。它显示 appBar 及其内容以及空白页面正文,并在 4 或 5 秒后加载实际正文中的数据。

我的问题是我需要先显示 CircularProgressIndicator,一旦数据加载,我将调用 runApp()。我怎么做?

// MAIN
void main() async {
    _isLoading = true;

  // Get Currency Json
  currencyData = await getCurrencyData();

  // Get Weather Json
  weatherData = await getWeatherData();

   runApp(new MyApp());
}



// Body
body: _isLoading ? 
new Center(child: 
    new CircularProgressIndicator(
        backgroundColor: Colors.greenAccent.shade700,
    )
) :
new Container(
    //… actual UI
)
4

1 回答 1

3

您需要将数据/或加载指示器放在脚手架内,每次无论您有没有数据,都显示脚手架,然后您可以做您想做的事情。

import 'dart:async';
import 'package:flutter/material.dart';

void main() {
  runApp(
    MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Hello Rectangle',
      home: Scaffold(
        appBar: AppBar(
          title: Text('Hello Rectangle'),
        ),
        body: HelloRectangle(),
      ),
    ),
  );
}

class HelloRectangle extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Center(
      child: Container(
        color: Colors.greenAccent,
        height: 400.0,
        width: 300.0,
        child: Center(
          child: FutureBuilder(
            future: buildText(),
            builder: (BuildContext context, AsyncSnapshot snapshot) {
              if (snapshot.connectionState != ConnectionState.done) {
               return CircularProgressIndicator(backgroundColor: Colors.blue);
              } else {
               return Text(
                  'Hello!',
                  style: TextStyle(fontSize: 40.0),
                  textAlign: TextAlign.center,
                );
              }
            },
          ),
        ),
      ),
    );
  }

  Future buildText() {
    return new Future.delayed(
        const Duration(seconds: 5), () => print('waiting'));
  }
}

`

于 2018-05-08T13:18:35.560 回答