Search code examples
flutterdartdatetimepickershowtimepicker

How to add two configurations in the showTimePicker build?


I am setting up a showTimePicker and I need to set the theme and time format for it. Both are configured in the widget builder but I do not know how to place both configurations to be returned.

This is the code of the TimePicker configuration, I leave commented the lines of the second configuration that I need to add.

final TimeOfDay selectedTime = await showTimePicker(
  context: context,
  initialTime: TimeOfDay.now(),
  builder: (BuildContext context, Widget child) {
    return (
      MediaQuery(
        data: MediaQuery.of(context).copyWith(alwaysUse24HourFormat: true),
        child: child,
    ));
      /*Theme(
        data: ThemeData.dark().copyWith(
          colorScheme: ColorScheme.dark(
            primary: redColor,
            onPrimary: Colors.white,
            surface: greyColor,
            onSurface: greyVeryLightColor,
          ),
          dialogBackgroundColor: greyLightColor,
        ),
        child: child,
      )*/
  },
);

Both work separately, but I don't know how to merge the settings.


Solution

  • You can simply wrap the child of MediaQuery widget with Theme widget. Please see the code below :

    import 'package:flutter/material.dart';
    
    void main() {
      runApp(MyApp());
    }
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          debugShowCheckedModeBanner: false,
          home: Scaffold(
            appBar: AppBar(title:const Text("Flutter Demo")),
            body: Center(
              child: MyWidget(),
            ),
          ),
        );
      }
    }
    
    class MyWidget extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return RaisedButton(
            onPressed: () async {
              final TimeOfDay selectedTime = await showTimePicker(
                context: context,
                initialTime: TimeOfDay.now(),
                builder: (BuildContext context, Widget child) {
                  return MediaQuery(
                    data: MediaQuery.of(context)
                        .copyWith(alwaysUse24HourFormat: true),
                    child: Theme(
                        data: ThemeData.dark().copyWith(
                          colorScheme: ColorScheme.dark(
                            primary: Colors.red,
                            onPrimary: Colors.white,
                            surface: Colors.grey,
                            onSurface: Colors.grey[100],
                          ),
                          dialogBackgroundColor: Colors.grey[400],
                        ),
                        child: child),
                  );
                },
              );
              print(selectedTime);
            },
            child: const Text("Show Time Picker"));
      }
    }