簡體   English   中英

const 列表文字中的值必須是常量,在 Flutter 中將圖像添加到列小部件時出現此錯誤

[英]The values in a const list literal must be constants, I am getting this error while adding an Image to Column Widget in Flutter

為什么我無法在此處添加圖片? 在 Flutter 中將圖像添加到列小部件時出現此錯誤。 當我刪除new關鍵字時,我收到另一個錯誤。 請檢查這個問題。 我創建了一個名為 assets>images>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> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM