我正在使闪屏飞溅,我想在显示闪屏(运行循环进度指示器)的同时运行一些计算,在完成所有计算之后,我想运行Navigator.push()进行导航到主屏幕。问题是,抖动永远不会等待计算,我所做的解决方法是在导航器中添加future.delayed()并等待任意时间,直到所有计算完成。
代码如下:(计算是正在加载的模型)
class SplashScreen extends StatefulWidget {
@override
_SplashScreenState createState() => _SplashScreenState();
}
class _SplashScreenState extends State<SplashScreen> {
@override
void initState() {
super.initState();
SchedulerBinding.instance.addPostFrameCallback((_) {
// Do all of this
final bestModel = Provider.of<BestSellingModel>(context, listen: false);
final salesModel = Provider.of<SalesModel>(context, listen: false);
final categoryModel = Provider.of<CategoryModel>(context, listen: false);
if (bestModel.isLoading) bestModel.getBestSelling();
if (salesModel.isLoading) salesModel.getSales();
if (categoryModel.isLoading) categoryModel.getCategories();
DatabaseHelper.instance.database;
// And only then navigate to next screen without a pre-established time
Future.delayed(Duration(seconds: 12), () {
Navigator.of(context).pushReplacement(
MaterialPageRoute(builder: (BuildContext context) => MainTabs()));
});
});
}
@override
Widget build(BuildContext context) {
Size screenSize = MediaQuery.of(context).size;
return Scaffold(
body: Stack(
fit: StackFit.expand,
children: <Widget>[
Container(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topRight,
end: Alignment.bottomLeft,
colors: [Color(0xffFBC707), Color(0xffF25D19)],
),
),
),
Column(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Expanded(
flex: 2,
child: Container(
width: screenSize.width / 1.8,
child: Image.asset('assets/images/splash_logo.png'),
),
),
Expanded(
flex: 1,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
// This needs to keep running while the models are being loaded
SizedBox(
child: CircularProgressIndicator(),
height: 64.0,
width: 64.0,
),
],
),
)
],
)
],
),
);
}
}
这是我使用的模型的一个示例:
class SalesModel with ChangeNotifier{
List<Product> products = [];
bool isLoading = true;
Future getSales() async {
products = await WooCommerce().getProductsByCategory(categoryId: 58);
isLoading = false;
notifyListeners();
}
}
那么,有没有一种方法可以使初始屏幕的循环进度指示器在加载模型的同时运行,并在加载所有模型后导航到主屏幕?
答案 0 :(得分:1)
我对登录状态做了类似的操作。 我的启动程序会监听登录状态流。
void setInProgress(bool value) {
setState(() {
_inProgress = value;
});
} // of setInProgress
在构建方法中,您可以添加条件
if (_inProgress)
Center(
child: CircularProgressIndicator(),
)
if (!_inProgress)
Center(
child: HomeScreenWidget(),
)
每次执行此操作时,我都应该将其封装在小部件中。 此外,如果计算状态不仅仅是布尔值,还可以使用StreamBuilder侦听计算状态流。