How to load theme at beginning in fluttter

无人久伴 提交于 2020-05-11 02:53:14

问题


I want to users can change and save the theme color in my app. However, I have no ideas how to load the saved theme color when the app start running. For example, I want to load the saved theme color directly in the comment place below. I tried SharedPreference. However the SharedPreference instance need to run with await. It seems can't be used here. Is there any way I can load saved theme here directly instead of using setState or something like it?

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Demo',
      theme: // how to load saved theme here?
      ),
      home: new MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

回答1:


This answer goes a bit further. It shows how to load and save theme preferences, how to build a ThemeData, and how to change the theme from a page of your app.


  • Save the user preferences (which theme is selected) using the shared_preferences plugin.
  • Use the "controller pattern" that is used throughout the Flutter framework to provide the currently selected theme (and changes to it) to your app.
  • Use an InheritedWidget to use the controller in any part of your app.

Here is how the controller looks like:

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

/// provides the currently selected theme, saves changed theme preferences to disk
class ThemeController extends ChangeNotifier {
  static const themePrefKey = 'theme';

  ThemeController(this._prefs) {
    // load theme from preferences on initialization
    _currentTheme = _prefs.getString(themePrefKey) ?? 'light';
  }

  final SharedPreferences _prefs;
  String _currentTheme;

  /// get the current theme
  String get currentTheme => _currentTheme;

  void setTheme(String theme) {
    _currentTheme = theme;

    // notify the app that the theme was changed
    notifyListeners();

    // store updated theme on disk
    _prefs.setString(themePrefKey, theme);
  }

  /// get the controller from any page of your app
  static ThemeController of(BuildContext context) {
    final provider = context.inheritFromWidgetOfExactType(ThemeControllerProvider) as ThemeControllerProvider;
    return provider.controller;
  }
}

/// provides the theme controller to any page of your app
class ThemeControllerProvider extends InheritedWidget {
  const ThemeControllerProvider({Key key, this.controller, Widget child}) : super(key: key, child: child);

  final ThemeController controller;

  @override
  bool updateShouldNotify(ThemeControllerProvider old) => controller != old.controller;
}

Here is how you would use the controller and InheritedWidget in your app:

void main() async {
  // load the shared preferences from disk before the app is started
  final prefs = await SharedPreferences.getInstance();

  // create new theme controller, which will get the currently selected from shared preferences
  final themeController = ThemeController(prefs);

  runApp(MyApp(themeController: themeController));
}

class MyApp extends StatelessWidget {
  final ThemeController themeController;

  const MyApp({Key key, this.themeController}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    // use AnimatedBuilder to listen to theme changes (listen to ChangeNotifier)
    // the app will be rebuilt when the theme changes
    return AnimatedBuilder(
      animation: themeController,
      builder: (context, _) {
        // wrap app in inherited widget to provide the ThemeController to all pages
        return ThemeControllerProvider(
          controller: themeController,
          child: MaterialApp(
            title: 'Flutter Demo',
            theme: _buildCurrentTheme(),
            home: MyHomePage(),
          ),
        );
      },
    );
  }

  // build the flutter theme from the saved theme string
  ThemeData _buildCurrentTheme() {
    switch (themeController.currentTheme) {
      case "dark":
        return ThemeData(
          brightness: Brightness.dark,
          primarySwatch: Colors.orange,
        );
      case "light":
      default:
        return ThemeData(
          brightness: Brightness.light,
          primarySwatch: Colors.blue,
        );
    }
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: new AppBar(),
      body: Center(
        child: Column(
          children: <Widget>[
            RaisedButton(
              onPressed: () {
                // thanks to the inherited widget, we can access the theme controller from any page
                ThemeController.of(context).setTheme('light');
              },
              child: Text('Light Theme'),
            ),
            RaisedButton(
              onPressed: () {
                ThemeController.of(context).setTheme('dark');
              },
              child: Text('Dark Theme'),
            )
          ],
        ),
      ),
    );
  }
}



回答2:


You have a few options as to how you'd load it. The first is as Gunter said in a comment - you make MyApp into a stateful widget and load it with initState(), then setState it.

That would look something like this:

class MyApp extends StatefulWidget {
  @override
  MyAppState createState() => MyAppState();
}

class MyAppState extends State<MyApp> {

  ThemeData theme = ThemeData.dark(); // whatever your default is

  @override
  void initState() {
    super.initState();
    SharedProperties.getInstance().then((prefs) {
     ThemeData theme = ThemeData.light(); // load from prefs here
     setState(() => this.theme = theme);
    });
  }

  ...
}

The second option is to use a FutureBuilder.

class MyApp extends StatelessWidget {

  final Future<ThemeData> loadThemeData = SharedPreferences.getInstance().then((prefs) {
     ... get theme from prefs
     return ThemeData.light();
  });


  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      future: loadThemeData,
      builder: (context, snapshot) {
        return MaterialApp(
          theme: snapshot.data,
        );        
      },
      initialData: ThemeData.dark(), // whatever you want your default theme to be
    );
  }
}

The third option is to do the loading before you actually start your app - in your main method. I don't know if this is really recommended as if sharedpreferences takes a while it could delay the start of your app, but realistically it should be very quick and you probably want to avoid a flash different theme showing anyways.

main() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  ThemeData theme = ThemeData.dark(); // get theme from prefs

  runApp(MyApp(
    theme: theme,
  ));
}

class MyApp extends StatelessWidget {
  final ThemeData theme;

  const MyApp({Key key, @required this.theme}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: theme,
      ....
    );
  }
}


来源:https://stackoverflow.com/questions/53105320/how-to-load-theme-at-beginning-in-fluttter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!