我需要将 redux 存储状态从屏幕传递到build
函数内部的另一个屏幕。
我的问题是在build
函数中我有 ViewModel 变量,它没有对状态的引用。
这是屏幕的代码:
import ...
class Menu extends StatefulWidget {
@override
_MenuState createState() => _MenuState();
}
class _MenuState extends State<Menu> {
@override
Widget build(BuildContext context) {
return StoreConnector<AppState, ViewModelLogin>(
converter: (store) => ViewModelLogin.create(store),
builder: (context, ViewModelLogin viewModel) {
Widget _buildPage(isLoggedIn) {
if (isLoggedIn) {
return ListView(
children: <Widget>[
ListTile(
title: Text('Settings'),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => MySettingsScreen(), // <-- HERE I NEED TO PASS THE STATE TO MySettingsScreen
),
);
},
),
ListTile(
leading: Image.network(
viewModel.loginType == 'facebook'
? 'https://img.icons8.com/color/52/000000/facebook.png'
: 'https://image.flaticon.com/teams/slug/google.jpg'
,
width: 30.0,
),
title: Text('Exit'),
onTap: () {
viewModel.onLogout(viewModel.loginType);
}
),
],
);
} else {
return LoginScreen(appBar: false);
}
}
return _buildPage(viewModel.isLoggedIn);
},
);
}
}
我需要将状态传递给 MySettingsScreen 的原因是在屏幕中我需要一个 store 变量来调用 web 服务(在构建函数之外)。
这是我需要商店状态的 MySettingsScreen 的一部分:
import ...
class MySettingsScreen extends StatefulWidget {
final AppState state;
MySettingsScreen({Key key, @required this.state}) : super(key: key);
@override
_MySettingsScreenState createState() => _MySettingsScreenState();
}
class _MySettingsScreenState extends State<MySettingsScreen> {
@override
void initState() {
super.initState();
_load();
}
void _load() async {
final url = 'url';
try {
http.Response res = await http.get(url, headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + // <-- HERE I NEED THE STORE VARIABLE
});
final data = json.decode(res.body);
tmpItems = _parseItems(data["bookings"]);
} catch(e) {
print(e);
}
}
@override
Widget build(BuildContext context) {
...
}
}