繁体   English   中英

如何将数据打印到 ListTile(title: )?

[英]How to print data to ListTile(title: )?

我是 flutter 的新手

如何打印从 getAge() 到 ListTile(title: ) 的数据?

这是代码:

const Divider(),
      const ListTile(
        leading: Icon(Icons.face),
        title: Text(''),
        subtitle: Text('Age'),
      ),
    ];
    return ListView(children: listTiles);
  }
}

void getAge() {
  final DateTime now = DateTime.now();
  final DateTime birthday = DateTime.parse('1985-8-13');

  final age = now.year -
      birthday.year -
      (now.month > birthday.month
          ? 0
          : now.month == birthday.month
              ? now.day >= birthday.day
                  ? 0
                  : 1
              : 1);
  print(age);
}

这是图像:

在此处输入图像描述

您不会“打印”到小部件。 您通过使其从 function 返回来提供它。 将您的 function 更改为

String getAge() {
  final DateTime now = DateTime.now();
  final DateTime birthday = DateTime.parse('1985-8-13');

  final age = now.year -
      birthday.year -
      (now.month > birthday.month
          ? 0
          : now.month == birthday.month
              ? now.day >= birthday.day
                  ? 0
                  : 1
              : 1);
  return age.toString();
}

然后像这样使用

  ListTile(
    leading: Icon(Icons.face),
    title: Text(getAge()),
    subtitle: Text('Age'),
  ),
int intAge = 0; //intialize age here

@override
 void initState() {
  super.initState();
  getAge(); //call in the initState function, it will be called first
}

void getAge() {
  final DateTime now = DateTime.now();
  final DateTime birthday = DateTime.parse('1985-8-13');

  final age = now.year -
      birthday.year -
      (now.month > birthday.month
          ? 0
          : now.month == birthday.month
              ? now.day >= birthday.day
                  ? 0
                  : 1
              : 1);
  intAge = age; //here assign value to intAge
}

const Divider(),
      const ListTile(
        leading: Icon(Icons.face),
        title: Text(intAge.toString()),//change to String
        subtitle: Text('Age'),
      ),
    ];
    return ListView(children: listTiles);
  }
}

你的第一个问题是你的时间格式,你的月份应该是08 ,然后从getAge()返回年龄:

String getAge() {//<-- add this
      final DateTime now = DateTime.now();

      final DateTime birthday = DateTime.parse('1985-08-13');//<-- change month to 08

      final age = now.year -
          birthday.year -
          (now.month > birthday.month
              ? 0
              : now.month == birthday.month
                  ? now.day >= birthday.day
                      ? 0
                      : 1
                  : 1);

      print(age);
      return age.toString();//<-- add this
    }

然后这样称呼它,不要忘记在ListTile之前删除const

ListTile(
    leading: Icon(Icons.face),
    title: Text(getAge()), //<-- add this
    subtitle: Text('Age'),
),

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM