flutter 将共享首选项与更改通知程序一起使用

ru9i0ody  于 2023-02-09  发布在  Flutter
关注(0)|答案(2)|浏览(119)

我正在尝试理解如何在更改通知程序中使用共享首选项。我创建了一个基本的应用程序,我想使用共享首选项保存更改通知程序中的一个bool和一个字符串。下面是我的main. dart:

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

void main() {
  runApp(
    MultiProvider(
      providers: [
        ChangeNotifierProvider(create: (_) => GlobalSettings1()),
        ChangeNotifierProvider(create: (_) => SectionSettings1()),
      ],
      child: MyApp(),
    ),
  );
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        debugShowCheckedModeBanner: false,
        initialRoute: '/seventh',
        routes: {
          '/': (context) => Page01(),
          '/first': (context) => Page02(),
          '/second': (context) => Page03(),
        });
  }
}

这是第01页

class _Page01State extends State<Page01> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          InkWell(
            onTap: () {
              context.read<GlobalSettings1>().ToggleSwitch();
            },
            child: Container(
              height: 30,
              width: 80,
              color: context.watch<GlobalSettings1>().toggleSwitch01
                  ? Colors.green
                  : Colors.red,
            ),
          ),
          SizedBox(
            height: 20,
          ),
          InkWell(
              onTap: () {
                showDialog(
                  context: context,
                  builder: (BuildContext context) => Material(
                    color: Colors.transparent,
                    child: Buttons(
                      onTap: (val) {
                        context.read<GlobalSettings1>().StringToSave(val);
                        Navigator.pop(context);
                      },
                    ),
                  ),
                );
              },
              child: Container(
                height: 30,
                width: 80,
                child: Center(
                  child: Text(
                    context.watch()<GlobalSettings1>().stringToSave,
                  ),
                ),
              )),
        ],
      ),
    );
  }
}

最后,这是我的更改通知:

class Buttons extends StatelessWidget {
  const Buttons({Key? key, required this.onTap}) : super(key: key);
  final ValueChanged? onTap;

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        InkWell(
            onTap: () {
              if (onTap != null) {
                onTap!('Choice01');
              }
            },
            child: Container(
              height: 30,
              width: 80,
              child: Text('Choice01'),
            )),
        SizedBox(
          height: 30,
        ),
        InkWell(
            onTap: () {
              if (onTap != null) {
                onTap!('Choice02');
              }
            },
            child: Container(
              height: 30,
              width: 80,
              child: Text('Choice02'),
            )),
      ],
    );
  }
}

class GlobalSettings1 with ChangeNotifier {
  bool _toggleSwitch01 = true;
  String _stringToSave = 'Choice01';

  final SharedPreferences prefs;

  GlobalSettings1({required this.prefs});

  bool get toggleSwitch01 => _toggleSwitch01;
  String get stringToSave => _stringToSave;

  void ToggleSwitch() {
    _toggleSwitch01 = !_toggleSwitch01;
    _setPrefItems();
    notifyListeners();
  }

  void StringToSave(val) {
    _stringToSave = val;
    _setPrefItems();
    notifyListeners();
  }

  void _setPrefItems() {
    prefs.setBool('toggleSwitch01', _toggleSwitch01);
    prefs.setString('stringToSave', _stringToSave);
    notifyListeners();
  }

  void _getPrefItems() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    _stringToSave = prefs.getString('stringToSave') ?? '';
    _toggleSwitch01 = prefs.getBool('autoUpdateVariables') ?? true;
    notifyListeners();
  }

  bool getToggleSwitch01() {
    _getPrefItems();
    return _toggleSwitch01;
  }

  String getStringToSave() {
    _getPrefItems();
    return _stringToSave;
  }
}

正如您所看到的,Page01中有一个bool和一个String,其中bool和String是根据从buttons小部件生成并传递的值显示的。
在看了关于这个问题的其他教程后,我认为我已经正确设置了更改通知程序,但不确定如何设置main. dart和Page01,以便在设置bool和String时,它们在应用程序重新启动时保持原样。
我目前得到一个错误在main. dart:

ChangeNotifierProvider(create: (_) => GlobalSettings1()),

要求我添加必需的参数prefs,但我不确定括号中的代码应该是什么。
非常感谢,任何帮助都将不胜感激。

b1uwtaje

b1uwtaje1#

您需要将SharedPreferences的一个示例传递给您的GlobalSettings1,并将GlobalSettings1更改为:

class GlobalSettings1 with ChangeNotifier {
  bool _toggleSwitch01 = true;
  String _stringToSave = 'Choice01';

  final SharedPreferences prefs;

  GlobalSettings1({required this.prefs});

  bool get toggleSwitch01 => _toggleSwitch01;
  String get stringToSave => _stringToSave;

  void ToggleSwitch() {
    _toggleSwitch01 = !_toggleSwitch01;
    _setPrefItems();
    notifyListeners();
  }

  void StringToSave(val) {
    _stringToSave = val;
    _setPrefItems();
    notifyListeners();
  }

  void _setPrefItems() {
    prefs.setBool('toggleSwitch01', _toggleSwitch01);
    prefs.setString('stringToSave', _stringToSave);
    notifyListeners();
  }

  void _getPrefItems() { // <=== change this
    _stringToSave = prefs.getString('stringToSave') ?? '';
    _toggleSwitch01 = prefs.getBool('autoUpdateVariables') ?? true;
    notifyListeners();
  }

  bool getToggleSwitch01() {
    _getPrefItems();
    return _toggleSwitch01;
  }

  String getStringToSave() {
    _getPrefItems();
    return _stringToSave;
  }
}

然后将您的main更改为:

void main() {   
    SharedPreferences prefs = await SharedPreferences.getInstance();
    runApp(
        MultiProvider(
          providers: [
            ChangeNotifierProvider(create: (_) => GlobalSettings1(prefs: prefs)),
            ChangeNotifierProvider(create: (_) => SectionSettings1()),
          ],
          child: MyApp(),
        ),
    );
}
bnlyeluc

bnlyeluc2#

当前,您正在构造函数上传递示例。

GlobalSettings1({required this.prefs});

当它是SharedPreferences时,您可以使用

class GlobalSettings1 with ChangeNotifier {
  bool _toggleSwitch01 = true;
  String _stringToSave = 'Choice01';

  GlobalSettings1();

  ......

  void _setPrefItems() async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setBool('toggleSwitch01', _toggleSwitch01);
    prefs.setString('stringToSave', _stringToSave);
    notifyListeners();
  }

相关问题