List of data in Flutter is not showing

Issue

I have a list of quotes (three quotes) and am using the map function to map through the list of quotes to create a small widget for each one. But the quotes doesn’t display on the app.

import 'package:flutter/material.dart';

void main() {
  runApp(MaterialApp(
    home: QuoteList(),
  ));
}

class QuoteList extends StatefulWidget {
  const QuoteList({ Key? key }) : super(key: key);

  @override
  State<QuoteList> createState() => _QuoteListState();
}

class _QuoteListState extends State<QuoteList> {

  List<String> quotes = [
    "There are three constants in life.. change, choice and principles.",
    "In three words I can sum up everything Ive learned about life: it goes on.",
    "Guests, like fish, begin to smell after three days."
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey[200],
      appBar: AppBar(
        title: Text('Awesome Quotes'),
        centerTitle: true,
        backgroundColor: Colors.redAccent,
      ),
      body: Column(
        children: quotes.map((e) => Text(e)).toList(),
      ),
    );
  }
}

Solution

Move the quotes variable initialization inside the build method.

class _QuoteListState extends State<QuoteList> {
  @override
  Widget build(BuildContext context) {
    var quotes = [
      "There are three constants in life.. change, choice and principles.",
      "In three words I can sum up everything Ive learned about life: it goes on.",
      "Guests, like fish, begin to smell after three days."
    ];

    return Scaffold(
      backgroundColor: Colors.grey[200],
      appBar: AppBar(
        title: Text('Awesome Quotes'),
        centerTitle: true,
        backgroundColor: Colors.redAccent,
      ),
      body: Column(
        children: quotes.map((e) => Text(e)).toList(),
      ),
    );
  }
}

Also you can use type inference and use var instead of clarifying List<String>.

Answered By – Luka Cerrutti

Answer Checked By – Terry (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *