flutter - InitState - 函数未在 Flutter 上执行
问题描述
我正在通过 initState 调用以下函数,但由于某种原因它没有运行,当我打印一些“测试”时,控制台上没有出现任何内容。有什么问题?(我的州内还有其他功能)
class Home extends StatefulWidget {
@override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home>
with AutomaticKeepAliveClientMixin<Home> {
@override
void initState() {
super.initState();
getInfo();
}
int countPost = 0;
List<Post> contentList = [];
getInfo() async {
QuerySnapshot querySnapshot = await contentReference
.document(_id)
.collection("usersContent")
.getDocuments();
setState(() {
countPost = querySnapshot.documents.length;
contentList = querySnapshot.documents
.map((documentSnapshot) => Post.fromDocument(documentSnapshot))
.toList();
});
print("Test");
}
}
解决方案
首先,你不应该在 initState 中调用 setState,也可能 querySnapshot 有一些错误,做一个 try-catch 块来看看发生了什么。
getInfo() async {
print("init state is started");
try{
QuerySnapshot querySnapshot = await contentReference
.document(_id)
.collection("usersContent")
.getDocuments();
setState(() {
countPost = querySnapshot.documents.length;
contentList = querySnapshot.documents
.map((documentSnapshot) => Post.fromDocument(documentSnapshot))
.toList();
});}
catch(e){
print('error is $e')
}
print("Test");
}
编辑:更好的实现是使用 FutureBuilder:
import 'package:flutter/material.dart';
class Home extends StatefulWidget {
@override
_HomeState createState() => _HomeState();
}
class _HomeState extends State < Home > with AutomaticKeepAliveClientMixin {
int countPost = 0;
List < Post > contentList = [];
Future getInfo() async {
print("FutureBuilder is started");
try {
QuerySnapshot querySnapshot = await contentReference
.document(_id)
.collection("usersContent")
.getDocuments();
countPost = querySnapshot.documents.length;
return contentList = querySnapshot.documents
.map((documentSnapshot) => Post.fromDocument(documentSnapshot))
.toList();
} catch (e) {
return print('error is $e');
}
}
@override
bool get wantKeepAlive => true;
Widget build(BuildContext context) {
super.build(context);
return FutureBuilder(
future: getInfo(),
builder: (context, AsyncSnapshot snapshot) {
if (!snapshot.hasData) {
return Center(
child: CircularProgressIndicator(
strokeWidth: 6,
valueColor:
AlwaysStoppedAnimation < Color > (Colors.redAccent),
),
);
} else {
return Text('Done', style: TextStyle(color: Colors.black, fontSize: 40), );
}
}
);
}
}
推荐阅读
- unity3d - 如何重置 DontDestroyLoad 下的游戏对象?
- laravel - 使用 Laravel sanctum 进行 Laravel 默认身份验证返回 419 错误代码
- json - django嵌套模型json导入
- python - 我正在尝试使用 librosa 读取波形文件,但出现以下错误。为什么我会收到此错误,我该如何解决?
- angular - 带有 Hls.xhr.beforeRequest 问题的 Angular 8 动态 Videojs
- c# - 错误 0x8007000b:无法创建托管引导程序应用程序
- javascript - 如何使用echarts以相同的动画速度绘制多条串行曲线线
- sql-server - Access/SQL Server 存储过程搜索查询 - 空值
- php - 在 Laravel 中登录失败时在错误消息中插入按钮链接
- html - 如何证明 div 中的锚标记的合理性