如何在 Flutter 中添加加载屏幕

How do I add loading screen in Flutter

我正在制作一个带有 flutter 的应用程序,我想要一个加载屏幕,同时从 firestore 获取数据我曾经在 android 中通过 setvisibilty 执行此操作。我是 flutter 的新手,我不会不知道该怎么做 我在堆栈上看到了一些问题,但它们似乎没有帮助 full

如果 firebaseUser 不是 null,我想显示加载屏幕, 这是我的initState方法

  void initState() {
    super.initState();
    isRegistered();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        padding: EdgeInsets.all(32),
        child: Form(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Text("Login"),
              SizedBox(
                height: 16,
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: <Widget>[
                  Container(
                    width: 50,
                    child: TextFormField(
                      maxLength: 4,
                      keyboardType: TextInputType.number,
                      controller: countryCodeController,
                      decoration: InputDecoration(
                        hintText: '+251',
                      ),
                    ),
                  ),
                  Container(
                    width: 200,
                    child: TextFormField(
                      maxLength: 9,
                      keyboardType: TextInputType.number,
                      controller: phonenumberController,
                      decoration: InputDecoration(
                        hintText: '912345678',
                      ),
                    ),
                  ),
                ],
              ),
              SizedBox(
                height: 16,
              ),
              Container(
                width: double.infinity,
                child: FlatButton(
                    child: Text('Login'),
                    color: Colors.white,
                    padding: EdgeInsets.all(16),
                    onPressed: () {
                      final phoneNumber = countryCodeController.text.trim() + phonenumberController.text.trim();
                      if(phonenumberController.text.trim().length == 9 || countryCodeController.text.trim().length == 4){
                        loginUser(phoneNumber, context);
                      }else{
                        Fluttertoast.showToast(msg: "wronge input");
                      }
                    }),
              )
            ],
          ),
        ),
      ),
    );
  }
  void isRegistered() async{
    FirebaseAuth firebaseAuth = FirebaseAuth.instance;
    final FirebaseUser firebaseUser = await firebaseAuth.currentUser();
    final snapShot = await Firestore.instance.collection("users").document(
        firebaseUser.uid).get();
    if (firebaseUser != null) {
      if (snapShot.exists) {
        Navigator.pushReplacement(
            context,
            MaterialPageRoute(
                builder: (context) => HomePage(
                  firebaseUser: firebaseUser,
                )));
      }else{
      }
    }
  }
}

你可以这样做

   class RootScreenSM extends StatefulWidget {
      @override
      _RootScreenSMState createState() => _RootScreenSMState();
    }
    
    class _RootScreenSMState extends State<RootScreenSM> {
      @override
      Widget build(BuildContext context) {
        return StreamBuilder<FirebaseUser>(
          stream: FirebaseAuth.instance.onAuthStateChanged,
          builder: (BuildContext context, snapshot) {
            if (snapshot.connectionState == ConnectionState.waiting) {
              return new Container(
                color: Colors.white,
            //customize container look and feel here
              );
            } else {
              if (snapshot.hasData) {
                return  HomePage(
                     firebaseUser: snapshot.data,
                    );
              } else {
                return
                    notloggedin();
              }
            }
         },
      );
    }

看看我为你创建的这个例子:

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  bool _isLoading = false; // This is initially false where no loading state
  List<Timings> timingsList = List();



  @override
  void initState() {
    super.initState();
    dataLoadFunction(); // this function gets called
  }

  dataLoadFunction() async {
    setState(() {
      _isLoading = true; // your loader has started to load
    });
    // fetch you data over here
    setState(() {
      _isLoading = false; // your loder will stop to finish after the data fetch
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: _isLoading
            ? CircularProgressIndicator() // this will show when loading is true
            : Text('You widget tree after loading ...') // this will show when loading is false
      ),
    );
  }
}

如果有效请告诉我

您可以尝试创建一个这样的小部件组件并将其保存为名称 progress.dart

import 'package:flutter/material.dart';

Container circularProgress() {
  return Container(
    alignment: Alignment.center,
    padding: EdgeInsets.only(top: 10.0),
    child: CircularProgressIndicator(
      strokeWidth: 2.0,
      valueColor: AlwaysStoppedAnimation(primaryColor), //any color you want
    ),
  );
}

然后导入 progress.dart 并创建一个单独的容器

Container loadingScreen() {
    return circularProgress();
  }

然后将您的代码更改为:

        class RootScreenSM extends StatefulWidget {
      @override
      _RootScreenSMState createState() => _RootScreenSMState();
    }
    
    class _RootScreenSMState extends State<RootScreenSM> {
      @override
      Widget build(BuildContext context) {
        return StreamBuilder<FirebaseUser>(
          stream: FirebaseAuth.instance.onAuthStateChanged,
          builder: (BuildContext context, snapshot) {
            if (snapshot.connectionState == ConnectionState.waiting) {
              return loadingScreen();  // Container that you just created
            } else {
              if (snapshot.hasData) {
                return  HomePage(
                     firebaseUser: snapshot.data,
                    );
              } else {
                return
                    notloggedin();
    
              }
            }
        },
    );
  }

您可以试试这个方法,如果有效请告诉我们

我用flutter_spinkit做动画。
flutter_spinkit 包是一组带有 flutter 动画的加载指示器。
这里是加载小部件:

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

class Loading extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.white,
      child: Center(
        child: SpinKitFadingCube(
          color: Colors.lightGreen[100],
          size: 50.0
        )
      )
    );
  }
}

然后,在您的小部件中,您需要:

import '[yourpath]/loading.dart';

bool loading = false;

@override
  Widget build(BuildContext context) {
    return loading ? Loading() : Scaffold(
      body: Container(...

无论你的点击事件在哪里,你都应该将加载状态设置为TRUE:

setState(() => loading = true)

回调在哪里,你应该将状态设置回FALSE:

setState(() => loading = false)