Flutter完整开发实战详解( Redux、主题
在Flutter中,我们可以使用Redux和主题来管理应用程序的状态和外观。以下是如何实现的简化示例:
- 添加
redux
依赖项到pubspec.yaml
文件:
dependencies:
flutter:
sdk: flutter
redux: ^0.6.2
- 创建一个
State
类来保存应用程序的状态:
import 'package:redux/redux.dart';
class AppState {
final bool isLoading;
final String userName;
AppState({this.isLoading, this.userName});
AppState copyWith({bool isLoading, String userName}) {
return AppState(
isLoading: isLoading ?? this.isLoading,
userName: userName ?? this.userName,
);
}
}
final appStateReducer = combineReducers<AppState>([
TypedReducer<AppState, SetLoadingAction>(_setLoading),
TypedReducer<AppState, SetUserNameAction>(_setUserName),
]);
AppState _setLoading(AppState state, SetLoadingAction action) {
return state.copyWith(isLoading: action.isLoading);
}
AppState _setUserName(AppState state, SetUserNameAction action) {
return state.copyWith(userName: action.userName);
}
class SetLoadingAction {
final bool isLoading;
SetLoadingAction(this.isLoading);
}
class SetUserNameAction {
final String userName;
SetUserNameAction(this.userName);
}
- 在
main.dart
中配置Redux并初始化状态:
import 'package:flutter/material.dart';
import 'package:flutter_redux/flutter_redux.dart';
import 'package:redux/redux.dart';
void main() {
final store = Store<AppState>(
appStateReducer,
initialState: AppState(isLoading: false, userName: ''),
);
runApp(MyApp(store: store));
}
class MyApp extends StatelessWidget {
final Store<AppState> store;
MyApp({Key key, this.store}) : super(key: key);
@override
Widget build(BuildContext context) {
return StoreProvider<AppState>(
store: store,
child: MaterialApp(
home: HomePage(),
),
);
}
}
class HomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Flutter Redux Theme Example')),
body: Center(
评论已关闭