页面加载之前的循环加载Flutter

时间:2020-04-11 14:54:46

标签: flutter sharedpreferences flutter-layout

我有一个小部件列表和一个函数,如果小部件列表为空,则该函数返回一个Container来告诉用户添加到列表中:

_isCountEmpty() {
      if (count == 0 || count == null) {
   //if no widgets in list
        return Container(
            color: Colors.black,
            child: Text('Press edit to start adding exercises',
                style: TextStyle(
                  fontSize: 40,
                  color: Colors.white,
                )));
      }
   //if widgets in list

      return ListView(
        children: children,
        scrollDirection: Axis.vertical,
      );
    }

获得计数的initState:

 void initState() {
getCount().then(updateCount);
super.initState(); }

使用共享的首选项从另一个页面接收计数值,这些首选项在我的initState中调用。在initState中接收到计数值之前,屏幕会认为count的值为null,因此仅在瞬间,在ListView之前将Container()返回。 取而代之的是,我希望在屏幕从initState获取count的值时显示圆形指示器,然后在获得count的值后返回Container或ListView

谢谢

1 个答案:

答案 0 :(得分:1)

您可以尝试以下代码,该代码将从共享的首选项中加载计数器,然后可以将文本小部件替换为所需的任何列表或容器,如果counter == 0 || counter == null

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

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  int counter;
  Future<SharedPreferences> prefs;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
          child: FutureBuilder(
        future: prefs,
        builder: (context, AsyncSnapshot<SharedPreferences> snapshot) {
          if (!snapshot.hasData) {
            return CircularProgressIndicator();
          } else {
            counter = snapshot.data.getInt("counter");
            //Replace with whatever widget you want
            return Text("Loading is done your counter is : $counter");
          }
        },
      )),
    );
  }

  @override
  void initState() {
    super.initState();
    prefs = SharedPreferences.getInstance();
  }
}
相关问题