0

我在共享偏好中保存列表的每个人。由于 List 不能保存在共享首选项中,所以保存为 json 类型。我参考了stackover上的帖子。但是,当读取存储在首选项中的值时,会返回 null。请帮忙。

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:real_lotto/lotto_number.dart';

class DisplayNumber extends StatefulWidget {
  @override
  _DisplayNumberState createState() => _DisplayNumberState();
}

class _DisplayNumberState extends State<DisplayNumber> {
  String _number = '';

  //initState called when the widget is mounted
  void initState() {
    super.initState();
    if (_number == '') {
      loadLotto().then((String s) => setState((() {
            _number = s;
            print(s);
          })));
    }
  }

  @override
  Widget build(BuildContext context) {
    print(_number);
    return Scaffold();
  }
}

Future<void> _saveLotto(number) async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  prefs.setString('key', json.encode(number));
}

Future<String> loadLotto() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  var number = json.decode(prefs.getString('key'));
  return (number);
}

List<dynamic> myNumber() {
  var number = [];
  number.add((List.generate(45, (index) => ++index)..shuffle()).sublist(0, 6));
  number.add((List.generate(45, (index) => ++index)..shuffle()).sublist(0, 6));
  number.add((List.generate(45, (index) => ++index)..shuffle()).sublist(0, 6));
  number.add((List.generate(45, (index) => ++index)..shuffle()).sublist(0, 6));
  number.add((List.generate(45, (index) => ++index)..shuffle()).sublist(0, 6));
  for (var i = 0; i < number.length; i++) {
    number[i].sort();
  }
  _saveLotto(number);
  return number;
}
4

0 回答 0