由于篇幅限制,这里仅提供部分代码实例。
Redux状态管理
创建一个Counter
动作:
abstract class CounterActions {
static String increment = 'increment';
}
创建一个Reducer来处理Counter
动作:
int counterReducer(int state, action) {
if (action == CounterActions.increment) {
return state + 1;
}
return state;
}
在main.dart
中配置Redux并使用StoreProvider
来包裹根Widget:
void main() {
final store = Store<int>(counterReducer, initialState: 0);
runApp(new FlutterReduxApp(store));
}
class FlutterReduxApp extends StatelessWidget {
// ...
Widget build(BuildContext context) {
return StoreProvider<int>(
store: store,
child: MaterialApp(
// ...
),
);
}
}
在CounterPage
中使用StoreConnector
连接State到UI:
class _CounterPageState extends State<CounterPage> {
@override
Widget build(BuildContext context) {
return StoreConnector<int, VoidCallback>(
converter: (Store<int> store) {
return () => store.dispatch(CounterActions.increment);
},
builder: (BuildContext context, VoidCallback increment) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'${context.watch<int>()}',
style: Theme.of(context).textTheme.display1,
),
RaisedButton(
onPressed: increment,
child: Text('Increment'),
),
],
),
);
},
);
}
}
主题和国际化
在pubspec.yaml
中添加依赖:
dependencies:
flutter:
sdk: flutter
flutter_localizations:
sdk: flutter # 国际化
intl: any # 国际化
定义主题:
final ThemeData kIOSTheme = ThemeData(
primarySwatch: Colors.orange,
primaryColor: Colors.grey[100],
primaryColorBrightness: Brightness.light,
);
final ThemeData kAndroidTheme = ThemeData(
primarySwatch: Colors.blue,
);
在main.dart
中使用主题:
void main() {
runApp(new FlutterInternationalizationApp(ThemeData.light()));
}
class FlutterInternationalizationApp extends StatelessWidge