提问者:小点点

如何在Flutter应用程序启动前显示CircularProgressIndicator?


在我的演示应用程序中,我需要从服务器加载一个2 JSON文件。这两个JSON都有大量数据。我使用Future+async+await调用json,而不是使用runapp创建小部件。在体内,我试图激活一个循环进程指示器。它显示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
)

共1个答案

匿名用户

您需要将数据/或加载指示器放在支架内,无论您是否有数据,每次都显示支架,然后里面的内容就可以做您想做的事情了

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'));
  }
}

`