Добавление текста в загрузку CircularProgressIndicator

Рейтинг: 0Ответов: 1Опубликовано: 26.01.2023

Код успешно загружает данные, но это пустая фактически страница с крутящим свайпом. Как добавить в код текст, мол, идет загрузка или хотя бы индикацию загрузки? main.dart:

import 'dart:async';
import 'dart:io';

import 'package:curved_navigation_bar/curved_navigation_bar.dart';
import 'package:admob_flutter/admob_flutter.dart';
import 'package:connectivity/connectivity.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_story_app_online_2_8_22/NotepadeWidget.dart';
import 'package:flutter_story_app_online_2_8_22/langDemo.dart';

import 'package:flutter_story_app_online_2_8_22/offline/offline_data.dart';
import '../ConstantDatas.dart';
import '../MoreWidget.dart';
import '../PrefData.dart';

import '../SplashScreeen.dart';

import '../fab_bottom_app_bar.dart';
import '../favourite_widget.dart';
import '../home_widget.dart';
import '../model/ModelMainCategory.dart';
import '../services/MainCategoryServices.dart';
import 'dart:ui'
as ui;

import 'data/data_helper.dart';
import 'fab_with_icons.dart';

import '../generated/l10n.dart';

import 'layout.dart';
import 'model/ModelHomeBanner.dart';
import 'model/ModelMyStory.dart';
import 'themes/ThemeNotifier.dart';

Future < void > main() async {
  WidgetsFlutterBinding
    .ensureInitialized(); // This allows to use async methods in the main method without any problem.
  SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);
  Admob.initialize();

  runApp(LangDemoRun(true));
}

class MyApp extends StatefulWidget {
  @override
  // static final int primarycolor = "Story App";
  _MyApp createState() => _MyApp();
}

extension ColorExtension on String {
  toColor() {
    var hexColor = this.replaceAll("#", "");
    if (hexColor.length == 6) {
      hexColor = "FF" + hexColor;
    }
    if (hexColor.length == 8) {
      return Color(int.parse("0x$hexColor"));
    }
  }
}

class LangDemoRun extends StatefulWidget {
  bool fromSplash = false;

  LangDemoRun([this.fromSplash = false]);

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

class _LangDemoRun extends State < LangDemoRun > {
  @override
  void initState() {
    ConstantDatas.setThemePosition();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    print("getvals==${ui.window.locale.toString()}--${Platform.localeName}");
    ConstantDatas.setThemePosition();
    ThemeData themeData = new ThemeData(
      primaryColor: ConstantDatas.primaryColor,
      primaryColorDark: ConstantDatas.primaryColor);

    // ToastContext().init(context);
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      localizationsDelegates: [
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
        GlobalCupertinoLocalizations.delegate,
        S.delegate
      ],
      supportedLocales: S.delegate.supportedLocales,
      // locale: new Locale(setLocals, ''),
      theme: themeData,
      home: Directionality(
        textDirection: ConstantDatas.getSetDirection(context),
        // textDirection:intl.Bidi.detectRtlDirectionality("الصفحة الرئيسية")?TextDirection.rtl : TextDirection.ltr,
        // TextDirection.rtl,
        child: (widget.fromSplash) ? SplashScreeen() : MyApp(),
        // child: MyApp(),
      )
      // WillPopScope(
      //   child:
      ,
    );

  }
}

getDummyWidget() {
  return Container(
    width: double.infinity,
    height: double.infinity,
  );
}

class _MyApp extends State < MyApp > {
  // int _selectedIndex = 1;
  int _selectedIndex = 2;
  Color selectedItemsColors = Colors.white;


  static List < Widget > _widgetOptions = [];

  @override
  void initState() {
    setColors();
    _widgetOptions = < Widget > [

      HomeWidget(primaryGet == null ? ThemeNotifier.themeColorsList[0] : primaryGet!, () {
        setState(() {

        });
      })
    ];

    data();
    super.initState();
  }


  data() async {


    ModelMyStory modelMainCategory = await getMYStories();


    print("data===${modelMainCategory.data!.story!.length}");

  }

  ValueNotifier < bool > isLoading = ValueNotifier(true);
  ValueNotifier < bool > isPermission = ValueNotifier(true);

  // ThemeData data;
  Color ? primaryGet;

  // _MyApp();
  // _MyApp(this.data);

  void _selectedTab(int index) {
    setState(() {
      _selectedIndex = index;
      selectedItemsColors = Colors.white70;
    });
  }

  void _selectedFab(int index) {
    setState(() {
      _selectedIndex = index;
      print("selectedindex=$_selectedIndex");
      selectedItemsColors = Colors.white;
    });
  }

  void displayAlertDialog() {
    showCupertinoDialog(
      context: context,
      builder: (BuildContext context) => CupertinoAlertDialog(
        title: Text(
          S.of(context).exit,
          style: TextStyle(
            fontSize: 18,
            color: Colors.black87,
          ),
        ),
        content: Text(
          S.of(context).areYouSureWantToExitApp,
          style: TextStyle(
            color: Colors.black54,
            fontSize: 16,
            fontWeight: FontWeight.normal),
        ),
        actions: [
          CupertinoDialogAction(
            child: Text(
              'Yes',
              style: TextStyle(
                color: Colors.white,
                fontSize: 18,
                fontWeight: FontWeight.normal),
            ),
            // onPressed: () => Navigator.pop(context,true),
            onPressed: () {
              // Navigator.of(context).pop();
              // Navigator.pop(context,true);
              // SystemNavigator.pop();
              Future.delayed(const Duration(milliseconds: 200), () {
                SystemChannels.platform.invokeMethod('SystemNavigator.pop');
              });
              //   // Navigator.of(context).pop(true);
              //   // toast('Cancel');
              //   // finish(context);
            },
          ),
          CupertinoDialogAction(
            child: Text(
              S.of(context).no,
              style: TextStyle(
                color: Colors.red,
                fontSize: 18,
                fontWeight: FontWeight.normal),
            ),
            onPressed: () {
              Navigator.of(context).pop(false);

              // toast('Logout');
              // finish(context);
            },
          )
        ],
      ),
    );
  }


  _onBackPressed() {
    if (_selectedIndex == 3) {
      displayAlertDialog();
    } else {
      setState(() {
        _selectedIndex = 3;
      });
    }
  }

  int isLoadingStatus = 1;
  int isConnectionNone = 2;
  int isDataAvailable = 3;

  Future < int > checkConnection() async {
    var data = await _connectivity.checkConnectivity();
    var isFirstTime = await OfflineData.getIsFirstTime();


    print("data====${data}===$isFirstTime");
    if (!isFirstTime) {
      isLoading.value = false;
      return isDataAvailable;
    } else if (isFirstTime &&
      (data == ConnectivityResult.mobile ||
        data == ConnectivityResult.wifi)) {

      OfflineData.checkData((value) {
        isLoading.value = false;
        isPermission.value = value;


      });

      return isLoadingStatus;
    } else {
      return isConnectionNone;
    }

  }

  setColors() async {
    int pos = await PrefData().getThemePos();
    print("getcolor11=$pos");
    setState(() {
      primaryGet = ThemeNotifier.themeColorsList[pos];
      print("getcolor111=$primaryGet");
    });
  }

  final Connectivity _connectivity = Connectivity();

  @override
  Widget build(BuildContext context) {
    // ConstantDatas.setThemePosition();
    print("getcolor2${ConstantDatas().getPrimaryColor()}");
    _widgetOptions = < Widget > [
      FavouriteWidget(),

      MoreWidget(),
      MoreWidget(),
      HomeWidget(primaryGet == null ? ThemeNotifier.themeColorsList[0] : primaryGet!, () { // клики

        Future.delayed(Duration(seconds: 1), () {
          isLoadingStatus = 1;
          isConnectionNone = 2;
          isDataAvailable = 3;
          isLoading.value = true;

          setState(() {

          });
        });
      }),
      // NotepadeWigdet(),

    ];
    return new WillPopScope(
      child: Scaffold(
        backgroundColor: ConstantDatas.backgroundColors,

        body: Center(


          child: FutureBuilder < int > (
            future: checkConnection(),
            builder: (context, snapshot) {
              print("snapshot===${snapshot.data}");

              if (snapshot.data != null) {
                if (snapshot.data == isLoadingStatus) {
                  return ValueListenableBuilder < bool > (
                    builder: (context, value, child) {
                      return value ?
                        CircularProgressIndicator(
                          backgroundColor: Colors.pink,
                          valueColor: new AlwaysStoppedAnimation < Color > (Colors.deepOrangeAccent),
                        ) :
                        // isPermission.value?
                        _widgetOptions.elementAt(_selectedIndex);
                      // :Text("Permission");
                    },
                    valueListenable: isLoading,
                  );

                } else if (snapshot.data == isDataAvailable) {
                  return _widgetOptions.elementAt(_selectedIndex);
                } else {
                  return InkWell(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      mainAxisSize: MainAxisSize.max,
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        ConstantDatas.getNoInternet(context),

                        SizedBox(height: 12, ),


                        TextButton(
                          style: ButtonStyle(
                            backgroundColor: MaterialStateProperty.all(ConstantDatas.primaryColor)
                          ),
                          onPressed: () async {
                            setState(() {

                            });
                          },
                          child: Text(
                            'Повторить',
                            style: TextStyle(color: Colors.white),
                          ),
                        ),

                      ],
                    ),
                  );
                }

              } else {
                return Container();
                // return ConstantDatas.getNoInternet(context);
              }
            },
          )


        ),
        bottomNavigationBar: FABBottomAppBar(
          centerItemText: S.of(context).home,
          backgroundColor: primaryGet,
          // color: ConstantDatas.bottomNavColor,
          color: Colors.white,
          // color: '#9DE6E0'.toColor(),
          selectedColor: selectedItemsColors,
          notchedShape: CircularNotchedRectangle(),
          onTabSelected: _selectedTab,
          items: [
            // FABBottomAppBarItem(
            //     iconData: Icons.markunread_mailbox,
            //     text: S.of(context).quickRead),
            FABBottomAppBarItem(
              iconData: Icons.favorite, text: S.of(context).favourite),
            // FABBottomAppBarItem(
            //     iconData: Icons.note_add, text: S.of(context).more),
            FABBottomAppBarItem(
              iconData: Icons.more_horiz, text: S.of(context).more),

          ],
        ),
        floatingActionButtonLocation:
        FloatingActionButtonLocation.centerDocked,
        floatingActionButton: _buildFab(context),
        // ),
      ),
      onWillPop: () async {
        _onBackPressed();
        return false;
      });

  }

  Widget _buildFab(BuildContext context) {

    return AnchoredOverlay(
      showOverlay: false,

      child: FloatingActionButton(
        backgroundColor: ConstantDatas.primaryColor,
        onPressed: () {
          _selectedFab(3);
        },
        // onPressed: () { },
        tooltip: 'Increment',
        child: Icon(
          Icons.home,
          color: Colors.white,
        ),
        elevation: 2.0,
      ),
    );
  }
}

Обратить мне внимание нужно на CircularProgressIndicator Как-то переделать в типа такой согласно документации, но как? Или тут нужно переделывать весь код с начала?

@override
Widget build(BuildContext context) {
  return Scaffold(
    body: Padding(
      padding: const EdgeInsets.all(20.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: < Widget > [
            Text(
              'Circular progress indicator with a fixed color',
              style: Theme.of(context).textTheme.titleLarge,
            ),
            CircularProgressIndicator(
              value: controller.value,
              semanticsLabel: 'Circular progress indicator',
            ),
          ],
        ),
    ),
  );
}

Ответы

▲ 0

Решил вопрос с помощью модуля percent_indicator. Установил и добавил

CircularPercentIndicator(
  radius: 150.0,
  lineWidth: 15.0,
  percent: 1.0,
  animation: true,
  restartAnimation: true,
  center: new Text(
    "  Загрузка базы данных, \n пожалуйста, подождите",
    style:
    new TextStyle(fontWeight: FontWeight.bold, fontSize: 20.0),
  ),
  backgroundColor: Colors.red,
  progressColor: Colors.deepOrange,
)

Осталось только понять как сделать, чтобы загрузка была динамичной. Мол, загрузка 10 процентов, 20, и на 100 смена экрана