RError.com

RError.com Logo RError.com Logo

RError.com Navigation

  • 主页

Mobile menu

Close
  • 主页
  • 系统&网络
    • 热门问题
    • 最新问题
    • 标签
  • Ubuntu
    • 热门问题
    • 最新问题
    • 标签
  • 帮助
主页 / 问题 / 1041610
Accepted
fantik
fantik
Asked:2020-11-02 22:48:37 +0000 UTC2020-11-02 22:48:37 +0000 UTC 2020-11-02 22:48:37 +0000 UTC

如何在颤动中使用共享首选项保存开关小部件状态?

  • 772

有一个 ChangeTheme 类,它有一个切换小部件,可以改变应用程序的主题,但是如果你转到另一个屏幕,然后再次返回带有开关的屏幕,它将不会再次处于活动状态。此外,如果您关闭应用程序,则由开关设置的主题将被重置。如何解决?

更改主题.dart

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



class ChangeTheme extends StatefulWidget{

  ChangeTheme({Key key, this.title}): super(key: key);
  final String title;
  @override
  MyState createState() => new MyState ();

}


class MyState extends State<ChangeTheme>{
  bool val = false;
  String message = "смена темы";
  FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin;

  @override
  Widget build(BuildContext context){
    set();
    return new Scaffold(

        appBar: AppBar(
          title: Text('Настройки'),
        ),
        body: Container(
            child: Column(
              children: <Widget>[
               new Switch(
                 value: val,
                 onChanged: (bool e) => setState(() => something(e)),
                ),
                new Text (message),

                ],
              ),
      ),
    );
  }

 void something(bool e) {
   ThemeChanger _themeChanger = Provider.of<ThemeChanger>(context);
    setState(() {

      if (e){
        _themeChanger.setTheme(ThemeData.dark());
        message = "Темнаяя тема";
        val = e;
        get();

      } else {
        _themeChanger.setTheme(ThemeData.light());
        message = "Светлая тема";
        val = e;
        get();
      }
    });
 }
  get() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    final myBool = prefs.getBool('my_bool_key') ?? false;
  }
  set() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setBool('my_bool_key', true);
  }

}

主要.dart

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

void main() async => runApp(new TodoApp());

class TodoApp extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider<ThemeChanger>(
      builder: (_) => ThemeChanger(ThemeData.light()),
      child: new MaterialAppWithTheme (
      ),
    );
  }
}

class MaterialAppWithTheme extends StatelessWidget {

  @override
  Widget build(BuildContext context) {

    final theme = Provider.of<ThemeChanger>(context);

    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: new TodoList(),
      theme: theme.getTheme(),
    );
  }

}

class TodoList extends StatefulWidget {
  @override
  createState() => new TodoListState();
}

class TodoListState extends State<TodoList> {

  List<String> _todoItems = [];



  @override
  Widget build(BuildContext context) {
    _getPrefs();
    return new Scaffold(
      appBar: new AppBar(title: new Text('Список задач'),
      actions: <Widget>[
      PopupMenuButton<String>(
       onSelected: choiceAction ,
        itemBuilder: (BuildContext context){
         return Constants.choices.map((String choice){
            return PopupMenuItem<String>(
            value: choice,
              child: Text(choice),
            );
         }).toList();
        },
      )
      ]),
      body: _buildTodoList(),

      floatingActionButton: new FloatingActionButton(
          onPressed: _addTodoItem,
          tooltip: 'Add task',
          child: new Icon(Icons.add)),
    );
  }

  Widget _buildTodoList() {
    return new ListView.builder(itemBuilder: (context, index) {
      if (index < _todoItems.length) {
        return _buildTodoItem(_todoItems[index], index);
      }
    });
  }


 void choiceAction(String choice){
    if (choice == Constants.ChangeTheme){
      _changeTheme();


    }

    else if (choice == Constants.OffAd){
      showDialog(
          context: context,
          builder: (BuildContext context) {
            return new AlertDialog(
                title: new Text('Хочешь отключить рекламу?\n\n'
                    'Разработчку и дизайнеру тоже хочеца кушатб, '
                    'поэтому для отключения рекламы отправь деняк. '),
                actions: <Widget>[
                  new FlatButton(
                      child: new Text('подробнее'),
                      onPressed: () => Navigator.of(context).pop()),
                  new FlatButton(
                      child: new Text('нет я жмот'),
                      onPressed: () => Navigator.of(context).pop()),
                ]);
          });


    } else if (choice == Constants.info){
      showDialog(
          context: context,
          builder: (BuildContext context) {
            return new AlertDialog(
                title: new Text('Todo\n'
                                'Разбработчик:  \n'
                                'Дизайнер:  \n'
                                ),
                actions: <Widget>[
                  new FlatButton(
                      child: new Text('оценить'),
                      onPressed: () => Navigator.of(context).pop()),
                  new FlatButton(
                      child: new Text('отмена'),
                      onPressed: () => Navigator.of(context).pop()),
                ]);
          });

    }
 }

 void _changeTheme(){
   Navigator.push(context,
       new MaterialPageRoute(
           builder: (context) => new ChangeTheme()));
 }



  Widget _buildTodoItem(String todoText, int index) {
    return new ListTile(
        title: new Text(todoText), onTap: () => _removeTodoItem(index));
  }

  void _addTodoItem() {
    // Push this page onto the stack
    Navigator.of(context).push(new MaterialPageRoute(builder: (context) {
      return new Scaffold(
          appBar: new AppBar(title: new Text('добавление задачи')),
          body: new TextField(
            autofocus: true,
            onSubmitted: (val) {
              _addItem(val);
              Navigator.pop(context); // Close the add todo screen
            },
            decoration: new InputDecoration(
                hintText: 'Введите вашу задачу',
                contentPadding: const EdgeInsets.all(16.0)),
          ));
    }));
  }

  void _addItem(String task) {
    if (task.length > 0) {
      setState(() => _todoItems.add(task));
      _setPrefs();
    }
  }

  void _removeTodoItem(int index) {
    showDialog(
        context: context,
        builder: (BuildContext context) {
          return new AlertDialog(
              title: new Text('Задача "${_todoItems[index]}" выполнена?'),
              actions: <Widget>[
                new FlatButton(
                    child: new Text('отмена'),
                    onPressed: () => Navigator.of(context).pop()),
                new FlatButton(
                    child: new Text('выполнена'),
                    onPressed: () {
                      _removeItem(index);
                      Navigator.of(context).pop();
                    })
              ]);
        });
  }

  void _removeItem(int index) {
    setState(() => _todoItems.removeAt(index));
    _setPrefs();
  }

  void _setPrefs() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setStringList('TodoList', _todoItems);
  }

  void _getPrefs() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    if (prefs.getStringList('TodoList') != null)
      _todoItems = prefs.getStringList('TodoList');
  }

}

主题.dart

import 'package:flutter/material.dart';

class ThemeChanger with ChangeNotifier {
  ThemeData _themeData;

  ThemeChanger(this._themeData);

  getTheme() => _themeData;
  setTheme(ThemeData theme) {
    _themeData = theme;

    notifyListeners();
  }
}

常量.dart

 class Constants {
  static const String ChangeTheme = 'Настройки';
  static const String info = 'Информация';
  static const String OffAd = 'Отключить рекламу';

  static const List<String> choices = <String>[
    ChangeTheme,
    info,
    OffAd
  ];

}
android
  • 1 1 个回答
  • 10 Views

1 个回答

  • Voted
  1. Best Answer
    MiT
    2020-11-04T18:36:13Z2020-11-04T18:36:13Z

    替换something为onThemeChanged, 调整main以从 读取设置SharedPreferences。并添加了一些小修复以使其正常工作。我不太明白为什么get()和set()在ChangeTheme.dart,我没有碰它。

    主要.dart

    void main() async {
      SharedPreferences.getInstance().then((prefs) {
        var darkModeOn = prefs.getBool('darkMode') ?? true;
        runApp(
          ChangeNotifierProvider<ThemeChanger>(
            builder: (_) =>
                ThemeChanger(darkModeOn ? ThemeData.dark() : ThemeData.light()),
            child: MaterialAppWithTheme(),
          ),
        );
      });
    }
    
    class MaterialAppWithTheme extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        final theme = Provider.of<ThemeChanger>(context);
    
        return MaterialApp(
          debugShowCheckedModeBanner: false,
          home: new TodoList(),
          theme: theme.getTheme(),
        );
      }
    }
    
    class TodoList extends StatefulWidget {
      @override
      createState() => new TodoListState();
    }
    
    class TodoListState extends State<TodoList> {
      List<String> _todoItems = [];
    
      @override
      Widget build(BuildContext context) {
        _getPrefs();
        return new Scaffold(
          appBar: new AppBar(title: new Text('Список задач'), actions: <Widget>[
            PopupMenuButton<String>(
              onSelected: choiceAction,
              itemBuilder: (BuildContext context) {
                return Constants.choices.map((String choice) {
                  return PopupMenuItem<String>(
                    value: choice,
                    child: Text(choice),
                  );
                }).toList();
              },
            )
          ]),
          body: _buildTodoList(),
          floatingActionButton: new FloatingActionButton(
              onPressed: _addTodoItem,
              tooltip: 'Add task',
              child: new Icon(Icons.add)),
        );
      }
    
      Widget _buildTodoList() {
        return new ListView.builder(itemBuilder: (context, index) {
          if (index < _todoItems.length) {
            return _buildTodoItem(_todoItems[index], index);
          }
        });
      }
    
      void choiceAction(String choice) {
        if (choice == Constants.ChangeTheme) {
          _changeTheme();
        } else if (choice == Constants.OffAd) {
          showDialog(
              context: context,
              builder: (BuildContext context) {
                return new AlertDialog(
                    title: new Text('Хочешь отключить рекламу?\n\n'
                        'Разработчку и дизайнеру тоже хочеца кушатб, '
                        'поэтому для отключения рекламы отправь деняк. '),
                    actions: <Widget>[
                      new FlatButton(
                          child: new Text('подробнее'),
                          onPressed: () => Navigator.of(context).pop()),
                      new FlatButton(
                          child: new Text('нет я жмот'),
                          onPressed: () => Navigator.of(context).pop()),
                    ]);
              });
        } else if (choice == Constants.info) {
          showDialog(
              context: context,
              builder: (BuildContext context) {
                return new AlertDialog(
                    title: new Text('Todo\n'
                        'Разбработчик:  \n'
                        'Дизайнер:  \n'),
                    actions: <Widget>[
                      new FlatButton(
                          child: new Text('оценить'),
                          onPressed: () => Navigator.of(context).pop()),
                      new FlatButton(
                          child: new Text('отмена'),
                          onPressed: () => Navigator.of(context).pop()),
                    ]);
              });
        }
      }
    
      void _changeTheme() {
        Navigator.push(context,
            new MaterialPageRoute(builder: (context) => new ChangeTheme()));
      }
    
      Widget _buildTodoItem(String todoText, int index) {
        return new ListTile(
            title: new Text(todoText), onTap: () => _removeTodoItem(index));
      }
    
      void _addTodoItem() {
        // Push this page onto the stack
        Navigator.of(context).push(new MaterialPageRoute(builder: (context) {
          return new Scaffold(
              appBar: new AppBar(title: new Text('добавление задачи')),
              body: new TextField(
                autofocus: true,
                onSubmitted: (val) {
                  _addItem(val);
                  Navigator.pop(context); // Close the add todo screen
                },
                decoration: new InputDecoration(
                    hintText: 'Введите вашу задачу',
                    contentPadding: const EdgeInsets.all(16.0)),
              ));
        }));
      }
    
      void _addItem(String task) {
        if (task.length > 0) {
          setState(() => _todoItems.add(task));
          _setPrefs();
        }
      }
    
      void _removeTodoItem(int index) {
        showDialog(
            context: context,
            builder: (BuildContext context) {
              return new AlertDialog(
                  title: new Text('Задача "${_todoItems[index]}" выполнена?'),
                  actions: <Widget>[
                    new FlatButton(
                        child: new Text('отмена'),
                        onPressed: () => Navigator.of(context).pop()),
                    new FlatButton(
                        child: new Text('выполнена'),
                        onPressed: () {
                          _removeItem(index);
                          Navigator.of(context).pop();
                        })
                  ]);
            });
      }
    
      void _removeItem(int index) {
        setState(() => _todoItems.removeAt(index));
        _setPrefs();
      }
    
      void _setPrefs() async {
        SharedPreferences prefs = await SharedPreferences.getInstance();
        prefs.setStringList('TodoList', _todoItems);
      }
    
      void _getPrefs() async {
        SharedPreferences prefs = await SharedPreferences.getInstance();
        if (prefs.getStringList('TodoList') != null)
          _todoItems = prefs.getStringList('TodoList');
      }
    }
    

    更改主题.dart

    class ChangeTheme extends StatefulWidget {
      ChangeTheme({Key key, this.title}) : super(key: key);
      final String title;
      @override
      MyState createState() => new MyState();
    }
    
    class MyState extends State<ChangeTheme> {
      var _darkTheme = true;
      String message = "смена темы";
      // FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin;
    
      @override
      Widget build(BuildContext context) {
        set();
    
        final themeChanger = Provider.of<ThemeChanger>(context);
        _darkTheme = (themeChanger.getTheme() == ThemeData.dark());
        return new Scaffold(
          appBar: AppBar(
            title: Text('Настройки'),
          ),
          body: Container(
            child: Column(
              children: <Widget>[
                new Switch(
                  value: _darkTheme,
                  onChanged: (val) {
                    setState(() {
                      _darkTheme = val;
                    });
                    onThemeChanged(val, themeChanger);
                  },
                ),
                new Text(message),
              ],
            ),
          ),
        );
      }
    
      void onThemeChanged(bool value, ThemeChanger themeChanger) async {
        (value)
            ? themeChanger.setTheme(ThemeData.dark())
            : themeChanger.setTheme(ThemeData.light());
        var prefs = await SharedPreferences.getInstance();
        prefs.setBool('darkMode', value);
      }
    
      get() async {
        SharedPreferences prefs = await SharedPreferences.getInstance();
        final myBool = prefs.getBool('my_bool_key') ?? false;
      }
    
      set() async {
        SharedPreferences prefs = await SharedPreferences.getInstance();
        prefs.setBool('my_bool_key', true);
      }
    }
    

    主题.dart

    class ThemeChanger with ChangeNotifier {
      ThemeData _themeData;
    
      ThemeChanger(this._themeData);
    
      getTheme() => _themeData;
    
      setTheme(ThemeData themeData) async {
        _themeData = themeData;
        notifyListeners();
      }
    }
    

    UPD:您还可以创建自己的主题并使用它们。例子:

    final darkTheme = ThemeData(
      primarySwatch: Colors.grey,
      primaryColor: Colors.black,
      brightness: Brightness.dark,
      backgroundColor: const Color(0xFF212121),
      accentColor: Colors.white,
      accentIconTheme: IconThemeData(color: Colors.black),
      dividerColor: Colors.black12,
    );
    

    而是ThemeData.dark()使用darkTheme.

    • 3

相关问题

Sidebar

Stats

  • 问题 10021
  • Answers 30001
  • 最佳答案 8000
  • 用户 6900
  • 常问
  • 回答
  • Marko Smith

    根据浏览器窗口的大小调整背景图案的大小

    • 2 个回答
  • Marko Smith

    理解for循环的执行逻辑

    • 1 个回答
  • Marko Smith

    复制动态数组时出错(C++)

    • 1 个回答
  • Marko Smith

    Or and If,elif,else 构造[重复]

    • 1 个回答
  • Marko Smith

    如何构建支持 x64 的 APK

    • 1 个回答
  • Marko Smith

    如何使按钮的输入宽度?

    • 2 个回答
  • Marko Smith

    如何显示对象变量的名称?

    • 3 个回答
  • Marko Smith

    如何循环一个函数?

    • 1 个回答
  • Marko Smith

    LOWORD 宏有什么作用?

    • 2 个回答
  • Marko Smith

    从字符串的开头删除直到并包括一个字符

    • 2 个回答
  • Martin Hope
    Alexandr_TT 2020年新年大赛! 2020-12-20 18:20:21 +0000 UTC
  • Martin Hope
    Alexandr_TT 圣诞树动画 2020-12-23 00:38:08 +0000 UTC
  • Martin Hope
    Air 究竟是什么标识了网站访问者? 2020-11-03 15:49:20 +0000 UTC
  • Martin Hope
    Qwertiy 号码显示 9223372036854775807 2020-07-11 18:16:49 +0000 UTC
  • Martin Hope
    user216109 如何为黑客设下陷阱,或充分击退攻击? 2020-05-10 02:22:52 +0000 UTC
  • Martin Hope
    Qwertiy 并变成3个无穷大 2020-11-06 07:15:57 +0000 UTC
  • Martin Hope
    koks_rs 什么是样板代码? 2020-10-27 15:43:19 +0000 UTC
  • Martin Hope
    Sirop4ik 向 git 提交发布的正确方法是什么? 2020-10-05 00:02:00 +0000 UTC
  • Martin Hope
    faoxis 为什么在这么多示例中函数都称为 foo? 2020-08-15 04:42:49 +0000 UTC
  • Martin Hope
    Pavel Mayorov 如何从事件或回调函数中返回值?或者至少等他们完成。 2020-08-11 16:49:28 +0000 UTC

热门标签

javascript python java php c# c++ html android jquery mysql

Explore

  • 主页
  • 问题
    • 热门问题
    • 最新问题
  • 标签
  • 帮助

Footer

RError.com

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

帮助

© 2023 RError.com All Rights Reserve   沪ICP备12040472号-5