enjoycode
enjoycode

Reputation: 240

how to save theme settings that have been specified in flutter?

how to save the theme settings that have been specified in flutter?

I'm having problems here. I have difficulty to storing data locally. I tried 'Flutter_Secure_Storage' but I don't understand how to use it. in essence I want the selected theme to be saved locally and when the application is restarted it can use that theme again. I've tried using sharedpreference but it doesn't help.

I will include my source code after this and the image

     @override
    Widget build(BuildContext context) {
    return Scaffold(
      appBar: PreferredSize(
        preferredSize: Size.fromHeight(38.0),
        child: AppBar(
          automaticallyImplyLeading: true,
          title: const Text('Theme'),
          leading: IconButton(
            icon: const Icon(Icons.arrow_back_ios),
            onPressed: () {
              Navigator.pop(context);
            },
          ),
        ),
      ),
      body: new Container(
        child: new Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            //text
            new Container(
              padding: EdgeInsets.all(10.0),
              child: new Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: <Widget>[
                  new Container(
                    padding: EdgeInsets.only(top: 50, left: 10, right: 10),
                    child: new Column(
                      children: <Widget>[
                        //light theme
                        new Row(
                          children: <Widget>[
                            new Column(
                              children: <Widget>[
                                new Container(
                                    width: 120,
                                    height: 200,
                                    color: Color.fromRGBO(255, 127, 80, 5),
                                    child: new Icon(
                                      FontAwesomeIcons.cloudSun,
                                      color: Colors.yellowAccent,
                                      size: 50,
                                    )),
                                new Text(
                                  'Light',
                                  style: TextStyle(fontSize: 16),
                                ),
                                ButtonBar(
                                  alignment: MainAxisAlignment.center,
                                  children: <Widget>[
                                    Radio(
                                      value: 1,
                                      groupValue: selectRadio,
                                      activeColor: Colors.blue,
                                      onChanged: (val) {
                                        //print('Radio $val');

                                        setState(() {
                                          setSelectedRadio(val);
                                          Provider.of<ThemeNotifier>(context).switchTheme();
                                        });
                                      },
                                    )
                                  ],
                                )
                              ],
                            )
                          ],
                        )
                      ],
                    ),
                  ),
                  new Container(
                    padding: EdgeInsets.only(top: 50, left: 10, right: 10),
                    child: new Column(
                      children: <Widget>[
                        //light theme
                        new Row(
                          children: <Widget>[
                            new Column(
                              children: <Widget>[
                                new Container(
                                    width: 120,
                                    height: 200,
                                    color: Color.fromRGBO(173, 216, 230, 5),
                                    child: new Icon(
                                      FontAwesomeIcons.cloudMoon,
                                      color: Color.fromRGBO(2, 22, 69, 5),
                                      size: 50,
                                    )),
                                new Text(
                                  'Dark',
                                  style: TextStyle(fontSize: 16),
                                ),
                                ButtonBar(
                                  alignment: MainAxisAlignment.center,
                                  children: <Widget>[
                                    Radio(
                                      value: 2,
                                      groupValue: selectRadio,
                                      activeColor: Colors.blue,
                                      onChanged: (val) {
                                        //print('Radio $val');

                                        setState(() {
                                          setSelectedRadio(val);
                                          Provider.of<ThemeNotifier>(context).switchTheme();

                                        });
                                      },
                                    )
                                  ],
                                )
                              ],
                            )
                          ],
                        )
                      ],
                    ),
                  )
                ],
              ),
            )
          ],
        ),
      ),
    );
  }

Upvotes: 0

Views: 2316

Answers (1)

chunhunghan
chunhunghan

Reputation: 54367

You can use Package https://pub.dev/packages/theme_provider
this package provide saveThemesOnChange and loadThemeOnInit

You can also save / load theme from disk with ThemeProvider.controllerOf(context).saveThemeToDisk(); and ThemeProvider.controllerOf(context).loadThemeFromDisk();

Run full example code and click Next theme button then restart this app
You will see it start from dark theme

code snippet

return ThemeProvider(
      saveThemesOnChange: true,
      loadThemeOnInit: true,
      themes: <AppTheme>[
        AppTheme.light(),
        AppTheme.dark(),
        customAppTheme(),
      ],
      child: MaterialApp(
        home: ThemeConsumer(
          child: HomePage(),
        ),
      ),
    );
  }

full example code

import 'package:flutter/material.dart';
import 'package:theme_provider/theme_provider.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ThemeProvider(
      saveThemesOnChange: true,
      loadThemeOnInit: true,
      themes: <AppTheme>[
        AppTheme.light(),
        AppTheme.dark(),
        customAppTheme(),
      ],
      child: MaterialApp(
        home: ThemeConsumer(
          child: HomePage(),
        ),
      ),
    );
  }
}

AppTheme customAppTheme() {
  return AppTheme(
    id: "custom_theme",
    description: "Custom Color Scheme",
    data: ThemeData(
      accentColor: Colors.yellow,
      primaryColor: Colors.red,
      scaffoldBackgroundColor: Colors.yellow[200],
      buttonColor: Colors.amber,
      dialogBackgroundColor: Colors.yellow,
    ),
  );
}

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("Example App")),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            RaisedButton(
              child: Text("Next Theme"),
              onPressed: ThemeProvider.controllerOf(context).nextTheme,
            ),
            RaisedButton(
              child: Text("Theme Dialog"),
              onPressed: () {
                showDialog(
                    context: context,
                    builder: (_) => ThemeConsumer(child: ThemeDialog()));
              },
            ),
            RaisedButton(
              child: Text("Second Screen"),
              onPressed: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (_) => ThemeConsumer(child: SecondPage()),
                  ),
                );
              },
            ),
          ],
        ),
      ),
    );
  }
}

class SecondPage extends StatelessWidget {
  const SecondPage({
    Key key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Second Screen"),
      ),
      body: Center(
        child: RaisedButton(
          child: Text("Next Theme"),
          onPressed: ThemeProvider.controllerOf(context).nextTheme,
        ),
      ),
    );
  }
}

demo

enter image description here

Upvotes: 1

Related Questions