Flutter Widget状态构造函数未运行

时间:2018-03-09 12:13:20

标签: dart flutter

我的代码:

import 'package:flutter/material.dart';
import '../services.dart';
import 'PersonCard.dart';

class PersonList extends StatefulWidget {  
  PersonList() {
    Services.fetchPeople();
  }

  @override
  _PersonListState createState() => new _PersonListState();
}

class _PersonListState extends State<PersonList> {    
  _PersonListState() {
    print('Helo!?'); // Not running
  }

  @override
  Widget build(BuildContext context) {
    return new Padding(
      padding: new EdgeInsets.all(10.0),
      child: new ListView(
        children: <Widget>[
          // new PersonCard('Bob', 'Wazowski', '2 minutes ago'),
          // new PersonCard('Tim', 'Alan', '5 hours ago'),
          // new PersonCard('Josh', 'Applebee', 'Yesterday'),
        ]
      )
    );
  }
}

基本上,当我的窗口小部件加载PersonList()函数运行时,调用带有Services.fetchPeople()的Web服务。基本上我想要做的是fetchPeople()将返回Map,然后我可以迭代并创建PersonCard个对象。

但是_PersonListState()构造函数没有运行。我错过了一些明显的东西吗?

1 个答案:

答案 0 :(得分:1)

您可以使用widget.people.map((p) => new PersonCard(...))将数据转换为wigets:

class PersonList extends StatefulWidget {  
  PersonList() {
    Services.fetchPeople().then((p) => setState(() => people = p));
  }

  List<Person> people;

  @override
  _PersonListState createState() => new _PersonListState();
}

class _PersonListState extends State<PersonList> {    
  _PersonListState() {
    print('Helo!?'); // Not running
  }

  @override
  Widget build(BuildContext context) {
    return new Padding(
      padding: new EdgeInsets.all(10.0),
      child: new ListView(
        children: widget.people.map(
            (p) => new PersonCard(p.firstName, p.lastName, p.updateTime /* or whatever that is */,
        ).toList(),
      ),
    );
  }
}