skip to Main Content

So, I was just checking out the Buttons docs and trying to create an elevated button, a very basic thing and I followed the guide here to create a basic elevated button. But now I am getting an error on line final ButtonStyle elevatedButtonStyle = ElevatedButton.styleFrom( which is a bit weird cuz I am just following the guide.

Following is the error I get :

Error (Xcode): lib/login.dart:8:58: Error: Method invocation is not a constant expression.

Could not build the application for the simulator.
Error launching application on iPhone 14 Pro Max.

Below is my full dart file as you might see I just started making changes to it,

import 'package:flutter/material.dart';
import 'package:samples/constants/constants.dart';

class LoginPage extends StatelessWidget {

  const LoginPage() : super();

  final ButtonStyle elevatedButtonStyle = ElevatedButton.styleFrom(
    onPrimary: Constants.jaffaOrange,
    primary: Constants.jaffaOrange,
    shape: const RoundedRectangleBorder(
      borderRadius: BorderRadius.all(Radius.circular(2))
    )
  );

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Center(
          child: ElevatedButton(
            style: elevatedButtonStyle,
            onPressed: () { },
            child: Text('Login'),
          ),
        ),
     );
  }
}

I have a feeling I am making a stupid mistake (Been off dart and flutter for a while!)

2

Answers


  1. Chosen as BEST ANSWER

    I ended up marking my style as static since I needed that const constructor

    My final solution looks like:

    final ButtonStyle elevatedButtonStyle = ElevatedButton.styleFrom(
        onPrimary: Constants.jaffaOrange,
        primary: Constants.jaffaOrange,
        shape: const RoundedRectangleBorder(
          borderRadius: BorderRadius.all(Radius.circular(2))
        )
      );
    

  2. Remove const from the constructor as elevatedButtonStyle is initialized with a non-constant value.

    class LoginPage extends StatelessWidget {
    
      LoginPage() : super();
    
      final ButtonStyle elevatedButtonStyle = ElevatedButton.styleFrom(
        onPrimary: Constants.jaffaOrange,
        primary: Constants.jaffaOrange,
        shape: const RoundedRectangleBorder(
          borderRadius: BorderRadius.all(Radius.circular(2))
        )
      );
    ...
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search