Home > Software design >  I am having error with line const MyHomePage({Key? key, this.title}) : super(key: key);
I am having error with line const MyHomePage({Key? key, this.title}) : super(key: key);

Time:10-13

 import 'package:flutter/material.dart';
    
    void main() => runApp(MyApp());
    
    class MyApp extends StatelessWidget {
       // This widget is the root of your application.
       @override
       Widget build(BuildContext context) {
          return MaterialApp`
             title: 'Hello World Demo Application',
             theme: ThemeData(
                primarySwatch: Colors.blue,
             ),
             home: MyHomePage(title: 'Home page'),
          );
       }
    }
    class MyHomePage extends StatelessWidget {
       const MyHomePage({Key? key, this.title}) : super(key: key);
       final String title;
    
       @override
       Widget build(BuildContext context) {
          return Scaffold(
             appBar: AppBar(
                title: Text(this.title),
             ),
             body: Center(
                child:
                Text(
                   'Hello World',
                )
             ),
          );
       }
    }
    

19:26: Error: The parameter 'title' can't have a value of 'null' because of its type 'String', but the implicit default value is 'null'. Try adding either an explicit non-'null' default value or the 'required' modifier. MyHomePage({Key , this.title}) : super(key: key);

19:47: Error: Getter not found: 'key'. MyHomePage({Key , this.title}) : super(key: key);

CodePudding user response:

Your title is a non-nullable final variable, it can't have null value. You need to mark the title parameter as required:

const MyHomePage({Key? key, required this.title}) : super(key: key);

CodePudding user response:

This code is 100% working. try this.

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Hello World Demo Application',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Home page'),
    );
  }
}

class MyHomePage extends StatelessWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);
  final String title;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(title),
      ),
      body: const Center(
          child: Text(
        'Hello World',
      )),
    );
  }
}

screen shot added

  • Related