Flutter State not getting updated - flutter

i am trying to comment section in social media app in android,the issue is after making the post comment ,the newly added comment is not showing in real time,the state is not getting updated , i tried to check the order of function calls by making print data in console,
console log
I/flutter ( 2069): comment posted succesfully
10
I/flutter ( 2069): getcomments
I/flutter ( 2069): setstate called
)),
GestureDetector(
onTap: () async {
await CommentService().postComment(
commentText: controller.text, postid: widget.postid);
await CommentService().getCommentsdata(post_id: widget.postid);
setState(() {
controller.clear();
print('setstate called');
});
},

Related

Navigate to same page with new data on GETX navigation

GetPage(
name: _Paths.PRODUCT_DETAILS_PAGE,
page: () => const ProductDetailsPageView(),
binding: ProductDetailsPageBinding(),
middlewares: [
ProductDetailsMiddleware(),
],
),
Navigate to ProductDetailsPage from ProductDetailsPage with some new data using GetMiddleware by parameters:
Get.toNamed(
Routes.PRODUCT_DETAILS_PAGE,
preventDuplicates: true,
parameters: {
'model': json.encode(product),
},
);
and this navigation continue by several times.
After that Navigate to back constantly with different previous data
But when I second time navigate this page an error happened like:
I/flutter (22387): The widget on which setState() or markNeedsBuild() was called was:
I/flutter (22387): Obx
I/flutter (22387): The widget which was currently being built when the offending call was made was:
I/flutter (22387): Builder

Update new version is not working in flutter

I have a flutter app which has an update button. This is used to update when new version is available in play store. It works fine until few days before. But now it is not working. It only shows a notification when user has installed the same version otherwise an error will be thrown.
> 2022-07-04 12:01:39.072 27969-28023/? E/flutter: [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: Bad state: No element
#0 ListMixin.firstWhere (dart:collection/list.dart:167)
#1 NewVersion._getAndroidStoreVersion (package:new_version/new_version.dart:157)
<asynchronous suspension>
#2 _SettingsPageState._checkVersion (package:bnews/ui_components/pages/settings_page.dart:196)
<asynchronous suspension>
So now I cant update my app using this update button. I use new_version flutter package to update. This is the code
void _checkVersion() async {
final newVersion = NewVersion(
androidId: "com.abc.def",
);
final status = await newVersion.getVersionStatus();
newVersion.showUpdateDialog(
context: context,
versionStatus: status!,
dialogTitle: "UPDATE!!!",
dialogText: "Please update the app from " + "${status.localVersion}" + " to " + "${status.storeVersion}",
updateButtonText: "Lets update",
);
}
I think package not found problem is there. But it works fine until few days before. I have also updated new_version package but still same problem. Is this problem with playstore?
this is a bug check pub.dev new_version issues
for checking if there is a new version, I use upgrader package, just wrap the home of your materialApp and it will handle everything:
home: UpgradeAlert(
upgrader: Upgrader(
showReleaseNotes: false,
dialogStyle: UpgradeDialogStyle.cupertino,
shouldPopScope: () => true,
),
child: MyHomepage(),
),
Anyone who still face this issue can try a new package new_version_plus,you can use the same code by just changing name,its that simple

Dio Interceptor not working on first request in same callback, only subsequent calls

I am testing out dio and tried to add a interceptor to simply add a token to future requests but am getting a weird results I can't seem to fix. All I have as a test is a 2 buttons. One when clicked should log me in and add the token to the interceptor, and the second button requests the auth profile data. For some reason, clicking the log in button I log in fine but get a 403 Forbidden when clicking the second button to access the auth profile data (even though i request the profile data after adding the interceptor). The weird part is that when i click the second button again (without changing any code or even hot reloading) everything works fine and the auth profile data is printed out. Every time I hot restart I get back to this same problem where my first request of the auth profile data has a 403 but subsequent requests work fine. I've been trying to figure out what is going on for a couple hours and cannot understand whats wrong. Please help. Thank you. (The backend is handled by django but the problem cannot be there as the api works with other frameworks and even in dio works fine on subsequent button presses, just not the first)
Code
class HomeScreen extends StatefulWidget {
#override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
Dio session = Dio(
BaseOptions(
connectTimeout: 30000,
baseUrl: 'http://127.0.0.1:8000',
responseType: ResponseType.json,
contentType: ContentType.json.toString(),
),
);
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
RaisedButton(
child: Text('Log In'),
onPressed: () async {
print('starting');
var res = await session.post('/auth/login/',
data: {'username': 'tester', 'password': 'tester'});
print(res.data);
session.interceptors.clear();
session.interceptors.addAll([
InterceptorsWrapper(
onRequest: (RequestOptions requestOptions) {
session.interceptors.requestLock.lock();
String token = res.data['key'];
if (token != null) {
session.options.headers[HttpHeaders.authorizationHeader] =
‘token $token’;
}
session.interceptors.requestLock.unlock();
return requestOptions;
},
onError: (e) => print(e.message),
),
]);
print(session.interceptors);
}),
RaisedButton(
child: Text('Get Profile'),
onPressed: () async {
session.get('/api/auth/').then((res) => print(res.data));
}),
],
),
),
);
}
}
Console on clicking the log in button
Restarted application in 11,586ms.
flutter: starting
flutter: {key: 745c0a53112e61d54bea5ea725f7fa92e3a2cdbb}
flutter: [Instance of 'InterceptorsWrapper']
Console on the first time clicking the get profile button
flutter: Http status error [403]
[VERBOSE-2:ui_dart_state.cc(177)] Unhandled Exception: DioError [DioErrorType.RESPONSE]: Http status error [403]
#0 DioMixin._request._errorInterceptorWrapper.<anonymous closure>.<anonymous closure>.<anonymous closure>
package:dio/src/dio.dart:870
#1 _rootRunUnary (dart:async/zone.dart:1198:47)
#2 _CustomZone.runUnary (dart:async/zone.dart:1100:19)
#3 _FutureListener.handleValue (dart:async/future_impl.dart:143:18)
#4 Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:696:45)
#5 Future._propagateToListeners (dart:async/future_impl.dart:725:32)
#6 Future._completeWithValue (dart:async/future_impl.dart:529:5)
#7 Future._asyncCompleteWithValue.<anonymous closure> (dart:async/future_impl.dart:567:7)
#8 _rootRun (dart:async/zone.dart:1190:13)
#9 _CustomZone.run (dart:async/zone.dart:1093:19)
#10 _CustomZone.runGuarded (dart:async/zone.dart:997:7)
#11 _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zon<…>
Console on subsequent times clicking the get profile button
flutter: {id: 3, username: tester, first_name: , last_name: , email: tester#tester.com}
5 more hours and finally figured out the problem.
session.options.headers[HttpHeaders.authorizationHeader] = 'token ' + token;
should be
requestOptions.headers[HttpHeaders.authorizationHeader] = 'token ' + token;

Flutter : firebase MissingPluginException

I'm having this problem about flutter and firebase(realtime-database).
Unhandled Exception: MissingPluginException(No implementation found for method Query#observe on channel plugins.flutter.io/firebase_database)
Here is the error in terminal
error
// error message
[VERBOSE-2:ui_dart_state.cc(157)] Unhandled Exception: MissingPluginException(No implementation found for method Query#observe on channel plugins.flutter.io/firebase_database)
#0 MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:154:7)
<asynchronous suspension>
#1 MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:329:12)
#2 Query._observe.<anonymous closure> (package:firebase_database/src/query.dart:50:38)
#3 _runGuarded (dart:async/stream_controller.dart:820:24)
#4 _BroadcastStreamController._subscribe (dart:async/broadcast_stream_controller.dart:215:7)
#5 _ControllerStream._createSubscription (dart:async/stream_controller.dart:833:19)
#6 _StreamImpl.listen (dart:async/stream_impl.dart:475:9)
#7 Stream.first (dart:async/stream.dart:1254:25)
#8 Query.once (package:firebase_database/src/query.dart:84:55)
#9 _IoTState.initState (package:flutter_try_iot/main.dart:36:13)
#10 StatefulElement._f<…>
I'm trying to get data from firebase to display in flutter app.
Here is my code main.dart
class _IoTState extends State<IoT> {
final getIot = FirebaseDatabase.instance.reference();
final getData = FirebaseDatabase.instance.reference().child('xxx-xxx');
String temperatue = "0";
String illuminance = "0";
List<String> temp = [];
List<String> light = [];
#override
void initState(){
getData.once().then((DataSnapshot snapshot){
if (snapshot.value == null) {
print("Item doesn't exist in the db");
} else {
print("Item exists in the db");
}
});
}
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Color(0xFF7ACADA),
title: Text(
"IoT ZigBee Simulation",
textAlign: TextAlign.center,
style: TextStyle(
color: Color(0xFF1A1244)
),
),
),
body: Column(
),
);
}
}
pubspec.yaml
firebase_core: ^0.4.5
firebase_database: ^3.1.6
flutter_icons: ^1.1.0
fl_chart: ^0.10.1
I follow instructions to add ios to firebase .ios add firebase
no issues found by flutter doctor
I follow other peoples suggestion to do flutter clean & flutter packages get, but still not able to fix this problem
https://github.com/flutter/flutter/issues/13971
terminal
Also pop up a window telling me The file “Runner.xcworkspace” has been modified by another application" everytime I execute flutter clean/ flutter packages get
I successfully connect to firebase yesterday, but after I close my simulator I start to receive error message
success picture
Please give me some solution or advice to fix this problem, thanks.
Please tell me if I need to provide additional information

How to fix "the method 'cancel' called on null" while working with http requests flutter

I'm trying to athenticate using APIs from a flutter app but i get these errors everytime i click Login Button
final resp = await http.post("http://192.168.73.5/myserv/login.php", body: {
"login": "login",
"apid": "re0b53fd92d4b1593db1880az322d66ea9d4",
"email": _email,
"pass": _password,
});
var __data =json.decode(resp.body);
if (__data.length == 0) {
final snackbar = SnackBar(
content: Text('Server error'),
);
scaffoldKey.currentState.showSnackBar(snackbar);
} else if (__data[0]['resp'] == 'error') {
final snackbar = SnackBar(
content: Text('Password or email is incorrect!'),
);
scaffoldKey.currentState.showSnackBar(snackbar);
} else if (__data[0]['resp'] == 'sucess') {
final snackbar = SnackBar(
content: Text('You are logged in'),
);
scaffoldKey.currentState.showSnackBar(snackbar);
Navigator.of(context)
.pushReplacement(MaterialPageRoute(builder: (context) => HomeApp()));
}
}
══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
I/flutter (29517): The following NoSuchMethodError was thrown while finalizing the widget tree:
I/flutter (29517): The method 'cancel' was called on null.
I/flutter (29517): Receiver: null
I/flutter (29517): Tried calling: cancel()
I/flutter (29517): When the exception was thrown, this was the stack:
My suggestion would be to take a look to your dispose method. There you might notice a statement calling a cancel method on something that was never initiated or used, only declared. In my case I got this error because at the disposed method I was trying to cancel a subscription to a Firebase service that I had not used. I never attached a listener to it, therefore when trying to cancel it, Flutter complained saying "the method cancel was called on null". I deleted the unnecessary line at dispose method and the error resolved. Hope the explanation helps somebody.