我正在尝试使用Firestore中的值初始化TextEditingController,并希望获得一些帮助来了解如何在initState函数中执行此操作。在initState上,我想调用文档并将TextEditingController设置为标题为“ author”的文档字段的值。这是我要执行的操作的示例:
services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromSeconds(120);
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
});
如何构造此通话?
答案 0 :(得分:2)
创建一个新的异步方法,而不是在initState()
中调用它
void initialize() async{
var document = await Firestore.instance.collection('books').document('Harry Potter').get();
_authorController = new TextEditingController(text: document['author']);
}
@override
void initState() {
super.initState();
initialize();
}
我建议将document['author']
作为参数从父窗口小部件发送到此窗口小部件,而不是在此处调用。
答案 1 :(得分:0)
要能够从firebase中查询信息,您需要使用关键字async
或then
进行异步调用。
async
的示例:
class SomePage extends StatefulWidget {
@override
_SomePageState createState() => _SomePageState();
}
class _SomePageState extends State<SomePage> {
final _authorController = new TextEditingController();
final _firestore = Firestore.instance;
// Async Method
void initAuthor() async {
// we use the try catch to get an error in case an error happens with firestore
try {
final documentSnapshot = await _firestore.collection('books').document('Harry Potter').get();
_authorController.text = documentSnapshot.data['author'];
}catch(e){
print(e);
}
}
@override
void initState() {
super.initState();
initAuthor();
}
}
then
的示例:
class SomePage extends StatefulWidget {
@override
_SomePageState createState() => _SomePageState();
}
class _SomePageState extends State<SomePage> {
final _authorController = new TextEditingController();
final _firestore = Firestore.instance;
void initAuthor() {
final documentSnapshot = _firestore.collection('books')
.document('Harry Potter')
.get()
.then((documentSnapshot) {
_authorController.text = documentSnapshot.data['author'];
}).catchError((error){
print(error);
});
}
@override
void initState() {
super.initState();
initAuthor();
}
}