gpt4 book ai didi

dart - 当在全局变量中使用值时,由于 EdgeInsets.all,Flutter dart 编译失败

转载 作者:IT王子 更新时间:2023-10-29 07:12:44 38 4
gpt4 key购买 nike

错误:

Argument of a constant creation must be constant expressions.

代码:

import 'package:flutter/material.dart';

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

class MyApp extends StatefulWidget{
@override
State<StatefulWidget> createState() {
// TODO: implement createState
return _MyAppState();
}
}

class _MyAppState extends State<MyApp> {
List<String> _products = ['Food Tester'];
var _font_size = 20.0;

build(context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('EasyList'),
),
body: Column(
children: [
Container(
margin: EdgeInsets.all(_font_size),
child: RaisedButton(
onPressed: () {},
child: Text('Add product'),
),
),
Column(children: _products.map((element) =>Card(
child: Column(
children: <Widget>[Image.asset("assets/food.jpg"), Text(element)],
),
)).toList()),

],
),
));
}
}

注意:当参数为静态时,我的意思是 20.0 然后它工作完美,但如果我们将它作为变量,则 Dart 编译失败。这里变量在 EdgeInsets.all 方法中传递,编译失败。

最佳答案

@override
Widget build(BuildContext context) {
const double _font_size = 20;

.....

}

这只是使用常量,所以我们需要将 const 声明为变量。

关于dart - 当在全局变量中使用值时,由于 EdgeInsets.all,Flutter dart 编译失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54074314/

38 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com