ก๊วนซอฟท์แวร์ </softganz> SoftGang (Gang Software)

Web &amp; Software Developer Gang.

Flutter App Lifecycle

by Little Bear @9 พ.ค. 64 12:53 ( IP : 171...174 ) | Tags : App , Flutter

Step 1. Create a new application. The main screen in which will be StatefulWidget. Which should implement the WidgetsBindingObserver interface. Next, we get the instance of WidgetBinding and add an observer to it.

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> with WidgetsBindingObserver {
  @override
  void initState() {
    WidgetsBinding.instance.addObserver(this);
    super.initState();
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Tutorial Lifecycle'),
      ),
      body: Center(),
    );
  }
}

Step 2. Now we have the didChangeAppLifecycleState method available. In this example, we simply print a state change to the thermal.

@override
void didChangeAppLifecycleState(AppLifecycleState state) {
  print('state = $state');
}



ที่มา Flutter App Lifecycle