Use redux
Aoi-hosizora opened this issue · 0 comments
Aoi-hosizora commented
See https://pub.dev/packages/flutter_redux.
Temp code:
- pubspec.yaml
# ...
flutter_redux: ^0.7.0
# ...
- redux/state.dart
import 'package:flutter/foundation.dart';
import 'package:manhuagui_flutter/model/user.dart';
import 'package:redux/redux.dart';
class GlobalState {
String token;
User user;
GlobalState({
@required this.token,
@required this.user,
});
}
class RefreshAction<T> {
final T data;
const RefreshAction(this.data);
}
final tokenReducer = combineReducers<String>([
TypedReducer((String token, RefreshAction<String> action) {
token = action.data;
return token;
}),
]);
final userReducer = combineReducers<User>([
TypedReducer((User user, RefreshAction<User> action) {
user = action.data;
return user;
}),
]);
GlobalState globalReducer(GlobalState state, action) {
return GlobalState(
token: tokenReducer(state.token, action),
user: userReducer(state.user, action),
);
}
- page/mine.dart
import 'package:flutter/material.dart';
import 'package:flutter_redux/flutter_redux.dart';
import 'package:manhuagui_flutter/model/user.dart';
import 'package:redux/redux.dart';
import 'package:manhuagui_flutter/service/redux/state.dart';
/// 我的
class MineSubPage extends StatefulWidget {
const MineSubPage({Key key}) : super(key: key);
@override
_MineSubPageState createState() => _MineSubPageState();
}
class _MineSubPageState extends State<MineSubPage> with AutomaticKeepAliveClientMixin {
@override
bool get wantKeepAlive => true;
@override
Widget build(BuildContext context) {
super.build(context);
return StoreProvider(
store: Store<GlobalState>(
globalReducer,
initialState: GlobalState(
token: '',
user: null,
),
),
child: StoreConnector<GlobalState, User>(
converter: (store) => store.state.user,
builder: (context, user) => Scaffold(
body: Center(
child: Text('MineSubPage'),
),
),
),
);
}
}