Как настроить выбор даты - PullRequest
0 голосов
/ 14 мая 2018

Я использую метод showDatePicker() для отображения выбора даты в моем приложении флаттера. Как настроить цвета палитры дат?

Вот код моей темы:

class CustomTheme extends Theme {
  /*
   * Colors:
   *    Primary Blue: #335C81 (51, 92, 129)
   *    Light Blue:   #74B3CE (116, 179, 206)
   *    Yellow:       #FCA311 (252, 163, 17)
   *    Red:          #E15554 (255, 85, 84)
   *    Green:        #3BB273 (59, 178, 115)
   */

  static int _fullAlpha = 255;
  static Color blueDark =  new Color.fromARGB(_fullAlpha, 51, 92, 129);
  static Color blueLight = new Color.fromARGB(_fullAlpha, 116, 179, 206);
  static Color yellow =    new Color.fromARGB(_fullAlpha, 252, 163, 17);
  static Color red =       new Color.fromARGB(_fullAlpha, 255, 85, 84);
  static Color green =     new Color.fromARGB(_fullAlpha, 59, 178, 115);

  static Color activeIconColor = yellow;


  CustomTheme(Widget child): super(
    child: child,
    data: new ThemeData(
      primaryColor: blueDark,
      accentColor: yellow,
      cardColor: blueLight,
      backgroundColor: blueDark,
      highlightColor: red,
      splashColor: green
    )
  );
}

Вот мой код для переноса страницы в тему:

  @override
  Widget build(BuildContext context) {
    [...]
    return new CustomTheme(
      new Scaffold(
        [...]
      )
    );
  }

Ответы [ 2 ]

0 голосов
/ 20 июня 2019

Если вы хотите изменить только данные темы для DatePicker, вам нужно обернуть виджет, отвечающий за отображение datePicker внутри виджета Builder, и в конечном итоге обернуть все это внутри виджета Theme, как показано ниже:

PS: Но когда я писал этот ответ, цвет текста («OK / CANCEL») не был принят. Это проблема в рамках флаттера. 19623 - это проблема.

Widget dateOfBirth(String hintText){

    return Theme(
      data: Theme.of(context).copyWith(
        primaryColor: Color(0xFFFF3661), //color of the main banner
        accentColor: Color(0xFFFF3661), //color of circle indicating the selected date
        buttonTheme: ButtonThemeData(
          textTheme: ButtonTextTheme.accent //color of the text in the button "OK/CANCEL"
        ),
      ),
      child: Builder(              // This widget is required for the theme to be applied
        builder: (context){
          return GestureDetector(
            onTap: () async {

              DateTime initialDate = DateTime(DateTime.now().year - 17,DateTime.now().month,DateTime.now().day);

              final picked = await showDatePicker(
                context: context,
                initialDate: initialDate,
                firstDate: DateTime(DateTime.now().year - 100,DateTime.now().month,DateTime.now().day),
                lastDate: DateTime(DateTime.now().year - 17,DateTime.now().month,DateTime.now().day),
              );

              if(picked != null && picked != dobSelected){
                setState(() {
                  dobSelected = picked; // dobSelected is variable to store the selected value
                });
              }

              return picked;
            },
            child: Padding(        //You can use any other widget here
              padding: const EdgeInsets.symmetric(horizontal: 40.0),
              child: Container(
                  height: 55,
                  width: MediaQuery.of(context).size.width,
                  alignment: Alignment.centerLeft,
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.all(Radius.circular(3)),
                    color: Color(0xFFF2F2F2),
                  ),
                  padding: const EdgeInsets.symmetric(horizontal: 13),
                  child: dobSelected == null?Text('Date Of Birth',style: TextStyle(color: widget.isLender?Color(0xFF8B8B8B):Color(0xFFB3B1B1),fontSize: 15),):Text(DateFormat('yyyy-MM-dd').format(dobSelected))
              ),
            ),
          );
        },
      ),
    );
  }

выход

custom datePicker flutter

Надеюсь, это поможет !!!

0 голосов
/ 14 мая 2018

Я предполагаю, что вы хотите настроить средство выбора даты иначе, чем из вашей основной темы. Обычно сборщик даты следует вашей основной теме.

Если это так, оберните кнопку, которая запускает действие, в Builder внутри Theme. Например, вот FAB, который высвечивает оранжевое средство выбора даты (в теме приложения из легких материалов), наследуя остальное от основной темы.

  floatingActionButton: new Theme(
    data: Theme.of(context).copyWith(
          primaryColor: Colors.amber,
        ),
    child: new Builder(
      builder: (context) => new FloatingActionButton(
            child: new Icon(Icons.date_range),
            onPressed: () => showDatePicker(
                  context: context,
                  initialDate: new DateTime.now(),
                  firstDate:
                      new DateTime.now().subtract(new Duration(days: 30)),
                  lastDate: new DateTime.now().add(new Duration(days: 30)),
                ),
          ),
    ),
  ),

Проверьте исходный код date_picker.dart, чтобы увидеть, какие части темы влияют на различные аспекты средства выбора даты.

Если вы просто хотите, чтобы сборщик следовал основной теме, вот рабочий пример

import 'package:flutter/material.dart';

class PickerThemeDemo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(title: const Text('Picker theme demo')),
      body: new Container(),
      floatingActionButton: new FloatingActionButton(
        child: new Icon(Icons.date_range),
        onPressed: () => showDatePicker(
              context: context,
              initialDate: new DateTime.now(),
              firstDate: new DateTime.now().subtract(new Duration(days: 30)),
              lastDate: new DateTime.now().add(new Duration(days: 30)),
            ),
      ),
    );
  }
}

Color hexToColor(int rgb) => new Color(0xFF000000 + rgb);

class CustomTheme extends Theme {
  //Primary Blue: #335C81 (51, 92, 129)
  //Light Blue:   #74B3CE (116, 179, 206)
  //Yellow:       #FCA311 (252, 163, 17)
  //Red:          #E15554 (255, 85, 84)
  //Green:        #3BB273 (59, 178, 115)

  static Color blueDark = hexToColor(0x335C81);
  static Color blueLight = hexToColor(0x74B3CE);
  static Color yellow = hexToColor(0xFCA311);
  static Color red = hexToColor(0xE15554);
  static Color green = hexToColor(0x3BB273);

  CustomTheme(Widget child)
      : super(
          child: child,
          data: new ThemeData(
            primaryColor: blueDark,
            accentColor: yellow,
            cardColor: blueLight,
            backgroundColor: blueDark,
            highlightColor: red,
            splashColor: green,
          ),
        );
}

void main() {
  runApp(
    new MaterialApp(
      home: new CustomTheme(new PickerThemeDemo()),
    ),
  );
}

Если вы хотите применить тему ко всему приложению, ее можно кратко добавить (без использования класса CustomTheme) в приложение Material:

Color hexToColor(int rgb) => new Color(0xFF000000 + rgb);

void main() {
  runApp(
    new MaterialApp(
      theme: new ThemeData(
        brightness: Brightness.light,
        primaryColor: hexToColor(0x335C81),
        accentColor: hexToColor(0xFCA311),
        splashColor: hexToColor(0x3BB273),
      ),
      home: new PickerThemeDemo(),
    ),
  );
} 
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...