const列表文字中的值必须是常量,我在Flutter中将Image添加到Column Widget时遇到了这个错误



为什么我无法在此处添加图像?我在Flutter中向列小工具添加图像时遇到了这个错误。当我删除new关键字时,我会得到另一个错误。请查看此问题。我制作了一个名为assets>图像>girl-icon.jpg。此外,我还启用了pubspec.yaml文件中的资产。

import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'My First Flutter App',
theme: ThemeData(
scaffoldBackgroundColor: Colors.white,
),
home: const WelcomeScreen());
}
}
class WelcomeScreen extends StatelessWidget {
const WelcomeScreen({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('First Page'),
backgroundColor: Colors.amber,
),
body:Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: const <Widget> [
Text("Login",
style: TextStyle(
fontSize: 30,
fontWeight: FontWeight.bold,
)),
new Image.asset("assets/images/girl-icon.jpg"),
],
),
heightFactor: 30,
),
);
}}

请参阅此处的问题截图

const需要一个硬编码的constant值,并且您在构建dynamically时将MyApp调用为常量,这就是它抛出错误的原因。在MyApp之前删除const以解决此问题:

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

以及从这里:

children: <Widget> [
Text("Login",
style: TextStyle(
fontSize: 30,
fontWeight: FontWeight.bold,
)),
new Image.asset("assets/images/girl-icon.jpg"),
]
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'My First Flutter App',
theme: ThemeData(
scaffoldBackgroundColor: Colors.white,
),
home: const WelcomeScreen());
}
}
class WelcomeScreen extends StatelessWidget {
const WelcomeScreen({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('First Page'),
backgroundColor: Colors.amber,
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text("Login",
style: TextStyle(
fontSize: 30,
fontWeight: FontWeight.bold,
)),
Image.asset("assets/images/girl-icon.jpg"),
],
),
heightFactor: 30,
),
);
}
}

我的方法就是删除

const <Widget> 

最新更新