I want to get data from db first and then to show it on the ui, how to let this action execute every time before return the ui?
class TestScreen extends StatelessWidget {
// execute this method every time before return the ui.
data = getDataFromDB();
return ListView.builder(
itemCount: data.count;
itemBuilder: ...
);
}
CodePudding user response:
You can use a StatefullWidget
and a FutureBuilder
to achieve what you want:
class Example extends StatefulWidget {
@override
_ExampleState createState() => _ExampleState();
}
class _ExampleState extends State<Example> {
Future<int> future;
@override
void initState() {
future = Future.value(42);
super.initState();
}
@override
Widget build(BuildContext context) {
return FutureBuilder(
future: future,
builder: (context, snapshot) {
// create some layout here
},
);
}
}
You can then use snapshot.hasData
to know whether your future as yet completed or not. If it has, return your list. If it has not, return a loading widget or whatever you want ;)
Snippet taken from https://stackoverflow.com/a/52249579/5990125 which is a similar answer to a different question. Credit to Rémi Rousselet.
CodePudding user response:
It's better to pass db data before navigate to the specific screen,
data = db.query();
Get.ToNamed('TestScreen', arguments: data);
class TestScreen extends StatelessWidget {
return ListView.builder(
itemCount: Get.arguments;
itemBuilder: ...
);
}