Home > OS >  How do I use this code from the FLutter Engish_Words package?
How do I use this code from the FLutter Engish_Words package?

Time:12-04

I'm trying to learn Flutter (As someone without a lot of programming background) and in a tutorial have just learned how to import the English Words package.

I have tried to use the example code as shown at: https://pub.dev/packages/english_words

The error I receive is: This expression has a type of void so it's value cannot be used. It is the line: nouns.take(50).forEach(print); that gives the error.

This is the code:

import 'package:flutter/material.dart';
import 'package:english_words/english_words.dart';

void main() {
  home: Scaffold(
    body: SafeArea(
      child: Center(
        child: Container(
          child: Text(
              nouns.take(50).forEach(print);
          ),
        ),
      ),
    ),
  );

  }

Thanks for any clues.

CodePudding user response:

Everything in flutter is a Widget as well as Text, used as a child of Container widget.

The error I receive is: This expression has a type of void so its value cannot be used. It is the line: nouns.take(50).forEach(print); that gives the error.

the line: nouns.take(50).forEach(print), actually return a list of 50 most used nouns and printing them. In Dart & Flutter print is a function that return void. void means nothing. so the line nouns.take(50).forEach(print) actually returns nothing but Text Widget requires String in order to display on screen.

CodePudding user response:

The error occurs because nouns returns a List<String> and foreach is a void method, which returns nothing. But your Text requires a String. If you want to display all nouns make use of ListView. Below is a small example.

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final List<String> words = nouns.take(50).toList();

    return MaterialApp(
      home: Scaffold(
        body: ListView.builder(
          itemBuilder: (context, index) => Text(words[index]),
          itemCount: words.length,
        ),
      ),
    );
  }
}
  • Related