初始化異步載入資料

import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

class ConstellationSelectionPage extends StatefulWidget {
  const ConstellationSelectionPage({Key? key}) : super(key: key);

  @override
  _ConstellationSelectionPageState createState() => _ConstellationSelectionPageState();
}

class _ConstellationSelectionPageState extends State<ConstellationSelectionPage> {
  late SharedPreferences _prefs;
  String? selectedConstellation;

  //基本資料
  List<String> constellations = [
    '白羊座',
    '金牛座',
    '双子座',
    '巨蟹座',
    '狮子座',
    '处女座',
    '天秤座',
    '天蝎座',
    '射手座',
    '摩羯座',
    '水瓶座',
    '双鱼座',
  ];

  @override
  void initState() {
    super.initState();
    initSharedPreferences(); //使用一個流程
  }

  Future<void> initSharedPreferences() async {
    _prefs = await SharedPreferences.getInstance();
    loadSavedConstellation();
  }

  Future<void> loadSavedConstellation() async {
    final String? savedConstellation = _prefs.getString('selectedConstellation');
    if (savedConstellation != null) {
      setState(() {
        selectedConstellation = savedConstellation;
      });
    } else {
      setState(() {
        selectedConstellation = constellations.first;
      });
      saveSelectedConstellation(constellations.first);
    }
  }

  Future<void> saveSelectedConstellation(String? constellation) async {
    if (constellation != null) {
      setState(() {
        selectedConstellation = constellation;
      });
      await _prefs.setString('selectedConstellation', constellation);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('星座选择'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Text(
              '请选择你的星座:',
              style: TextStyle(fontSize: 18),
            ),
            const SizedBox(height: 16),
            DropdownButton<String>(
              value: selectedConstellation,
              items: constellations.map((constellation) {
                return DropdownMenuItem<String>(
                  value: constellation,
                  child: Text(constellation),
                );
              }).toList(),
              onChanged: saveSelectedConstellation,
            ),
          ],
        ),
      ),
    );
  }
}

 

留言

熱門文章