flutterconstantsnew-project

Flutter beginner - first time seeing lots of constant blue problems in IDE


My questions relates to this post: Flutter const with const constructors

I've got an issue trying to get rid of the blue squiggly lines under the majority of my widgets plus the MyApp class which I've never seen before. I prefix all the widgets with the const constructor but the issue just shifts to a different area of my code. I don't have this issue when coding in a different project so think it might be something outside the main.dart file.

Screenshots below illustrate errors and my fix attempts.

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


class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        backgroundColor: Colors.teal[900],
        body:  SafeArea(
          child: Center(
            child:  Row(
              children: [
                Expanded(
                  child: Image(
                    image: AssetImage('images/dice1.png'),
                  ),
                ),
                SizedBox(
                  width: 20,
                ),
                Expanded(
                  child: Image(
                    image: AssetImage('images/dice1.png'),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

enter image description here

enter image description here

enter image description here


Solution

  • You should put const keyword possibly highest in the widget tree. So if you've got three constant children inside a list (in a Row in your example), the whole list is a const itself.

    If all children inside a list are constant, put const keyword right before the list.

    So instead of this:

    Row(
      children: [
        const Child1(),
        const Child2(),
        ...
      ],
    )
    

    Do this:

    Row(
      children: const [
        Child1(),
        Child2(),
        ...
      ],
    )
    

    For more information see: https://dart.dev/guides/language/effective-dart/usage#dont-use-const-redundantly