为了简单地解释代码,我们有一个简单的流构建器,它从Firestore数据库中获取数据,然后我们返回并在屏幕上显示'username'的值。
我们也有一个TextField在同一个小部件&我注意到,每当我点击它,它似乎重建并再次获取数据。目标是避免在设备的键盘打开或关闭时重新构建,因为这会花费不必要的读取。任何想法我可以达到相同的结果,但没有重建效果?
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import '../models/user.dart';
class Admin extends StatefulWidget {
const Admin({
Key? key,
}) : super(key: key);
@override
State<Admin> createState() => _AdminState();
}
class _AdminState extends State<Admin> {
final TextEditingController _userController = TextEditingController();
@override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
appBar: AppBar(
elevation: 4,
toolbarHeight: 50,
backgroundColor: Colors.white,
actions: [
Container(
padding: const EdgeInsets.symmetric(horizontal: 12),
width: MediaQuery.of(context).size.width,
child: const Text('Admin',
style: TextStyle(
color: Colors.black,
fontSize: 20,
letterSpacing: 0.3,
fontWeight: FontWeight.w500)),
),
]),
body: Column(
children: [
TextField(
controller: _userController,
decoration: InputDecoration(
labelText: 'User',
),
),
StreamBuilder(
stream: FirebaseFirestore.instance
.collection('users')
.limit(1)
.snapshots(),
builder: (context,
AsyncSnapshot<QuerySnapshot<Map<String, dynamic>>> snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Row();
}
return snapshot.data?.docs.length != 0
? SingleChildScrollView(
child: ListView.builder(
physics: const NeverScrollableScrollPhysics(),
shrinkWrap: true,
itemCount: snapshot.data?.docs.length,
itemBuilder: (context, index) {
User user = User.fromSnap(
snapshot.data!.docs[index],
);
return Text('${user.username}');
},
),
)
: Row();
},
),
],
),
),
);
}
}
要停止重复获取数据,您可以在这里做一件事而不是从流构建中调用firebasefirestore您可以在void initState()中完成方法并将其数据存储在变量
中。将此代码添加到构建方法
@override
void initState() {
super.initState();
streamData = FirebaseFirestore.instance
.collection('users')
.limit(1)
.snapshots();
}
,然后替换这个代码
stream: FirebaseFirestore.instance
.collection('users')
.limit(1)
.snapshots(),
与
stream : streamData,
尝试将类转换为无状态小部件