Advertisement
mitrakov

Redux Thunk example

May 31st, 2020
1,113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Dart 4.16 KB | None | 0 0
  1. // pubspec.yaml
  2. dependencies:
  3.   http: ^0.12.1
  4.   flutter_redux: 0.5.0
  5.   redux_thunk: ^0.2.1
  6.  
  7. // appstate.dart
  8. class AppState {
  9.   final List<String> persons;
  10.   final String lastError;
  11.  
  12.   AppState({this.persons, this.lastError});
  13.   // it's strongly recommended to override ==/hashCode
  14. }
  15.  
  16. // actions.dart
  17. class PersonsFetchedAction {
  18.   final List<String> persons;
  19.   PersonsFetchedAction(this.persons);
  20. }
  21.  
  22. class FetchErrorAction {
  23.   final String error;
  24.   FetchErrorAction(this.error);
  25. }
  26.  
  27. // ajax.dart
  28. import 'dart:convert';
  29. import 'package:http/http.dart' as http;
  30. import 'package:guap_mobile/person.dart';
  31.  
  32. class Ajax {
  33.   static final baseUrl = "http://mitrakoff.com:8888/varlam";
  34.  
  35.   static Future<List<String>> fetchPersons() async {
  36.     final headers = {"username": "Tommy", "token": "33dbd779129f406bbbb003aecd23e96f"};
  37.     final response = await http.get("$baseUrl/person/list", headers: headers);
  38.     if (response.statusCode == 200) {
  39.       final personResponse = PersonResponse.fromJson(json.decode(response.body)); // you have to implement 'fromJson'
  40.       return personResponse.getPersons();
  41.     } else throw Exception("Failed to load persons (http code ${response.statusCode})");
  42.   }
  43. }
  44.  
  45. // thunks.dart
  46. import 'package:redux/redux.dart';
  47. import 'package:redux_thunk/redux_thunk.dart';
  48. import 'package:guap_mobile/redux/ajax.dart';
  49. import 'package:guap_mobile/redux/actions.dart';
  50.  
  51. class Thunk {
  52.   static ThunkAction<AppState> fetchPersons() {
  53.     return (Store<AppState> store) async {
  54.       try {
  55.         store.dispatch(PersonsFetchedAction(await Ajax.fetchPersons()));
  56.       } catch(e) {
  57.         store.dispatch(FetchErrorAction(e.toString()));
  58.       }
  59.     };
  60.   }
  61. }
  62.  
  63. // reducers.dart
  64. import 'package:redux/redux.dart';
  65. import 'package:guap_mobile/redux/actions.dart';
  66. import 'package:guap_mobile/redux/appstate.dart';
  67.  
  68. class AppReducer {
  69.   static AppState personsFetchedReducer(AppState state, PersonsFetchedAction action) {
  70.     return AppState(persons: action.persons, lastError: "");
  71.   }
  72.   static AppState fetchErrorReducer(AppState state, FetchErrorAction action) {
  73.     return AppState(persons: [], lastError: action.error);
  74.   }
  75.  
  76.   static Reducer<AppState> reducer = combineReducers<AppState>([
  77.     TypedReducer<AppState, PersonsFetchedAction>(personsFetchedReducer),
  78.     TypedReducer<AppState, FetchErrorAction>(fetchErrorReducer)
  79.   ]);
  80. }
  81.  
  82. // main.dart
  83. import 'package:flutter/material.dart';
  84. import 'package:flutter_redux/flutter_redux.dart';
  85. import 'package:redux/redux.dart';
  86. import 'package:redux_thunk/redux_thunk.dart';
  87. import 'package:guap_mobile/redux/appstate.dart';
  88. import 'package:guap_mobile/redux/reducers.dart';
  89. import 'package:guap_mobile/redux/thunks.dart';
  90.  
  91. void main() {
  92.   final store = new Store<AppState>(
  93.     AppReducer.reducer,
  94.     initialState: AppState(persons: [], lastError: ""),
  95.     middleware: [thunkMiddleware]
  96.   );
  97.  
  98.   runApp(MyApp(store: store));
  99. }
  100.  
  101. class MyApp extends StatelessWidget {
  102.   final Store<AppState> store;
  103.  
  104.   const MyApp({Key key, this.store}) : super(key: key);
  105.  
  106.   @override
  107.   Widget build(BuildContext context) {
  108.     return StoreProvider<AppState>(store: store, child: MaterialApp(
  109.         title: "Guap",
  110.         home: Scaffold(appBar: AppBar(
  111.             title: Text("Guap application")),
  112.             body: Column(
  113.               crossAxisAlignment: CrossAxisAlignment.center,
  114.               children: <Widget>[
  115.                 RaisedButton(child: Text("Push me!"), onPressed: () => store.dispatch(Thunk.fetchPersons())),
  116.                 StoreConnector<AppState, AppState>(
  117.                   distinct: true,
  118.                   converter: (store) => store.state,
  119.                   builder: (context1, state) {
  120.                     return Expanded(child: ListView.builder(
  121.                         itemCount: state.lastError.isNotEmpty ? 1 : state.persons.length,
  122.                         itemBuilder: (ctxt, i) {
  123.                           final item = state.lastError.isNotEmpty ? state.lastError : state.persons[i];
  124.                           return ListTile(title: Text(item));
  125.                         })
  126.                     );
  127.                   }
  128.                 )
  129.               ],
  130.             )
  131.         )
  132.     ));
  133.   }
  134. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement