是否有办法在扑朔迷离的LIstView.Builder中将纪元时间戳格式化为人类日期格式?

问题描述 投票:1回答:2

我正在我的应用程序中使用Stripe Payments。我需要显示交易列表和创建交易的日期。所以我为此称呼API。但是API响应中的日期格式为EPOCH时间戳。我必须将其转换为人类可读的日期格式。为此,我正在使用time formatter,在flutter中插入插件。有没有一种方法可以将时间戳转换为日期格式。我已附上以下代码。请告诉我一个解决方案。


import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:time_formatter/time_formatter.dart';
import 'package:rewahub/widgets/comp_search.dart';
import 'package:rewahub/widgets/loading.dart';
import 'package:rewahub/widgets/styles.dart';

class TransactionsPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomPadding: false,
      appBar: new PreferredSize(
        preferredSize: const Size.fromHeight(90.0),
        child: new AppBar(
          // elevation: 0.0,
          centerTitle: false,
          bottom: new PreferredSize(
            child: Column(
              children: <Widget>[
                new Row(
                  mainAxisSize: MainAxisSize.max,
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: <Widget>[
                    Text(
                      "8956",
                      textAlign: TextAlign.left,
                      style: TextStyle(color: Colors.white, fontSize: 18.0),
                    ),
                    Image.asset(
                      'assets/images/rewahub_icon.png',
                      height: 50.0,
                    ),
                    Text(
                      "RS 434.25",
                      style: TextStyle(color: Colors.white, fontSize: 18.0),
                    ),
                  ],
                ),
              ],
            ),
          ),
          flexibleSpace: Container(
            decoration: BoxDecoration(
              gradient: grad,
            ),
          ),
        ),
      ),
      body: Column(
        children: <Widget>[
          Container(
            decoration: BoxDecoration(
              gradient: grad,
            ),
            height: 100.0,
            child: Column(
              children: <Widget>[
                Padding(
                  padding: EdgeInsets.fromLTRB(50, 10, 50, 10),
                ),
                CompSearch(),
                Padding(
                  padding: EdgeInsets.only(left: 30.0),
                ),
                Expanded(
                  child: Align(
                    alignment: Alignment.centerLeft,
                    child: Text(
                      "        Tap the Items for Details",
                      style: TextStyle(
                        fontSize: 15.0,
                        color: Colors.white,
                      ),
                    ),
                  ),
                )
              ],
            ),
          ),
          Expanded(
            child: TransactionBody(),
          )
        ],
      ),
    );
  }
}

class TransactionBody extends StatefulWidget {
  @override
  _TransactionBodyState createState() => _TransactionBodyState();
}

class _TransactionBodyState extends State<TransactionBody> {
  var loading;
  List chargedata;
  Map data;

  final Map<String, String> authdata = {
    'Authorization': 'Bearer sk_test_91jzKPJNlDAb9oviflmUZ7kT00DU51CVeW',
  };
  chargelist() async {
    FirebaseUser userData = await FirebaseAuth.instance.currentUser();
    DocumentReference documentReference = Firestore.instance
        .collection('customer')
        .document(userData.uid)
        .collection('customerprofile')
        .document(userData.uid);
    documentReference.get().then((snaps) async {
      var stripeid;
      stripeid = snaps.data['id'];
      await new Future.delayed(const Duration(seconds: 1));

      await http
          .get("https://api.stripe.com/v1/charges?customer=" + stripeid + "",
              headers: authdata)
          .then((http.Response response) {
        data = json.decode(response.body);
      });
      chargedata = data["data"];
      setState(() {
        loading = false;
      });
      print(chargedata);
    });
  }

  @override
  void initState() {
    chargelist();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: new EdgeInsets.symmetric(vertical: 10.0, horizontal: 25.0),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(6.0),
        border: Border.all(color: Colors.white),
      ),
      child: loading == false
          ? new ListView.builder(
              itemCount: chargedata == null ? 0 : chargedata.length,
              itemBuilder: (BuildContext context, int index) {
                return ListTile(
                  contentPadding: EdgeInsets.only(top: 10, bottom: 10),
                  title: new Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      new Text(
                        "${chargedata[index]["description"]}",
                        style: TextStyle(fontSize: 20, color: Colors.black87),
                      ),
                    ],
                  ),
                  subtitle: new Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      new SizedBox(height: 6.0),
                      new Text(
                        " Date Created",
                        style: TextStyle(fontSize: 15, color: Colors.black54),
                      ),
                      new SizedBox(height: 4.0,),
                      timestamp = formatTime(chargedata[index]["created"]), 

// i am getting error here , while tried to convert it to human timestamp e:The element type 'String' can't be assigned to the list type 'Widget'.dart(list_element_type_not_assignable)//

                      new Text(
                        timestamp.toString(),
                        style: TextStyle(
                          fontSize: 15,
                          color: reddish,
                        ),
                      ),
                    ],
                  ),
                  trailing: Text(
                    "\$ ${chargedata[index]["amount"] / 100}",
                    style: TextStyle(
                      fontSize: 35,
                      color: Colors.blueGrey,
                      fontWeight: FontWeight.normal,
                    ),
                  ),
                  dense: false,
                  onTap: () {
                    print('Notifications');
                  },
                );
              })
          : LoadingPage(),
    );
  }
}

提前感谢。

listview flutter dart stripe-payments epoch
2个回答
1
投票

如果纪元以毫秒为单位,则为

var date = new DateTime.fromMillisecondsSinceEpoch(epoch);

其他方法包括new DateTime.fromMicrosecondsSinceEpoch(epoch);

如果单位是秒,则可能需要使用纪元* 1000

date = new DateTime.fromMillisecondsSinceEpoch(epoch*1000);


1
投票

尝试用Text(formatTime(chargedata[index]["created"]))代替timestamp = formatTime(chargedata[index]["created"])

Flutter希望在那里有一个小部件,但您正在提供一个纯字符串并收到错误。我希望这能解决您的问题。

© www.soinside.com 2019 - 2024. All rights reserved.