3
votes

Déclaration d'un ou plusieurs thèmes personnalisés

J'essaie de créer un thème personnalisé dans un projet de flutter.

J'ai créé un fichier séparé (mycolors.dart) où j'ai défini des couleurs (const myPrimaryColor = const Color (0xFFFF3900); etc etc)

Ensuite, dans main.dart, je fais référence à ces couleurs et à une police personnalisée, mais dans la version Widget ...

Comment puis-je isoler les données du thème (couleurs et styles de police / texte), disons «séparément», et y faire référence dans la classe?

Puis-je également définir 2 thèmes différents et les utiliser plus tard dans le projet?

Merci beaucoup.

import 'package:flutter/material.dart';
import 'package:my_repository/mycolors.dart';
import 'package:flutter_statusbarcolor/flutter_statusbarcolor.dart';

void main() {
  runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    FlutterStatusbarcolor.setStatusBarColor(myPrimaryColor);
    return MaterialApp(
      theme: ThemeData(
        fontFamily: 'Raleway',
        primaryColor: myPrimaryColor,
        accentColor: myAccentColor,
        scaffoldBackgroundColor: myBackgroundColor,
        cardColor: mySurfaceColor,
        textSelectionColor: myPrimaryColor,
        errorColor: myErrorColor,
      ),
      home: Scaffold( ....


2 commentaires

Pouvez-vous répéter "Comment puis-je isoler les données de thème (couleurs et styles de police / texte), hors de la construction du widget?"? Je ne suis pas sûr de comprendre.


Salut, je veux juste déclarer un ensemble indépendant (ou deux) de couleurs + une police, séparément, et y faire référence dans des circonstances différentes, dans l'application. Merci.


3 Réponses :


2
votes

Vous pouvez définir vos thèmes dans une classe, puis appeler ThemeName().theme .

voici comment j'ai un fichier de thème dans mon application:

class StartingPage extends StatefulWidget {
  @override
  _StartingPageState createState() => _StartingPageState();
}

class _StartingPageState extends State<StartingPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Container(
        child: Center(
          child: FlatButton(
            child: Text('change theme to orange'),
            onPressed: () {
              ThemeChanger.setTheme(
                  context,
                  ThemeData(
                    primarySwatch: Colors.orange,
                  ));
            },
          ),
        ),
      ),
    );
  }
}

pour changer votre thème pendant l'exécution, vous devez reconstruire le widget MaterialApp en implémentant un widget avec état supérieur à MaterialApp et peut le reconstruire sur demande.

exemple de mise en œuvre:

class ThemeChangingApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ThemeChanger(
      initialTheme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      materialAppBuilder: (context, theme) {
        return MaterialApp(
          theme: theme,
          home: StartingPage(),
        );
      },
    );
  }
}

alors vous devrez créer votre MaterialApp avec:

class ThemeChanger extends StatefulWidget {
  final ThemeData initialTheme;
  final MaterialApp Function(BuildContext context, ThemeData theme)
      materialAppBuilder;

  const ThemeChanger({Key key, this.initialTheme, this.materialAppBuilder})
      : super(key: key);

  @override
  _ThemeChangerState createState() => _ThemeChangerState();

  static void setTheme(BuildContext context, ThemeData theme) {
    var state = context.ancestorStateOfType(TypeMatcher<_ThemeChangerState>())
        as _ThemeChangerState;
      state.setState(() {
        state.theme = theme;
      });
  }
}

class _ThemeChangerState extends State<ThemeChanger> {
  ThemeData theme;

  @override
  void initState() {
    super.initState();
    theme = widget.initialTheme;
  }

  @override
  Widget build(BuildContext context) {
    return widget.materialAppBuilder(context, theme);
  }
}

et dans votre application, vous pouvez changer le thème comme ceci:

class MuskTheme {

  ...

  ThemeData get theme => ThemeData(
    brightness: Brightness.dark,
    primarySwatch: musk,
    accentColor: accentColor,
    fontFamily: fontFamily,
    backgroundColor: musk,
    canvasColor:canvasColor,
    textTheme: _textTheme,
    iconTheme: _iconTheme,
    cardColor: Color(0xff313A49),
    appBarTheme: AppBarTheme(color: canvasColor,elevation: 0),
    dialogBackgroundColor: canvasColor,
    snackBarTheme: SnackBarThemeData(
      backgroundColor: musk[800],
      actionTextColor: accentColor,
    ),
  );

...

}

ce paquet fait une chose similaire.


1 commentaires

C'était la réponse que je cherchais, elle n'a même pas besoin d'être enveloppée dans une classe.



0
votes

Vous pouvez créer un échafaudage avec un thème différent simplement en le déformant avec un widget Theme :

class StartingPage extends StatefulWidget {
  @override
  _StartingPageState createState() => _StartingPageState();
}

class _StartingPageState extends State<StartingPage> {
  @override
  Widget build(BuildContext context) {
    return Theme(
      data: ThemeData.dark(),
      child: Scaffold(
        appBar: AppBar(),
        body: Container(
          child: Center(
            child: Text('test'),
          ),
        ),
      ),
    );
  }
}


0 commentaires

-2
votes
   final ThemeData customTheme = _buildcustomTheme();

    ThemeData _buildcustomTheme() {

    return customThemeFoundation;

     }

            ThemeData customThemeFoundation =ThemeData(

       brightness: Brightness.dark,
         primaryColor: Color.fromRGBO(40, 204, 86, 1),
       accentColor: Colors.cyan[600],


             fontFamily: 'Georgia',


     textTheme: TextTheme(
             headline1: TextStyle(fontSize: 72.0, fontWeight: FontWeight.bold),
         headline6: TextStyle(fontSize: 36.0, fontStyle: FontStyle.italic),
           bodyText2: TextStyle(fontSize: 14.0, fontFamily: 'Hind'),
               ),
        



   and in main.dart just call it by
           import 'theme.dart';
           and just relpace theme:{.....}  with   theme: customTheme,

0 commentaires