79604506

Date: 2025-05-03 08:49:15
Score: 0.5
Natty:
Report link

I did this myself in one of my projects, if I want to tell you step by step what I did, it would be like this:

First I created a splash page, asked the server to send me an initial API that included all the initial data that showed the latest status of the user. (Depending on your needs, for example, here you can get prayer time data and qadha prayer records... all in one api), after this step you call this api in the splash page and set and specify the status of data capture and navigation with a progress bar. I can give you my code to help you use its structure for yourself:

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:lottie/lottie.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:provider/provider.dart';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:internet_connection_checker/internet_connection_checker.dart';
import 'package:share_plus/share_plus.dart';

class Splash extends StatefulWidget {
  const Splash({Key? key}) : super(key: key);

  @override
  _SplashState createState() => _SplashState();
}

class _SplashState extends State<Splash> with TickerProviderStateMixin {
  late final preferences = FunctionalPreferences();
  late AnimationController? controller;
  bool internetConnection = true;
  bool isLoading = true;
  bool showRetry = false;
  int hasActiveLanguage = 0;
  String languageName = '';
  String currentAppVersion = '';
  String currentApiVersion = '';

  @override
  void initState() {
    controller = AnimationController(
      vsync: this,
      duration: const Duration(seconds: 5),
    )
      ..addListener(() {
        setState(() {});
        if (controller!.isCompleted) {
          initialControls();
        }
      });

    internet(context);

    Future.delayed(const Duration(seconds: 8), () {
      if (isLoading) {
        setState(() {
          showRetry = true;
        });
      }
    });

    super.initState();
  }

  @override
  void dispose() {
    controller!.dispose();
    super.dispose();
  }

  internet(context) async {
    ModelUtils model = Provider.of<ModelUtils>(context, listen: false);
    bool result = await InternetConnectionChecker().hasConnection;
    final token = await preferences.getToken();

    debugPrint('token: ${token.toString()}');

    if (result == true) {
      if (token != '') {
        await initialData();
      } else {
        setState(() {
          isLoading = false;
        });
        if(!showRetry) {
          controller?.forward();
        }
      }
    } else {
      Connectivity().onConnectivityChanged.listen((ConnectivityResult result) async {
        if (result != ConnectivityResult.none) {
          if (token != '') {
            await initialData();
          } else {
            setState(() {
              internetConnection = true;
              isLoading = false;
            });
            if(!showRetry) {
              controller?.forward();
            }
          }
        }
      });
    }
  }

  Future<void> initialData() async {
    ModelUtils model = Provider.of<ModelUtils>(context, listen: false);
    final token = await preferences.getToken();
    
    try {

      Api.initialData().then((response) async {
        if (response.statusCode == 200) {
          var responseData = json.decode(response.body);         
            if (responseData != null) {
              controller?.forward();
              setState(() {
                isLoading = false;
                showRetry = false;
                currentApiVersion = responseData['current_version'];
              });

              // Things you want to do on responseData
            }
        } else {
          debugPrint('initial error: ${json.decode(response.body)}');
        }
      });
    } catch (e) {
      debugPrint('Err: $e');
    }
  }

  initialControls() async {
    ModelUtils model = Provider.of<ModelUtils>(context, listen: false);

    final token = await preferences.getToken();
    bool userSetting = await preferences.getSetting();
    model.userStreak = await preferences.getStreak();
    debugPrint('userSetting splash: ${userSetting}');

    if (token == '') {
      Navigator.push(
        context,
        MaterialPageRoute(builder: (context) => const Login()),
      );
    } else {
      if (userSetting == false) {
        Navigator.push(
          context,
          MaterialPageRoute(builder: (context) => Start(token: token)),
        );
      } else {
        Navigator.push(
          context,
          MaterialPageRoute(builder: (context) => MyHomePage()),
        );
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    ModelUtils model = Provider.of<ModelUtils>(context);
    if (internetConnection == false) {
      return const NoInternet(nestedScreen: false);
    }

    return Scaffold(
      backgroundColor: Color(model.appTheme['bg[500]']),
      body: SafeArea(
        child: Center(
          child: Column(
            children: [
              Expanded(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Lottie.asset(
                      'assets/lotties/processing.json',
                      width: size.width * 0.65,
                      height: size.width * 0.65,
                      fit: BoxFit.contain,
                      repeat: true,
                      animate: true,
                    ),
                    Padding(
                      padding: EdgeInsets.only(top: size.width * 0.06),
                      child: Text(
                        'در حال پردازش',
                        style: TextStyle(
                          fontSize: 19,
                          fontFamily: 'BakhBold',
                          color: Color(model.appTheme['primary']),
                        ),
                      ),
                    ),
                    
                    isLoading == true
                    ? Container(
                      margin: EdgeInsets.only(
                        top: size.width * 0.08,
                        right: size.width * 0.12,
                        left: size.width * 0.12
                      ),
                      alignment: Alignment.bottomCenter,
                      child: LinearProgressIndicator(
                        minHeight: size.width * 0.025,
                        backgroundColor: Color(model.appTheme['percentIndicator']),
                        borderRadius: BorderRadius.circular(10),
                        valueColor: AlwaysStoppedAnimation(Color(model.appTheme['primary']).withOpacity(0.5)),
                      ),
                    )
                    : Container(
                      margin: EdgeInsets.only(
                        top: size.width * 0.08,
                        right: size.width * 0.12,
                        left: size.width * 0.12
                      ),
                      alignment: Alignment.bottomCenter,
                      child: LinearProgressIndicator(
                        value: controller!.value,
                        minHeight: size.width * 0.025,
                        backgroundColor: Color(model.appTheme['percentIndicator']),
                        borderRadius: BorderRadius.circular(10),
                        valueColor: AlwaysStoppedAnimation(Color(model.appTheme['primary'])),
                      ),
                    ),

                  ],
                ),
              ),
                           
              if (showRetry)
                Container(
                  width: size.width * 0.5,
                  margin: EdgeInsets.symmetric(
                    vertical: size.width * 0.03
                  ),
                  child: Button(
                    title: 'تلاش مجدد',
                    bgColor: model.appTheme['primary'],
                    borderColor: model.appTheme['primary'],
                    shadowColor: model.appTheme['shadow'],
                    titleColor: model.appTheme['cartDark'],
                    onTap: () async {
                      setState(() {
                        isLoading = true;
                        showRetry = false;
                      });

                      bool internetAvailable = await InternetConnectionChecker().hasConnection;
                      if (internetAvailable) {
                        await initialData();
                        setState(() {
                          internetConnection = true;
                          isLoading = false;
                        });
                      } else {
                        setState(() {
                          internetConnection = false;
                          showRetry = true;
                        });
                      }
                    }
                  ),
                ),
            ],
          ),
        ),
      ),
    );
  }
}

I hope I was able to help you. Good luck

Reasons:
  • RegEx Blacklisted phrase (1): I want
  • Long answer (-1):
  • Has code block (-0.5):
  • Low reputation (1):
Posted by: maryam hashemi