skip to Main Content

I’m studying platters by myself. When I enter the code like below, it says to use const grammar like the attached picture, how can I add it without errors?

enter image description here


class MyHomePage extends StatelessWidget {
  final String title; //
  MyHomePage({required this.title});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(
          title,
        ),
      ),
      body: Center(
        // child: Image.asset('images/tree.jpg'),
        child: Text(
          'Hello, Text Widget',
          style: TextStyle(
            fontSize: 25,
            color: Colors.purple,
          ),
        ),
      ),
    );
  }
}


Please give me answer bro…
I’m begginner

3

Answers


  1. It is just warring/suggestion message for better practice , you can add const before center

    body: const Center(
      // child: Image.asset('images/tree.jpg'),
      child: Text(
        'Hello, Text Widget',
        style: TextStyle(
          fontSize: 25,
          color: Colors.purple,
        ),
      ),
    ),
    

    But if you read something inside the Center widget, it cant be const.

    Find more about dart.

    Login or Signup to reply.
  2. do this way,

    class MyHomePage extends StatelessWidget {
      final String title; //
      MyHomePage({required this.title});
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text(
              title,
            ),
          ),
          body: const Center(
            // child: Image.asset('images/tree.jpg'),
            child: Text(
              'Hello, Text Widget',
              style: TextStyle(
                fontSize: 25,
                color: Colors.purple,
              ),
            ),
          ),
        );
      }
    }
    

    or

    class MyHomePage extends StatelessWidget {
      final String title; //
      MyHomePage({required this.title});
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text(
              title,
            ),
          ),
          body: Center(
            // child: Image.asset('images/tree.jpg'),
            child: const Text(
              'Hello, Text Widget',
              style: TextStyle(
                fontSize: 25,
                color: Colors.purple,
              ),
            ),
          ),
        );
      }
    }
    
    Login or Signup to reply.
  3. It is good practise to use const keyword, when you know, it not going to change during compile time. In your case add it in Center() widget .

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search