问题
@override
void didChangeDependencies() async {
if (_isInit) {
print('First stat');
final restaurant = await Provider.of<Restaurants>(context, listen: false)
.fetchAndSetRestaurants();
print('test');
}
_isInit = false;
super.didChangeDependencies();
}
bool showFavourites = false;
@override
Widget build(BuildContext context) {
return Scaffold(
//bottomNavigationBar: BottomNavBar(),
appBar: homeAppBar(context),
body: SingleChildScrollView(
child: showFavourites
? Padding(
padding: const EdgeInsets.only(top: 20),
child:
RestaurantList(), //RestaurantList(restaurants: restaurants)
)
: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
SearchBox(
onChanged: (value) {},
),
CategoryList(),
RestaurantList(), //RestaurantList(restaurants: restaurants)
]),
));
}
}
class RestaurantList extends StatelessWidget {
@override
Widget build(BuildContext context) {
final List<Restaurant> restaurants1 =
Provider.of<Restaurants>(context).getRestaurants1;
print('List: ${restaurants1[0].name}');
return ListView.builder(
scrollDirection: Axis.vertical,
shrinkWrap: true,
itemBuilder: (ctx, i) =>
restaurants1[i].isAvailable || restaurants1[i].totalQuantity != 0
? Column(
children: [
ChangeNotifierProvider.value(
value: restaurants1[i], child: RestaurantCard()),
Divider(),
],
)
: Container(),
itemCount: restaurants1.length,
);
}
The data (restaurants1) inside the 'RestaurantList' widget is being accessed before it is available. Even putting 'await' while fetching it in didChangeDependencies doesn't seem to work.
This is the output I am getting:
flutter: First stat
flutter: null
flutter: SUCCESS :KFC
flutter: test
[VERBOSE-2:profiler_metrics_ios.mm(184)] Error retrieving thread information: (ipc/send) invalid destination port
null is called by the getter 'getRestaurants1'
回答1:
You can use FutureBuilder
widget and retrieve data inside it's future
parameter. Official Flutter Documentation has simple example that describe how to declare and work with FutureBuilder
.
In your case, try something like this:
FutureBuilder<List<Restaurant>>(
future: Provider.of<Restaurants>(context, listen: false).fetchAndSetRestaurants(),
builder: (context, snapshot) {
// Items are not available and you need to handle this situation, simple solution is to show a progress indicator
if (!snapshot.hasData) {
return CircularProgressIndicator();
}
return ListView.builder(
scrollDirection: Axis.vertical,
shrinkWrap: true,
itemBuilder: (ctx, i) =>
restaurants1[i].isAvailable || restaurants1[i].totalQuantity != 0
? Column(
children: [
ChangeNotifierProvider.value(
value: restaurants1[i], child: RestaurantCard()),
Divider(),
],
)
: Container(),
itemCount: restaurants1.length,
);
},
);
来源:https://stackoverflow.com/questions/65967347/how-can-i-wait-for-data-before-it-is-available-flutter