Home > Software engineering >  Flutter- split date multilines
Flutter- split date multilines

Time:12-28

I want to display Date into two lines. For example, 22 Dec 2021. I want to display 22 Dec in the first line and 2021 into 2nd line inside a rounded container.

DateFormat('dd MMM yyyy').format(date) contains dateFormat function

Container(
  width: 70.w,
  height: 70.h,
  decoration: BoxDecoration(
                shape: BoxShape.circle,
                color: (index % 2 == 0) ? Colors.white : dateRoundedDisplay,
              ),
 child: Center(child: Text(dateFormat(date: DateTime.parse(items[index].date))),),)

CodePudding user response:

import 'package:intl/intl.dart';

Just need to put \n in the format function

DateTime now = DateTime.now();
formattedDate = DateFormat('dd MMM \n yyyy').format(now);


Center(                   
  child: Text(formattedDate),    
)

                            

CodePudding user response:

You can do this in many ways. The simple solution is:-

Get the datetime:

final date = DateTime.now();

Get individual day, month, and year and concatenate the string and pass to the text widget.

 Text(
      "${date.day}/${date.month}\n ${date.year}",
      textAlign: TextAlign.center
     ),

Note: Don't forget to add \n between month and year so that the year appears in the next line.

Here is the complete example:

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);
  static const String _title = 'Focus Sample';

  @override
  Widget build(BuildContext context) {
    
    // get the current datetime.
    final date = DateTime.now();
    
    
    return MaterialApp(
      title: _title,
      home: Scaffold(
        appBar: AppBar(title: const Text(_title)),
        body: Center(child: Container(
          alignment: Alignment.center,
          decoration: const BoxDecoration(
            shape: BoxShape.circle, 
            color: Colors.red,
          ),
          height: 300,
          width: 300,
          child: Text(
            "${date.day}/${date.month}\n ${date.year}",
            style: const TextStyle(color: Colors.white),
            textAlign: TextAlign.center
          ),
        ),
         )
      ),
    );
  }
}
  • Related