Flutter snippets - String-Date conversion, Phone Field, PopupMenu

1. Convert Date from one format to another format.

Let's say, I have a date with this format 2022-02-02.
Difficult to read, isn't it? To me it looks like 0202020202 :D
So, it is recommended to convert it to more readable format
e.g. 02-Feb-2022

Following code snippet will take care of it.

String displayDate(String date) {
    var modelDate = DateFormat("yyyy-MM-dd").parse(date);
    return DateFormat("dd-MMM-yyyy").format(modelDate);
}

2. Show Phone number field.



Just copy & paste following method inside your stateful widget & you are good to go.

String number = '';
Widget _numberField() {
  double deviceWidth = MediaQuery.of(context).size.width;
  var textField = TextFormField(
    onChanged: (value) {
      setState(() => number = value);
    },
    keyboardType: TextInputType.phone,
    decoration: const InputDecoration(
      labelText: 'Phone number',
      hintText: '+1 650-555-1234',
    ),
  );
  if (deviceWidth > 600) {
    return SizedBox(
      width: 600,
      child: textField,
    );
  } else {
    return textField;
  }
}

3. Show a pop-up menu button.


PopupMenuButton(
  itemBuilder: (context) => [
    PopupMenuItem(
      child: const Text('Refresh'),
      value: 1,
      onTap: () {
          debugPrint('User tapped on Refresh menu item');
      },
    ),
    PopupMenuItem(
      child: const Text('Filter'),
      value: 2,
      onTap: () {
          debugPrint('User tapped on Filter menu item');
      },
    ),
  ],
),

Hope those code snippets help you some day.
Cheers.

H2
H3
H4
3 columns
2 columns
1 column
Join the conversation now
Logo
Center