How can I access my user activity?
I want to update something on my server when my user exit from the application
I try this way but I don't know where I make mistakes, because that way doesn't work.
class _MyHomePageState extends State<MyHomePage> with WidgetsBindingObserver {
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
// TODO: implement didChangeAppLifecycleState
print("----------------------------------------------------------------");
print(state);
print("----------------------------------------------------------------");
super.didChangeAppLifecycleState(state);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: const Icon(Icons.add),
),
);
}
}
anyone can help me?
CodePudding user response:
you have to use this in initState
something like this:
@override
void initState() {
WidgetsBinding.instance.addObserver(this);
print("initstate");
// TODO: implement initState
super.initState();
}
CodePudding user response:
you can use didChangeAppLifecycleState
with WidgetsBindingObserver
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> with WidgetsBindingObserver {
@override
void initState() {
super.initState();
// Add the observer
WidgetsBinding.instance!.addObserver(this);
}
@override
void dispose() {
// Remove the observer
WidgetsBinding.instance!.removeObserver(this);
super.dispose();
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
super.didChangeAppLifecycleState(state);
// These are the callbacks
switch (state) {
case AppLifecycleState.resumed:
// widget is resumed
break;
case AppLifecycleState.inactive:
// widget is inactive
break;
case AppLifecycleState.paused:
// widget is paused
break;
case AppLifecycleState.detached:
// widget is detached
break;
}
}
@override
Widget build(BuildContext context) {
return Scaffold();
}