Home > Mobile >  Can't display const text in Flutter
Can't display const text in Flutter

Time:12-12

I am using english-words package and I try to get random word and display it in Text but I got error. What I am doing wrong?

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

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final wordPair = WordPair.random();

    return MaterialApp(
      theme: ThemeData(primaryColor: Colors.purple[900]),
      home: Scaffold(
        appBar: AppBar(title: const Text('WordPair Generator')),
        body: const Center(child: Text(wordPair.asPascalCase))
        ));
  }
}

I get error at Text(wordPair.asPascalCase): Evaluation of this constant expression throws an exception.dart(const_eval_throws_exception)

CodePudding user response:

Remove the const keyword before the Center widget. you cant use a const widget if that widget has a none-constant data/variable at the build time.

Edit: More on const

  • Related