我是Flutter编程的初学者。我尝试了一个示例,它抛出错误,即返回 null 的构建函数。我的代码有问题吗?
这是我的代码。
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Startup Name Generator',
home: RandomWords(),
);
}
}
class RandomWordsState extends State<RandomWords> {
@override
Widget build(BuildContext context) {
final _suggestions = <WordPair>[];
final _biggerFont = const TextStyle(fontSize: 18.0);
Widget _buildRow(WordPair pair) {
return ListTile(
title: Text(
pair.asPascalCase,
style: _biggerFont,
),
);
}
Widget _buildSuggestions() {
return ListView.builder(
padding: const EdgeInsets.all(16.0),
itemBuilder: /*1*/ (context, i) {
if (i.isOdd) return Divider(); /*2*/
final index = i ~/ 2; /*3*/
if (index >= _suggestions.length) {
_suggestions.addAll(generateWordPairs().take(10));
}
return _buildRow(_suggestions[index]);
});
}
}
}
class RandomWords extends StatefulWidget {
@override
RandomWordsState createState() => RandomWordsState();
}
下面是运行代码时发生的错误。
I/flutter ( 1781): A build function returned null.
I/flutter ( 1781): The offending widget is:
I/flutter ( 1781): RandomWords
I/flutter ( 1781): Build functions must never return null.
I/flutter ( 1781): To return an empty space that causes the building widget to fill available room, return
I/flutter ( 1781): "Container()". To return an empty space that takes as little room as possible, return
I/flutter ( 1781): "Container(width: 0.0, height: 0.0)".
I/flutter ( 1781):
I/flutter ( 1781): The relevant error-causing widget was:
I/flutter ( 1781): RandomWords file:///C:/Users/cyberpunk/flutterProjects/flutter_app/lib/main.dart:11:14
您没有将任何小部件返回给您的build
。您需要在构建中返回一个小部件,在这种情况下_buildSuggestions()
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Startup Name Generator',
home: RandomWords(),
);
}
}
class RandomWordsState extends State<RandomWords> {
final _suggestions = <WordPair>[];
final _biggerFont = const TextStyle(fontSize: 18.0);
@override
Widget build(BuildContext context) {
return _buildSuggestions(); // return a widget
}
Widget _buildRow(WordPair pair) {
return ListTile(
title: Text(
pair.asPascalCase,
style: _biggerFont,
),
);
}
Widget _buildSuggestions() {
return ListView.builder(
padding: const EdgeInsets.all(16.0),
itemBuilder: /*1*/ (context, i) {
if (i.isOdd) return Divider(); /*2*/
final index = i ~/ 2; /*3*/
if (index >= _suggestions.length) {
_suggestions.addAll(generateWordPairs().take(10));
}
return _buildRow(_suggestions[index]);
});
}
}
class RandomWords extends StatefulWidget {
@override
RandomWordsState createState() => RandomWordsState();
}
您没有在build
函数中返回任何内容。添加退货_buildSuggestions()
。