【问题标题】:Flutter - Load variables with SharedPreferencesFlutter - 使用 SharedPreferences 加载变量
【发布时间】:2022-06-29 00:00:19
【问题描述】:

我正在学习如何在 Flutter 中使用 SharedPreferences 库。

我创建了这段代码,我希望在我关闭并重新打开应用程序后将 counter 和 counter2 变量保留为最后一次保存。

但是,当我重新打开应用程序时,counter 和 counter2 值返回 0。 谁能向我解释我哪里出错了?

谢谢。

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

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int counter = 0;
  int counter2 = 0;

  increment() {
    setState(() {
      counter += 1;
      counter2 += 2;
    });
  }

  loadData() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();

    setState(() {
      String? json = prefs.getString('UserData');
      print('loaded json: $json');

      if (json == null) {
        print('NO DATA (null)');
      } else {
        Map<String, dynamic> map = jsonDecode(json);
        print('map $map');
        final data = Data.fromJson(map);
        print('Data ${data.counter}, ${data.counter2}');
      }
    });
  }

  saveData() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();

    final _data = Data(counter: counter, counter2: counter2);

    String json = jsonEncode(_data);
    print('saved json: $json');
    prefs.setString('UserData', json);
  }

  clearData() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.clear();
    print('data cleared');
  }

  /// dichiarare l' initState()
  @override
  void initState() {
    super.initState();
    loadData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Text(
              'You have pushed the button this many times:',
            ),
            Text(
              'c: $counter, c2: $counter2',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          increment();
          saveData();
        },
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

class Data {
  int counter = 0;
  int counter2 = 0;

  Data({required this.counter, required this.counter2});

  Map<String, dynamic> toJson() {
    return {
      'counter': counter,
      'counter2': counter2,
    };
  }

  Data.fromJson(Map<String, dynamic> json) {
    counter = json['counter'];
    counter2 = json['counter2'];
  }
}

【问题讨论】:

    标签: flutter dart sharedpreferences flutter-sharedpreference


    【解决方案1】:

    简短的回答是,当您调用 loadData();' inside initStatethe function is performed asynchronously relative to the rest of the widget, so your Scaffold is built before the data is available. This is why you are seeing the data in from yourprint` 但不在应用程序中时。

    一种解决方法是给我们https://api.flutter.dev/flutter/widgets/FutureBuilder-class.html

    【讨论】:

      猜你喜欢
      • 2021-02-24
      • 1970-01-01
      • 2021-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-11
      • 1970-01-01
      相关资源
      最近更新 更多