简体   繁体   中英

Save a theme (Flutter/Dart)

Good morning, Here I have two buttons that change the theme of my application (light and dark). When I reload my app the theme is not the one I selected last. I would like the application to back up the last theme used locally. You may need to save just a number that indicates which theme used the last one. . . But I don't know at all how to do this?

Here's the code: main.dart

import 'package:flutter/material.dart';
import 'package:animated_splash_screen/animated_splash_screen.dart';
import 'package:watch/nav.dart';
import 'package:page_transition/page_transition.dart';

import 'package:watch/blocs/theme.dart';
import 'package:provider/provider.dart';


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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider<ThemeChanger>(
      builder: (_) => ThemeChanger(ThemeData.dark()),
      child: MaterialAppWithTheme(),
    );
  }
}

class MaterialAppWithTheme extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final theme = Provider.of<ThemeChanger>(context);
    return MaterialApp(
    debugShowCheckedModeBanner: false,
    theme: theme.getTheme(),

    home: AnimatedSplashScreen(
      duration: 3000,
        splash: "",
        splashTransition: SplashTransition.slideTransition,
        pageTransitionType: PageTransitionType.downToUp,
        nextScreen: Nav(),
    ),
    );
  }
}

settings.dart

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:watch/blocs/theme.dart';
import 'package:watch/constants.dart';

class Parametres extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    ThemeChanger _themeChanger = Provider.of<ThemeChanger>(context);

    return Scaffold(
      appBar: AppBar(
        title: Text('Paramètres', style: kAppBarStyle,), 
        elevation: 0,
        automaticallyImplyLeading: false,
        leading: GestureDetector(
          onTap: () {
            Navigator.pop(context);
          },
          child: Icon(
            Icons.arrow_back,
          ),
        ),
      ),
      body: Container(
        child: Column(
          children: <Widget>[
            FlatButton(
              onPressed: () => _themeChanger.setTheme(
                ThemeData(                 
                  bottomNavigationBarTheme: bNavBar,
                  scaffoldBackgroundColor: kBlackMedium,
                  brightness: Brightness.dark,
                  iconTheme: bIcons,
                )), 
              child: Text('Dark Theme')),
            FlatButton(
              onPressed: () => _themeChanger.setTheme(
                ThemeData(
                  bottomNavigationBarTheme: lNavBar,
                  scaffoldBackgroundColor: Colors.white,
                  brightness: Brightness.light,
                  iconTheme: lIcons,
                  primaryColor: kWhite,
                )), 
              child: Text('Light Theme')),
          ],
        ),
      ),
    );
  }
}

Thank you

使用Shared Preference 包,您可以在那里将简单值存储为键对值。在初始屏幕的 init 中加载该数据,以便您可以根据主题显示屏幕

You should use local memory to save theme.

You can use shared preference or hive db or sqflite or other database system.

About changing theme you can use Cubit,Bloc,Provider or etc or even if ValueNotifier.

However you should wrap your MaterialApp or CupertinoApp with "your state management widget"

And add some Logic

OR you can use some library Library to change theme

Shared preference is best option for it. Since I don't know about your ThemeChanger class I add here my theme class first:

class MyThemeModel extends ChangeNotifier{
  ThemeData _themedata;

  MyThemeModel(bool isActive){
    if(isActive == null){
      getThemeData;
    }
    else{
      if(isActive){
        _themedata = sleepTheme;
      }
      else{
        _themedata = morningTheme;
      }
    }

  }

  ThemeData get getThemeData => _themedata;

  void setThemeData(ThemeData data){
    _themedata = data;
    notifyListeners();
  }
}

In main.dart

void main() async{
  var isSleepActive;
  if(SharedPrefHelper.prefInstance.checkContains(SharedPrefKeys.ISMORNING)){
    isSleepActive = SharedPrefHelper.prefInstance.getBool(SharedPrefKeys.ISMORNING);
  }
  else{
    isSleepActive = false;
  }
  runApp(MultiProvider(
      providers: [
        ChangeNotifierProvider(
          builder: (context) => MyThemeModel(isSleepActive),
        )
      ],
    child: MyApp(),
    )
  );
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: Provider.of<MyThemeModel>(context).getThemeData,
      title: 'Theme App',
      home: AnimatedSplashScreen(
       duration: 3000,
       splash: "",
       splashTransition: SplashTransition.slideTransition,
       pageTransitionType: PageTransitionType.downToUp,
       nextScreen: Nav(),
),
      debugShowCheckedModeBanner: false,
    );
  }

In order to change theme with flat button:

FlatButton(
              onPressed: () => myThemeModel.setThemeData(
                ThemeData(
                  bottomNavigationBarTheme: lNavBar,
                  scaffoldBackgroundColor: Colors.white,
                  brightness: Brightness.light,
                  iconTheme: lIcons,
                  primaryColor: kWhite,
                )), 
              child: Text('Light Theme')),

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM