颤振共享首选项返回空值

时间:2020-12-27 14:41:22

标签: flutter flutter-sharedpreference

大家 我在共享首选项中保存了列表。 由于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;
}

0 个答案:

没有答案