-
|
I am streaming objects from the Rust backend. I printed the length and the contents of the returned items in the build(), and the build() got the objects I streamed. The odd thing was the UI didn't get updated. Did I miss anything here? class ExplorerScreen extends StatefulWidget {
const ExplorerScreen({super.key});
@override
State<ExplorerScreen> createState() => _ExplorerScreenState();
}
class _ExplorerScreenState extends State<ExplorerScreen> {
Item? activeItem;
StreamSubscription<Item>? itemSubscription;
Item? previousItem;
List<Widget> streamedWidgets = [];
@override
void initState() {
super.initState();
_loadHomeDirectory();
}
Future<void> _loadHomeDirectory() async {
final loadedItem = await Item.getHomeDirectory();
setState(() {
activeItem = loadedItem;
});
itemSubscription = _startListening();
}
@override
void dispose() {
itemSubscription?.cancel();
super.dispose();
}
StreamSubscription<Item> _startListening() {
setState(() {
streamedWidgets.clear();
});
if (itemSubscription != null) {
itemSubscription?.cancel();
}
return activeItem!.list().listen((receivedItem) async {
try {
final displayItem = await receivedItem.display();
setState(() {
streamedWidgets.add(
MacosListTile(
title: Text(displayItem.name),
subtitle: Text(displayItem.fullpath),
onClick: () {
setState(() {
previousItem = activeItem;
activeItem = receivedItem;
itemSubscription = _startListening();
});
},
),
);
});
} catch (e) {
setState(() {
streamedWidgets.add(MacosListTile(title: Text("Error: $e")));
});
}
});
}
@override
Widget build(BuildContext context) {
// Handle the case when item is still loading
if (activeItem == null) {
return MacosWindow(child: Center(child: CircularProgressIndicator()));
}
print("building ui...");
print(streamedWidgets.length);
return MacosWindow(
child: Column(
children: [Expanded(child: ListView(children: streamedWidgets))],
),
);
}
}
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
|
I figured this out. So the problem lies here: StreamSubscription<Item> _startListening() {
setState(() {
streamedWidgets.clear();
});I called the The solution is to replace the original method calling with streamedWidgets = []; This way, it will create a new array and therefore a new reference to trigger the UI update. |
Beta Was this translation helpful? Give feedback.
I figured this out. So the problem lies here:
I called the
clearmethod, but theclearmethod won't necessarily recreate a new array, and the reference to the object is kept by the runtime. Flutter refreshes the UI based on the change of references. Therefore, even though the data has changed, the UI won't get updated...The solution is to replace the original method calling with
streamedWidgets = [];This way, it will create a new array and therefore a new reference to trigger the UI update.