Flutter-文本小部件更新一次迭代太晚了



我声明了一个文本小部件,如下所示:

Text userText = Text("user not found");

我在构建小部件中返回小部件,如下所示:

@override
Widget build(BuildContext context) {
return Stack(
children: [
RepaintBoundary(
child: userText,
key: textKey
),
.....

它在RepaintBoundary中,因为我将把这个小部件转换为BitmapDescriptor,用它作为我的谷歌地图上的标记。

然后我有以下功能来创建标记:

Future<void> getData() async {
var map = new Map();

QuerySnapshot querySnapshot = await firestore.collection("users").get(); //get the data
querySnapshot.docs.forEach((element) { 
print("Data: ${element.data()['user_uid']}");
map[element.data()['user_uid']] = element.data()['location']['geopoint'];
});
print("-Map- => ${map}");

int id = 0;
for(var entry in map.entries) {
_user = entry.key;
userText = Text('${entry.key}');
print("USER TEXT: " + userText.toString());
GeoPoint geo = entry.value;
print("USER: " + _user);
print("LOCATION: " + geo.latitude.toString() + " , " + geo.longitude.toString());

BitmapDescriptor testIcon = await getCustomIcon(textKey); //this transforms the Text widget into a BitmapDescriptor
_markers.add(
Marker(
markerId: new MarkerId(id.toString()),
position: new LatLng(geo.latitude, geo.longitude),
icon: testIcon
)
);
print("MARKERS IN FOREACH: " + _markers.toString());
id++;
}
print("Map: ${map}");
setState(() {});
}

在Firestore数据库中,我有两个文档,都有一个user_uidlocation字段。该功能的输出如下:

I/flutter (13998): USER TEXT: Text("JTtxo8zgjAcsLbTgg753TOacD6R2")
I/flutter (13998): USER: JTtxo8zgjAcsLbTgg753TOacD6R2
I/flutter (13998): LOCATION: 52 , 4
I/flutter (13998): USER TEXT: Text("eBpkVzUPRLPUJHfDyfdo918UcIn1")
I/flutter (13998): USER: eBpkVzUPRLPUJHfDyfdo918UcIn1
I/flutter (13998): LOCATION: 53 , 4

这正是我想要的。一切似乎都在运转。然而,在我的地图上,有一个标记的文本为user not found,还有一个标记为JTtxo8zgjAcsLbTgg753TOacD6R2。接下来,具有文本JTtxo8zgjAcsLbTgg753TOacD6R2的标记在位置53, 4上,并且具有文本user not found的标记在地点52, 4上。

所以我想的是,除了Text小部件显示";先前的";文本这是什么原因?

如果有什么不清楚的地方,请告诉我!

检查以下要点:https://gist.github.com/itsJoKr/ce5ec57bd6dedf74d1737c1f39481913

在你的代码中:

override
void initState() {
super.initState();
getData();
}
Future<void> getData() async {
List<Widget> widgets = [];
for (int i = 0; i < 5; i++) {
widgets.add(Text("Number: $i"));
}
MarkerGenerator(
widgets,
(bitmaps) {
for (int i = 0; i < 5; i++) {
_markers.add(Marker(
markerId: new MarkerId(i.toString()),
position:
new LatLng(52.08674971530128 + i / 1000, 4.269159032232106),
icon: BitmapDescriptor.fromBytes(bitmaps[i]),
));
}
setState(() {});
},
).generate(context);
print("Markers: $_markers");
}

编辑:

因为它会等待图像加载,有时在FirstLayout未被调用后,您应该将其更改为:

class MarkerGenerator {
...
void generate(BuildContext context) {
if (SchedulerBinding.instance.schedulerPhase == SchedulerPhase.persistentCallbacks) {
SchedulerBinding.instance.addPostFrameCallback((_) => afterFirstLayout(context));
} else {
afterFirstLayout(context);
}
}

相关内容

  • 没有找到相关文章

最新更新