4

My code:

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'),
        ]
      )
    );
  }
}

Basically when my widget loads the PersonList() function runs that calls a web service with Services.fetchPeople(). Basically what I want to do is that fetchPeople() will return a Map which I can then iterate over and create PersonCard objects.

But the _PersonListState() constructor doesn't run. Am I missing something obvious?

1
  • Where or how do you use PersonList? When Services.fetchPeople() returns, should it not return a value? You'd need to assign this value somewhere. Commented Mar 9, 2018 at 12:18

1 Answer 1

1

You can use widget.people.map((p) => new PersonCard(...)) to convert data to 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(),
      ),
    );
  }
}
Sign up to request clarification or add additional context in comments.

4 Comments

I'm getting the error: "The argument type 'Iterable<Map>' can't be assigned to the parameter type 'List<Widget>" when I try to map over widget.people and pass to the 'children' prop
I think I missed a ) (a bit difficult to see without a proper IDE). Iterable sounds like you omitted toList(). Not sure about the <Map> though. Can you update your question and add the concrete code you're using?
But why is the constructor not running? Is it correct?
There is not enough information to answer that. See comment below the original question.