Untitled
unknown
kotlin
2 years ago
3.7 kB
5
Indexable
Future<void> _fetchMenus(int checkServer) async { setState(() { _fetchingData = true; }); var checkCache; final prefs = await SharedPreferences.getInstance(); // Vou buscar o numero de menus(apenas coloco isto na shared preferences para ver ha ja ha instancias criadas ou nao) final int? length = prefs.getInt("length"); // Se nao houve intancias criadas retorno false e por isso dou fetch aos menus pelo docker if (length == null) { checkCache = false; } else { getFromSharedPreferences(); checkCache = true; } try { http.Response response = await http .get(Uri.parse('http://${MyApp.host}:${MyApp.port}/menu'), headers: { 'Content-Type': 'application/json; charset=UTF-8' }).timeout(const Duration(milliseconds: 1000)); try { if (response.statusCode == HttpStatus.ok) { final Map<String, dynamic> decodedData = json.decode(const Utf8Decoder().convert(response.bodyBytes)); List<Menu> menus = []; List<Menu> orderedMenus = []; for (int i = 0; i < 5; i++) { var day = numberToWeekDay(i); if (checkServer == 1) { if (decodedData[day]['update'] != null) { var menu = Menu.fromJson(decodedData[day]['update']); setState(() => menu.updatedCache = true); menus.add(menu); } else { var menu = Menu.fromJson(decodedData[day]['original']); setState(() => menu.updatedCache = false); menus.add(Menu.fromJson(decodedData[day]['original'])); } } else { if (decodedData[day]['update'] != null) { var menu = Menu.fromJson(decodedData[day]['original']); setState(() => menu.updatedCache = true); menus.add(menu); } else { var menu = Menu.fromJson(decodedData[day]['original']); setState(() => menu.updatedCache = false); menus.add(menu); } } } int currentDay = DateTime.now().weekday - 1; for (int i = 0; i <= 4; i++, currentDay++) { if (currentDay == 5) currentDay = 0; orderedMenus.add(menus .where( (element) => element.weakDay == numberToWeekDay(currentDay)) .single); // print( "$currentDay ${numberToWeekDay(currentDay)}"); } setState(() { _menus = orderedMenus; }); } } catch (ex) { debugPrint('Something went wrong: $ex'); } } catch (ex) { try { await http.get(Uri.parse('http://${MyApp.host1}:${MyApp.port}/menu'), headers: { 'Content-Type': 'application/json; charset=UTF-8' }).timeout(const Duration(milliseconds: 500)); MyApp.host = MyApp.host1; _fetchMenus(1); } catch (ex) { try { await http.get(Uri.parse('http://${MyApp.host2}:${MyApp.port}/menu'), headers: { 'Content-Type': 'application/json; charset=UTF-8' }).timeout(const Duration(milliseconds: 500)); MyApp.host = MyApp.host2; _fetchMenus(1); } catch (ex) { debugPrint('Something went wrong: $ex'); } } } finally { _fetchingData = false; } if (checkCache == false) { getFromSharedPreferences(); } setState(() { _fetchingData = false; }); }
Editor is loading...