下記のコードを実行しようとすると以下のようなエラーが//here1
で出力されます、
The class 'TopPage' doesn't have an unnamed constructor. (view docs) Try using one of the named constructors defined in 'TopPage'.
Dart
import 'package:flutter/material.dart'; import 'dart:math'; void main() => runApp(TopPage()); //here1 class TopPage extends StatelessWidget { List<Widget> _tiles; _tiles.add(UniqueColorGenerator.getColor());// here2 _tiles.add(UniqueColorGenerator.getColor());;// here2 Widget build(BuildContext context) { return Container( //omit } } class UniqueColorGenerator { static List _colorOptions = [ const Color(0xff2196f3), const Color(0xfff44336), ]; static Random _random = Random(); static Color getColor() { final selectedColor = _colorOptions.removeAt(_random.nextInt(_colorOptions.length)); print(selectedColor); return selectedColor; } }
そこで、上記の"here2"について、以下のように直接List<Widget> _tilesを初期化してあげるとエラーは出力されなくなります。
Dart
class TopPage extends StatelessWidget { // final Color _color = UniqueColorGenerator.getColor(); List<Widget> _tiles=[ UniqueColorGenerator.getColor(), UniqueColorGenerator.getColor() ]; Widget build(BuildContext context) { return Container( color: _color, child: const Padding(padding: EdgeInsets.all(100.0))); } }
diagnostic-messagesを参照すると、
Description
The analyzer produces this diagnostic when an unnamed constructor is invoked on a class that > defines named constructors but the class doesn’t have an unnamed constructor.
名前なしコンストラクタを呼び出そうとしているが、名前なしコンストラクタがないですよ、というメッセージに読み取れます。
オブジェクト指向およびクラスを勉強を初めたばかりで、Language Tourのコンストラクタ部分を読んでも、このエラーの意味・問題点、解決方法がわからないのですが、(基本的なコンストラクタの考え方がわかっておらず申し訳ございませんが)、アドバイス願えますでしょうか?
よろしくお願い申し上げます。
まだ回答がついていません
会員登録して回答してみよう