Home > Enterprise >  Flutter non-const constructor error within AppBar when trying to use text inside material app
Flutter non-const constructor error within AppBar when trying to use text inside material app

Time:12-23

Hello I have a quick question, what am I doing wrong here? I am trying to make an AppBar within a Scaffold however when I try to use Text it doesn't seem to work and says to add a Const, however when I do it doesn't solve the issue.

Sorry if there is information out there already for this, I just don't know the specific terms to look up to solve this issue. I know you can put the AppBar in the void main() however I am following a tutorial and would like to do it similarly to that.

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 const MaterialApp(
      home: Scaffold(
          appBar: AppBar(
            title: Text('My First App'),
          ),
          body: Text('This is the body of text.')
      ),
    );
  }
}

This is the error that is outputted:

12:25: Error: Cannot invoke a non-'const' constructor where a const expression is expected. Try using a constructor or factory that is 'const'. appBar: const AppBar( ^^^^^^

New Error:

../../runtime/platform/allocation.cc: 14: error: Out of memory. version=2.14.4 (stable) (Wed Oct 13 11:11:32 2021 0200) on "windows_x64" pid=24408, thread=30512, isolate_group=(nil)(0000000000000000), isolate=(nil)(0000000000000000) isolate_instructions=0, vm_instructions=7ff65bad4f10 pc 0x00007ff65bcdaa42 fp 0x00000056bb8ff3c0 Dart_IsPrecompiledRuntime 0x21a352 -- End of DumpStackTrace

FAILURE: Build failed with an exception.

  • Where: Script 'C:\Users\A\Documents\flutter\packages\flutter_tools\gradle\flutter.gradle' line: 1005

  • What went wrong: Execution failed for task ':app:compileFlutterBuildDebug'.

Process 'command 'C:\Users\A\Documents\flutter\bin\flutter.bat'' finished with non-zero exit value -1073740791

  • Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

CodePudding user response:

Just remove const before Material app


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(
      home: Scaffold(
          appBar: AppBar(
            title: Text('My First App'),
          ),
          body: Text('This is the body of text.')
      ),
    );
  }
}
  • Related