美文网首页Flutter圈子
flutter踩坑合集:

flutter踩坑合集:

作者: 汪卫国 | 来源:发表于2020-03-25 00:38 被阅读0次

1. This class (or a class which this class inherits from) is marked as '@immutable', but one or more of its instance fields are not final: IconContainer.icon, IconContainer.color, IconContainer.sizedart(must_be_immutable)

有道翻译为:这个类(或者这个类继承的一个类)被标记为'@不可变的,但是它的一个或多个实例字段不是final: IconContainer.icon。conContainer。颜色,IconContainer。sizedart(必须是不可变的)

解决方案:

  1. 如果变量不是可变的话,就在前面加上final,这样就可以去除警告。
  2. 本案例可见,icon、color和size都是通过实例化时动态传参的,所以是可变的,因此不能在变量声明时加上final。要想去除警告,将无状态组件StatelessWidget替换成有状态组件StatefulWidget

2.构造函数中可选参数的默认值无法生效?

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
    @override
    Widget build(BuildContext context) {
        return MaterialApp(
            home: Scaffold(
            appBar: AppBar(title: Text('Flutter Demo')),
            body: HomeContent(),
        ));
    }
}
// 自定义Icon组件
class HomeContent extends StatelessWidget {
    @override
    Widget build(BuildContext context) {
        return IconContainer(Icons.home);
    }
}
class IconContainer extends StatelessWidget {
    IconData icon;
    Color color;
    double size;
    // 默认构造函数
    IconContainer(IconData icon, {Color color = Colors.yellow, double size = 40.0});

    @override
    Widget build(BuildContext context) {
        return Container(
            width: 100.0,
            height: 100.0,
            margin: EdgeInsets.fromLTRB(0, 20, 0, 0),
            decoration: BoxDecoration(
                color:this.color,
                borderRadius: BorderRadius.circular(10)
            ),
            child: Center(
                child: Icon(
                    Icons.home,
                    size: this.size,
                    color: Colors.white,
                ),
            ),
        );
    }
}

解决方案:

将构造函数写成完成格式,不要简写。

IconContainer(IconData icon, {Color color = Colors.yellow, double size = 40.0}){
        this.icon = icon;
        this.color = color;
        this.size = size;
    }

相关文章

网友评论

    本文标题:flutter踩坑合集:

    本文链接:https://www.haomeiwen.com/subject/muaoyhtx.html