当在全局变量中使用值时,由于 EdgeInsets.all,Flutter dart 编译失败
Flutter dart compiled fail due to EdgeInsets.all when use value in global variable
错误:
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 声明为变量。
错误:
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 声明为变量。