Tripping
Tripping

Reputation: 453

How do I add loading screen in Flutter

I am making an app with flutter and I want a loading screen while fetching data from firestore I used to do this in android by setvisibilty .I am new to flutter and I don't know how to do it I saw some questions on stack but they didn't seem to help full

I want to show the loading screen if firebaseUser is not null, this is my initState method

  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{
      }
    }
  }
}

Upvotes: 8

Views: 11585

Answers (4)

griffins
griffins

Reputation: 8246

You can do something like this

   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();
              }
            }
         },
      );
    }

Upvotes: 0

Joe
Joe

Reputation: 546

I use flutter_spinkit for the animation.
The package flutter_spinkit is a collection of loading indicators animated with flutter.
Here the Loading widget:

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

Then, from within your widgets, you need to:

import '[yourpath]/loading.dart';

bool loading = false;

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

Wherever is your click event, you should set the state of loading to TRUE:

setState(() => loading = true)

and where the callback is, you should set the state back to FALSE:

setState(() => loading = false)

Upvotes: 4

hasib_ullah
hasib_ullah

Reputation: 260

You can try creating a widget component such as this and save it with the name 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
    ),
  );
}

Then import the progress.dart and create a separate container

Container loadingScreen() {
    return circularProgress();
  }

Then change your code to:

        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();
    
              }
            }
        },
    );
  }

You can try this method and let us know if it worked

Upvotes: 1

Sagar Acharya
Sagar Acharya

Reputation: 3767

Just check out this example I have created for you:

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

Let me know if it works

Upvotes: 6

Related Questions