Arkadaşlar uygulamam'da hava durumu ekledim stabil bir şekilde çalışıyor ama konum'da isimler farklı çıkıyor bunu nasıl çözebilirim.
https://weatherapi.com kullanıyorum.
Teşekkürler R10+
Flutter uygulamam'da aldığım hata acil yardım
6
●77
- 01-11-2021, 02:24:40
- 01-11-2021, 12:00:25Evet hocam orada normal illerin isimleri gözüküyor uygulamada boyle cikiyorLecter41 adlı üyeden alıntı: mesajı görüntüle
- 01-11-2021, 12:01:46Kodunuzu paylaşırsanız daha hızlı yardımcı olabiliriz.sefagoksoy adlı üyeden alıntı: mesajı görüntüle
- 01-11-2021, 12:12:30utf-8 olarak decode ederseniz düzgün çalışacaktır.
örneğin:
Future<List<Model>> Weather() async {
var response = await http
.get("https://WeatherLink");
if (response.statusCode == 200) {
return (jsonDecode(utf8.decode(response.bodyBytes)) as List)
.map((tekGonderiMap) => Model.fromJson(tekGonderiMap))
.toList();
} else {
return throw Exception("hata:" + response.statusCode.toString());
}
} - 01-11-2021, 12:48:51Arkadaşlar kullandığım kodlar böyle internetten yapabildiğim kadarıyla.
[WeatherResponse.dart]
class WeatherResponse { Current? current; Location? location; WeatherResponse({this.current, this.location}); factory WeatherResponse.fromJson(Map<String, dynamic> json) { return WeatherResponse( current: json['current'] != null ? Current.fromJson(json['current']) : null, location: json['location'] != null ? Location.fromJson(json['location']) : null, ); } Map<String, dynamic> toJson() { final Map<String, dynamic> data = new Map<String, dynamic>(); if (this.current != null) { data['current'] = this.current!.toJson(); } if (this.location != null) { data['location'] = this.location!.toJson(); } return data; } } class Location { String? country; double? lat; String? localtime; int? localtime_epoch; double? lon; String? name; String? region; String? tz_id; Location({this.country, this.lat, this.localtime, this.localtime_epoch, this.lon, this.name, this.region, this.tz_id}); factory Location.fromJson(Map<String, dynamic> json) { return Location( country: json['country'], lat: json['lat'], localtime: json['localtime'], localtime_epoch: json['localtime_epoch'], lon: json['lon'], name: json['name'], region: json['region'], tz_id: json['tz_id'], ); } Map<String, dynamic> toJson() { final Map<String, dynamic> data = new Map<String, dynamic>(); data['country'] = this.country; data['lat'] = this.lat; data['localtime'] = this.localtime; data['localtime_epoch'] = this.localtime_epoch; data['lon'] = this.lon; data['name'] = this.name; data['region'] = this.region; data['tz_id'] = this.tz_id; return data; } } class Current { int? cloud; Condition? condition; double? feelslike_c; double? feelslike_f; double? gust_kph; double? gust_mph; int? humidity; int? is_day; String? last_updated; int? last_updated_epoch; double? precip_in; double? precip_mm; double? pressure_in; double? pressure_mb; double? temp_c; double? temp_f; double? uv; double? vis_km; double? vis_miles; int? wind_degree; String? wind_dir; double? wind_kph; double? wind_mph; Current( {this.cloud, this.condition, this.feelslike_c, this.feelslike_f, this.gust_kph, this.gust_mph, this.humidity, this.is_day, this.last_updated, this.last_updated_epoch, this.precip_in, this.precip_mm, this.pressure_in, this.pressure_mb, this.temp_c, this.temp_f, this.uv, this.vis_km, this.vis_miles, this.wind_degree, this.wind_dir, this.wind_kph, this.wind_mph}); factory Current.fromJson(Map<String, dynamic> json) { return Current( cloud: json['cloud'], condition: json['condition'] != null ? Condition.fromJson(json['condition']) : null, feelslike_c: json['feelslike_c'], feelslike_f: json['feelslike_f'], gust_kph: json['gust_kph'], gust_mph: json['gust_mph'], humidity: json['humidity'], is_day: json['is_day'], last_updated: json['last_updated'], last_updated_epoch: json['last_updated_epoch'], precip_in: json['precip_in'], precip_mm: json['precip_mm'], pressure_in: json['pressure_in'], pressure_mb: json['pressure_mb'], temp_c: json['temp_c'], temp_f: json['temp_f'], uv: json['uv'], vis_km: json['vis_km'], vis_miles: json['vis_miles'], wind_degree: json['wind_degree'], wind_dir: json['wind_dir'], wind_kph: json['wind_kph'], wind_mph: json['wind_mph'], ); } Map<String, dynamic> toJson() { final Map<String, dynamic> data = new Map<String, dynamic>(); data['cloud'] = this.cloud; data['feelslike_c'] = this.feelslike_c; data['feelslike_f'] = this.feelslike_f; data['gust_kph'] = this.gust_kph; data['gust_mph'] = this.gust_mph; data['humidity'] = this.humidity; data['is_day'] = this.is_day; data['last_updated'] = this.last_updated; data['last_updated_epoch'] = this.last_updated_epoch; data['precip_in'] = this.precip_in; data['precip_mm'] = this.precip_mm; data['pressure_in'] = this.pressure_in; data['pressure_mb'] = this.pressure_mb; data['temp_c'] = this.temp_c; data['temp_f'] = this.temp_f; data['uv'] = this.uv; data['vis_km'] = this.vis_km; data['vis_miles'] = this.vis_miles; data['wind_degree'] = this.wind_degree; data['wind_dir'] = this.wind_dir; data['wind_kph'] = this.wind_kph; data['wind_mph'] = this.wind_mph; if (this.condition != null) { data['condition'] = this.condition!.toJson(); } return data; } } class Condition { int? code; String? icon; String? text; Condition({this.code, this.icon, this.text}); factory Condition.fromJson(Map<String, dynamic> json) { return Condition( code: json['code'], icon: json['icon'], text: json['text'], ); } Map<String, dynamic> toJson() { final Map<String, dynamic> data = new Map<String, dynamic>(); data['code'] = this.code; data['icon'] = this.icon; data['text'] = this.text; return data; } }[WeatherWidget.dat]
import 'package:flutter/material.dart'; import 'package:test_uygulama/models/WeatherResponse.dart'; import 'package:test_uygulama/network/RestApis.dart'; import 'package:test_uygulama/utils/Common.dart'; import 'package:nb_utils/nb_utils.dart'; import '../main.dart'; import 'AppWidgets.dart'; class WeatherWidget extends StatelessWidget { static String tag = '/WeatherWidget'; @override Widget build(BuildContext context) { return FutureBuilder<WeatherResponse>( future: weatherMemoizer.runOnce(() => getWeatherApi()), builder: (_, snap) { return Container( alignment: Alignment.center, padding: EdgeInsets.only(top: 16, left: 8, right: 8, bottom: 8), decoration: BoxDecoration( color: getAppBarWidgetBackGroundColor(), boxShadow: [ BoxShadow(color: gray.withOpacity(0.5), blurRadius: 0.6, spreadRadius: 1.0), ], ), child: Row( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: [ Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( snap.hasData ? snap.data!.location!.name.validate() : '-', style: boldTextStyle(color: getAppBarWidgetTextColor(), size: 28), overflow: TextOverflow.ellipsis, ).paddingLeft(8), 4.height, Text( 'Here\'s your news feed', style: secondaryTextStyle(color: getAppBarWidgetTextColor()), ).paddingLeft(8), ], ).expand(), Row( children: [ snap.hasData ? cachedImage( 'https:${snap.data!.current!.condition?.icon?.validate()}', height: 50, usePlaceholderIfUrlEmpty: false, ).paddingRight(8) : SizedBox(), Text( (snap.hasData ? '${snap.data!.current!.temp_c.validate().toInt().toString()}°' : '-'), style: boldTextStyle(size: 30, color: getAppBarWidgetTextColor()), ).paddingRight(8), ], ), ], ), ); }, ); } } [Restapis.dart]import 'dart:convert'; import 'dart:io'; import 'dart:typed_data'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/material.dart'; import 'package:geolocator/geolocator.dart'; import 'package:http/http.dart'; import 'package:test_uygulama/main.dart'; import 'package:test_uygulama/models/BaseResponse.dart' as BR; import 'package:test_uygulama/models/CategoryData.dart'; import 'package:test_uygulama/models/CommentData.dart'; import 'package:test_uygulama/models/DashboardResponse.dart'; import 'package:test_uygulama/models/LoginResponse.dart'; import 'package:test_uygulama/models/RegisterResponse.dart'; import 'package:test_uygulama/models/SearchNewsResponse.dart'; import 'package:test_uygulama/models/TweetModel.dart'; import 'package:test_uygulama/models/WeatherResponse.dart'; import 'package:test_uygulama/network/NetworkUtils.dart'; import 'package:test_uygulama/screens/DashboardScreen.dart'; import 'package:test_uygulama/utils/Constants.dart'; import 'package:nb_utils/nb_utils.dart'; //region Third Party APIs Future<WeatherResponse> getWeatherApi() async { LocationPermission permission = await Geolocator.requestPermission(); if (permission == LocationPermission.always || permission == LocationPermission.whileInUse) { Position? position = await Geolocator.getLastKnownPosition(); if (position == null) { position = await Geolocator.getCurrentPosition(); } return WeatherResponse.fromJson(await (handleResponse(await buildHttpResponse('$mWeatherBaseUrl?key=$mWeatherAPIKey&q=${position.latitude},${position.longitude}'), true))); } else { throw errorSomethingWentWrong; } } Future<List<TweetModel>> loadTweetConfig() async { AuthCredential credential = TwitterAuthProvider.credential(accessToken: mTwitterApiAccessToken, secret: mTwitterApiAccessTokenSecret); return FirebaseAuth.instance.signInWithCredential(credential).then((value) async { final String proxy = isWeb ? "http://localhost:8888/" : ""; final String authUrl = "${proxy}https://api.twitter.com/oauth2/token"; final String key = Uri.encodeQueryComponent(mTwitterApiKey); final String secret = Uri.encodeQueryComponent(mTwitterApiSecretKey); final Uint8List bytes = AsciiEncoder().convert("$key:$secret"); final String auth = base64Encode(bytes); Response authRes = await post( Uri.parse(authUrl), headers: {"Authorization": "Basic $auth", "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"}, body: "grant_type=client_credentials", ); Map decoded = jsonDecode(authRes.body); if (isIos) { await setValue(TWITTER_USERNAME, value.additionalUserInfo!.profile!['screen_name']); } else { await setValue(TWITTER_USERNAME, value.additionalUserInfo!.username.validate()); } await setValue(TWITTER_ACCESS_TOKEN, decoded['access_token']); await setValue(IS_TWITTER_LOGGED_IN, true); FirebaseAuth.instance.signOut(); if (retryCount > 2) { //retryCount = 0; throw ''; } return await loadTweets(); }).catchError((e) { retryCount++; }); } Future<List<TweetModel>> loadTweets() async { return await get( Uri.parse('https://api.twitter.com/1.1/statuses/user_timeline.json?tweet_mode=extended&screen_name=${getStringAsync(TWITTER_USERNAME)}'), headers: {'Authorization': 'Bearer ${getStringAsync(TWITTER_ACCESS_TOKEN)}'}, ).then((timelineRes) async { if (timelineRes.statusCode.isSuccessful()) { retryCount = 0; log('Response: ${timelineRes.body}'); Iterable it = jsonDecode(timelineRes.body); return it.map((e) => TweetModel.fromJson(e)).toList(); } else { retryCount++; await setValue(IS_TWITTER_LOGGED_IN, false); return await loadTweetConfig(); } }).catchError((e) { retryCount++; throw e; }); } //endregion //region User Authentications Future validateToken() async { return await handleResponse(await buildHttpResponse('jwt-auth/v1/token/validate', request: {}, method: HttpMethod.POST)); } Future<LoginResponse> login(Map request, {bool isSocialLogin = false}) async { Response response = await buildHttpResponse(isSocialLogin ? 'news/api/v1/mighty/social_login' : 'jwt-auth/v1/token', request: request, method: HttpMethod.POST); if (!response.statusCode.isSuccessful()) { if (response.body.isJson()) { var json = jsonDecode(response.body); if (json.containsKey('code') && json['code'].toString().contains('invalid_username')) { throw 'invalid_username'; } } } return await handleResponse(response).then((json) async { var loginResponse = LoginResponse.fromJson(json); await setValue(TOKEN, loginResponse.token.validate()); await setValue(USER_ID, loginResponse.user_id.validate()); await setValue(FIRST_NAME, loginResponse.first_name.validate()); await setValue(LAST_NAME, loginResponse.last_name.validate()); await setValue(USER_EMAIL, loginResponse.user_email.validate()); await setValue(USERNAME, loginResponse.user_nicename.validate()); await setValue(USER_DISPLAY_NAME, loginResponse.user_display_name.validate()); if (loginResponse.my_topics != null) await setValue(MY_TOPICS, jsonEncode(loginResponse.my_topics)); if (request['loginType'] == LoginTypeGoogle) { await setValue(PROFILE_IMAGE, request['photoURL']); } else { await setValue(PROFILE_IMAGE, loginResponse.profile_image.validate()); } if (!isSocialLogin) await setValue(PASSWORD, request['password']); await setValue(LOGIN_TYPE, request['loginType'] ?? LoginTypeApp); await setValue(IS_SOCIAL_LOGIN, isSocialLogin.validate()); if (loginResponse.myPreference != null) { await setValue(MY_PREFERENCE, jsonEncode(loginResponse.myPreference)); if (loginResponse.myPreference!.detailVariant.validate() == 0) { await setValue(DETAIL_PAGE_VARIANT, 1); } else { await setValue(DETAIL_PAGE_VARIANT, loginResponse.myPreference!.detailVariant.validate(value: 1)); } await setValue(THEME_MODE_INDEX, loginResponse.myPreference!.themeMode.validate()); if (loginResponse.myPreference!.themeMode.validate() == ThemeModeLight || loginResponse.myPreference!.themeMode.validate() == ThemeModeDark) { if (loginResponse.myPreference!.themeMode.validate() == ThemeModeLight) { appStore.setDarkMode(false); } else if (loginResponse.myPreference!.themeMode.validate() == ThemeModeDark) { appStore.setDarkMode(true); } } } appStore.setUserEmail(loginResponse.user_email); appStore.setUserId(loginResponse.user_id); appStore.setFirstName(loginResponse.first_name); appStore.setLastName(loginResponse.last_name); appStore.setMyTopics(loginResponse.my_topics.validate()); appStore.setLoggedIn(true); if (isSocialLogin) { FirebaseAuth.instance.signOut(); await setValue(IS_REMEMBERED, true); } else { appStore.setUserProfile(loginResponse.profile_image); } return loginResponse; }).catchError((e) { log(e); throw e.toString(); }); } Future<void> logout(BuildContext context) async { await removeKey(TOKEN); await removeKey(USER_ID); await removeKey(FIRST_NAME); await removeKey(LAST_NAME); await removeKey(USERNAME); await removeKey(USER_DISPLAY_NAME); await removeKey(MY_TOPICS); await removeKey(PROFILE_IMAGE); await removeKey(IS_LOGGED_IN); if (getBoolAsync(IS_SOCIAL_LOGIN) || getStringAsync(LOGIN_TYPE) == LoginTypeOTP || !getBoolAsync(IS_REMEMBERED)) { await removeKey(PASSWORD); await removeKey(USER_EMAIL); } appStore.setLoggedIn(false); appStore.setMyTopics([]); DashboardScreen().launch(context, isNewTask: true); } Future<RegisterResponse> createUser(Map request) async { return RegisterResponse.fromJson(await (handleResponse(await buildHttpResponse('news/api/v1/auth/register', request: request, method: HttpMethod.POST)))); } Future<LoginResponse> viewProfile() async { return LoginResponse.fromJson(await (handleResponse(await buildHttpResponse('news/api/v1/mighty/view-profile')))); } Future<LoginResponse> updateUser(id, Map request) async { return LoginResponse.fromJson(await (handleResponse(await buildHttpResponse('news/api/v1/mighty/update-profile', request: request, method: HttpMethod.POST)))); } Future<BR.BaseResponse> forgotPassword(Map request) async { return BR.BaseResponse.fromJson(await (handleResponse(await buildHttpResponse('news/api/v1/mighty/forgot-password', request: request, method: HttpMethod.POST)))); } Future<BR.BaseResponse> changePassword(Map request) async { return BR.BaseResponse.fromJson(await (handleResponse(await buildHttpResponse('news/api/v1/mighty/change-password', request: request, method: HttpMethod.POST)))); } Future<bool?> updateProfile({String? firstName, String? lastName, File? file, String? toastMessage, bool showToast = true}) async { var multiPartRequest = MultipartRequest('POST', Uri.parse('$mBaseUrl${'news/api/v1/mighty/update-profile'}')); multiPartRequest.fields['first_name'] = firstName ?? getStringAsync(FIRST_NAME); multiPartRequest.fields['last_name'] = lastName ?? getStringAsync(LAST_NAME); multiPartRequest.fields['my_topics'] = jsonEncode(appStore.myTopics); if (file != null) multiPartRequest.files.add(await MultipartFile.fromPath('profile_image', file.path)); Map map = { 'detailVariant': getIntAsync(DETAIL_PAGE_VARIANT), 'themeMode': getIntAsync(THEME_MODE_INDEX), }; multiPartRequest.fields['my_preference'] = jsonEncode(map); multiPartRequest.headers.addAll(buildHeaderTokens()); log(multiPartRequest.fields); Response response = await Response.fromStream(await multiPartRequest.send()); log(response.body); if (response.statusCode.isSuccessful()) { Map<String, dynamic> res = jsonDecode(response.body); LoginResponse data = LoginResponse.fromJson(res); await setValue(FIRST_NAME, data.first_name); await setValue(LAST_NAME, data.last_name); appStore.setFirstName(data.first_name); appStore.setLastName(data.last_name); if (data.profile_image != null) { await setValue(PROFILE_IMAGE, data.profile_image); appStore.setUserProfile(data.profile_image); } if (data.my_topics != null) { appStore.setMyTopics(data.my_topics!); await setValue(MY_TOPICS, jsonEncode(data.my_topics)); } if (data.myPreference != null) { await setValue(MY_PREFERENCE, jsonEncode(data.myPreference)); if (data.myPreference!.detailVariant.validate() == 0) { await setValue(DETAIL_PAGE_VARIANT, 1); } else { await setValue(DETAIL_PAGE_VARIANT, data.myPreference!.detailVariant.validate(value: 1)); } await setValue(THEME_MODE_INDEX, data.myPreference!.themeMode.validate()); } if (showToast) toast(toastMessage ?? 'Profile updated successfully'); return true; } else { toast(errorSomethingWentWrong); return false; } } //endregion //region News List Future<SearchNewsResponse> getWishList(int page) async { return SearchNewsResponse.fromJson(await (handleResponse(await buildHttpResponse('news/api/v1/mighty/get-fav-list?paged=$page&posts_per_page=$postsPerPage')))); } Future<SearchNewsResponse> blogFilterNewsApi(Map? request, int page) async { return SearchNewsResponse.fromJson(await (handleResponse(await buildHttpResponse('news/api/v1/mighty/get-blog-by-filter?paged=$page', request: request, method: HttpMethod.POST)))); } Future<DashboardResponse> getDashboardApi(Map request, int page) async { if (!(await isNetworkAvailable()) && getStringAsync(DASHBOARD_DATA).isNotEmpty) { return DashboardResponse.fromJson(jsonDecode(getStringAsync(DASHBOARD_DATA))); } return await handleResponse(await buildHttpResponse('news/api/v1/mighty/get-dashboard?paged=$page', request: request, method: HttpMethod.POST)).then((value) async { var res = DashboardResponse.fromJson(value); await setValue(DASHBOARD_DATA, jsonEncode(res)); if (res.social_link != null) { await setValue(TERMS_AND_CONDITION_PREF, res.social_link!.termCondition.validate()); await setValue(PRIVACY_POLICY_PREF, res.social_link!.privacyPolicy.validate()); await setValue(CONTACT_PREF, res.social_link!.contact.validate()); await setValue(DISABLE_AD, res.social_link!.disableAd.validate()); await setValue(DISABLE_LOCATION_WIDGET, res.social_link!.disableLocation.validate()); await setValue(DISABLE_TWITTER_WIDGET, res.social_link!.disableTwitter.validate()); await setValue(DISABLE_HEADLINE_WIDGET, res.social_link!.disableHeadline.validate()); await setValue(DISABLE_QUICK_READ_WIDGET, res.social_link!.disableQuickRead.validate()); await setValue(DISABLE_STORY_WIDGET, res.social_link!.disableStory.validate()); await setValue(COPYRIGHT_TEXT, res.social_link!.copyright_text.validate()); } return res; }).catchError((e) async { if (!await isNetworkAvailable() && getStringAsync(DASHBOARD_DATA).isNotEmpty) { return DashboardResponse.fromJson(jsonDecode(getStringAsync(DASHBOARD_DATA))); } throw e.toString(); }); } Future<NewsData> getBlogDetail(Map request, bool isLogin) async { return NewsData.fromJson(await (handleResponse(await buildHttpResponse('news/api/v1/mighty/get-post-details', request: request, method: HttpMethod.POST)))); } //endregion Future<List<CategoryData>> getCategories({int? page, int perPage = 100, int? parent}) async { if (!(await isNetworkAvailable()) && getStringAsync(CATEGORY_DATA).isNotEmpty) { Iterable it = jsonDecode(getStringAsync(CATEGORY_DATA)); return it.map((e) => CategoryData.fromJson(e)).toList(); } else { Iterable it = await (handleResponse(await buildHttpResponse('news/api/v1/mighty/get-category?parent=${parent ?? 0}&page=${page ?? 1}&per_page=$perPage'))); return it.map((e) => CategoryData.fromJson(e)).toList(); } } Future addWishList(Map request) async { return handleResponse(await buildHttpResponse('news/api/v1/mighty/add-fav-list', request: request, method: HttpMethod.POST)); } Future<BR.BaseResponse> removeWishList(Map request) async { return BR.BaseResponse.fromJson(await (handleResponse(await buildHttpResponse('news/api/v1/mighty/delete-fav-list', request: request, method: HttpMethod.POST)))); } Future<List<VideoData>> getVideos(int page) async { Iterable it = await (handleResponse(await buildHttpResponse('news/api/v1/mighty/get-video-list?paged=$page&posts_per_page=$postsPerPage'))); return it.map((e) => VideoData.fromJson(e)).toList(); } Future<List<CommentData>> getCommentList(int? id) async { Iterable res = await (handleResponse(await buildHttpResponse('wp/v2/comments/?post=$id'))); return res.map((e) => CommentData.fromJson(e)).toList(); } Future<BR.BaseResponse> postComment(Map request) async { return BR.BaseResponse.fromJson(await (handleResponse(await buildHttpResponse('news/api/v1/mighty/post-comment', request: request, method: HttpMethod.POST)))); } Future<void> removeComment({int? id, force = false}) async { return await (handleResponse(await buildHttpResponse('news/api/v1/mighty/delete-comment?id=$id&force=$force'))); }