2021年7月25日 星期日

[又重學flutter]state與生命週期


詳細flutter生命週期圖可以參考此部落格: https://medium.com/flutterdevs/explore-widget-lifecycle-in-flutter-e36031c697d0



以下運行結果為

1. App執行後,debug console印出init!!

2. 畫面中印出按鈕與aa,bb,cc

3. 按下按鈕後,畫面改為dd,ee,ff


測試生命週期: initState/ build/ setState/ dispose

import 'package:flutter/material.dart';

void main() {
  runApp(MaterialApp(home: HomePage()));
}

class HomePage extends StatefulWidget {
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  Map allDataMap = Map();
  
  void initState() {
    super.initState();
    print('init!!');
    allDataMap['first'] = 'aa';
    allDataMap['second'] = 'bb';
    allDataMap['third'] = 'cc';
  }

  
  Widget build(BuildContext context) {
    return Scaffold(
        body: SafeArea(
            child: Column(
      children: [
        GestureDetector(
            onTap: () {
              if (mounted) {
                setState(() {
                  allDataMap['first'] = 'dd';
                  allDataMap['second'] = 'ee';
                  allDataMap['third'] = 'cc';
                });
              }
            },
            child: Container(
              color: Colors.blue,
              child: Padding(
                padding: EdgeInsets.all(10.0),
                child: Text('click me'),
              ),
            )),
        Text(allDataMap['first']),
        Text(allDataMap['second']),
        Text(allDataMap['third']),
      ],
    )));
  }

  
  void dispose() {
    allDataMap = Map();
    super.dispose();
  }
}

沒有留言:

張貼留言