Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter Widget State Constructor Not Running

Tags:

flutter

dart

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 Answers

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(),
      ),
    );
  }
}
like image 85
Günter Zöchbauer Avatar answered Dec 01 '25 06:12

Günter Zöchbauer