我有一个Widget MainPage,它使用AppBar和bottomNavigationBar构建一个Scaffold。作为主体,我有一个IndexedStack并仅呈现当前活动的tab-widget。 每个选项卡都从Rest-API加载一些数据并显示数据。
当前,我正在尝试向MainPage中的AppBar添加一个重新加载按钮,但是我的问题是如何告诉子小部件它们应该重新加载数据。
MainPage看起来像这样:
import 'package:flutter/material.dart';
import 'package:iracingdata/Last10Races.dart';
import 'package:iracingdata/MyLicenses.dart';
import 'package:iracingdata/Utils.dart';
import 'package:iracingdata/main.dart';
class MainPage extends StatefulWidget {
MainPage({Key key}) : super(key: key);
@override
State<StatefulWidget> createState() => _MainState();
}
class _MainState extends State<MainPage> {
int _currentIndex = 0;
List<Widget> _children;
@override
void initState() {
super.initState();
_children = [Last10Races(), MyLicenses()];
}
void _onTabTapped(int tabIndex) {
setState(() { _currentIndex = tabIndex; });
}
void _onRefresh() {
// TODO: What to do here?
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Hallo ${Utils.decodeString(AppContainer.apiOf(context).playerInfo.displayName)}'),
actions: <Widget>[
FlatButton(
onPressed: _onRefresh,
child: Icon(Icons.refresh, color: Colors.white),
)
],
),
body: IndexedStack(
index: _currentIndex,
children: _children,
),
bottomNavigationBar: BottomNavigationBar(
currentIndex: _currentIndex,
onTap: _onTabTapped,
items: [
BottomNavigationBarItem(
icon: new Icon(Icons.assignment),
title: new Text('Last Races'),
),
BottomNavigationBarItem(
icon: new Icon(Icons.person),
title: new Text('My Licenses'),
),
],
),
);
}
}
其中一个子页面如下所示:
import 'package:flutter/material.dart';
import 'package:iracingdata/main.dart';
import 'package:iracingdata/model/LastRacesStats.dart';
class Last10Races extends StatefulWidget {
Last10Races({Key key}) : super(key: key);
@override
State<StatefulWidget> createState() => _Last10RacesState();
}
class _Last10RacesState extends State<Last10Races> {
Future<List<LastRacesStats>> _lastRacesFuture;
@override
void didChangeDependencies() {
if (_lastRacesFuture == null) {
_lastRacesFuture = AppContainer.apiOf(context).getLast10RacesStats();
}
super.didChangeDependencies();
}
void _reload() {
setState(() {
_lastRacesFuture = AppContainer.apiOf(context).getLast10RacesStats();
});
}
Widget _renderItem(LastRacesStats item) {
return Text(item.name);
}
Widget _renderError() {
return Text('Error');
}
Widget _renderLoading() {
return Text('Loading...');
}
Widget build(BuildContext context) {
return FutureBuilder(
future: _lastRacesFuture,
initialData: null,
builder:
(BuildContext context, AsyncSnapshot<List<LastRacesStats>> snapshot) {
if (snapshot.hasData) {
return RefreshIndicator(
onRefresh: () {
_reload();
return _lastRacesFuture;
},
child: ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (BuildContext context, int index) {
return _renderItem(snapshot.data[index]);
},
),
);
} else if (snapshot.hasError) {
return _renderError();
} else {
return _renderLoading();
}
},
);
}
}
我的问题是我真的不知道要在MainPage的_onRefresh中做什么。
感谢您的帮助。