Home > Software engineering >  Flutter theme not being applied to checkbox
Flutter theme not being applied to checkbox

Time:03-11

I have a checkbox that is not accepting the theme data shown below:

      final acceptTerms = Checkbox(
        value: _acceptIsChecked,
        tristate: false,
        onChanged: (bool? acceptIsChecked) {
          setState(() {
            _acceptIsChecked = acceptIsChecked!;
          });
        },
      );

My theme for the checkbox inside MaterialApp:

 theme: ThemeData(
    primarySwatch: createMaterialColor(Color(0xFFFF0000)),
    backgroundColor: Colors.black,
    fontFamily: 'Arial',
    textTheme: const TextTheme(
      headline1: TextStyle(fontSize: 20.0, fontWeight: FontWeight.bold),
      headline2: TextStyle(fontSize: 15.0, fontStyle: FontStyle.italic),
    ),
    primaryColor: Colors.white,
    checkboxTheme: CheckboxThemeData(
        checkColor: MaterialStateProperty.all(Colors.white),
        fillColor: MaterialStateProperty.all(Colors.orange),
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(45)
      )
    )
  ),

I'm expecting to see the checkbox fill color to be orange and the radius to be round vs square but it's defaulting to a blue fill color and staying square.

I am unable to figure out why. I can add the properties directly to the checkbox widget but I'd rather use a theme but currently it seems that isn't possible?

Full code from the register.dart file

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';


class RegisterPage extends StatefulWidget {
  RegisterPage({Key, key, this.title}) : super(key: key);

  final String? title;

  @override
  _RegisterPageState createState() => _RegisterPageState();
}

class _RegisterPageState extends State<RegisterPage> {


  TextStyle style =
     const TextStyle(fontSize: 20.0);
    
    final _scaffoldKey = GlobalKey<ScaffoldState>();
    bool _waiting = false;
    final _singleton = Singleton();
    bool _acceptIsChecked = false;

  @override
  void initState() {
    super.initState();
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.portraitUp,
      DeviceOrientation.portraitDown,
    ]);
  }

  @override
  Widget build(BuildContext context) {
    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.

    void showInSnackBar(BuildContext context, String value) {
      var sb = SnackBar(content: Text(value));
      _scaffoldKey.currentState!.showSnackBar(sb);
    }

    Widget okButton = MaterialButton(
      color: Theme.of(context).primaryColor,
      child: const Text("OK", style: TextStyle(color: Colors.white)),
      onPressed: () {
        Navigator.of(context).pushReplacementNamed('/login');
      },
    );

    List<Widget> _buildPage(BuildContext context) {
      AlertDialog accountCreatedAlert = AlertDialog(
        title: const Text("Success"),
        backgroundColor: Theme.of(context).backgroundColor,
        contentTextStyle: TextStyle(color: Theme.of(context).primaryColor),
        content: const Text("Account Created! Please login."),
        actions: [
          okButton,
        ],
      );


      final acceptTerms = Checkbox(
        value: _acceptIsChecked,
        activeColor: Colors.white,
        checkColor: Color(0xFF4C4184),
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(15),
        ),
        tristate: false,
        onChanged: (bool? acceptIsChecked) {
          setState(() {
            _acceptIsChecked = acceptIsChecked!;
          });
        },
      );
  

      var page = SingleChildScrollView(
        child: Center(
          child: Padding(
            padding: const EdgeInsets.all(20.0),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.center,
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                Image.asset(
                  "assets/logo.svg",
                  width: 400,
                ),

                Row(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Transform.scale(
                      scale: 2.0,
                      child: Theme(
                          data: ThemeData(unselectedWidgetColor: Colors.grey),
                          child: acceptTerms
                      ),

                    ),
                    const SizedBox(width: 10),
                    const Text("Accept Terms of Service?",
                    style: TextStyle(color: Colors.white))
                  ],
                ),
              ],
            ),
          ),
        ),
      );

      var l = List<Widget>.empty(growable: true);
      l.add(page);

      if (_waiting) {
        var modal = Stack(
          children: const [
            Opacity(
              opacity: 0.3,
              child: ModalBarrier(dismissible: false, color: Colors.grey),
            ),
          ],
        );
        l.add(modal);
      }

      return l;
    }

    return Scaffold(
      resizeToAvoidBottomInset : false,
      body: Container(
          width: double.infinity,
          height: double.infinity,
          decoration: BoxDecoration(
            image: DecorationImage(
              image: AssetImage("assets/background.png"),
              fit: BoxFit.cover,
            ),
          ),
          child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Stack(children: _buildPage(context))
              ]
          )
      ),




        );

  }
}
 

CodePudding user response:

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: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.green,
        backgroundColor: Colors.black,
        fontFamily: 'Arial',
        textTheme: const TextTheme(
          headline1: TextStyle(fontSize: 20.0, fontWeight: FontWeight.bold),
          headline2: TextStyle(fontSize: 15.0, fontStyle: FontStyle.italic),
        ),
        primaryColor: Colors.white,
        checkboxTheme: CheckboxThemeData(
          checkColor: MaterialStateProperty.all(Colors.white),
          fillColor: MaterialStateProperty.all(Colors.orange),
          shape:
              RoundedRectangleBorder(borderRadius: BorderRadius.circular(45)),
        ),
      ),
      home: const ShowCheckBox(),
    );
  }
}

class ShowCheckBox extends StatefulWidget {
  const ShowCheckBox({Key? key}) : super(key: key);

  @override
  State<ShowCheckBox> createState() => _ShowCheckBoxState();
}

class _ShowCheckBoxState extends State<ShowCheckBox> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Transform.scale(
          scale: 3,
          child: Checkbox(
            onChanged: (_) {},
            value: true,
            splashRadius: 50,
            tristate: false,
          ),
        ),
      ),
    );
  }
}

The same code is working for me - Upgrade your flutter sdk.

Open terminal and run the following command: flutter upgrade

Image

CodePudding user response:

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: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.green,
        backgroundColor: Colors.black,
        fontFamily: 'Arial',
        textTheme: const TextTheme(
          headline1: TextStyle(fontSize: 20.0, fontWeight: FontWeight.bold),
          headline2: TextStyle(fontSize: 15.0, fontStyle: FontStyle.italic),
        ),
        primaryColor: Colors.white,
        checkboxTheme: CheckboxThemeData(
          checkColor: MaterialStateProperty.all(Colors.white),
          fillColor: MaterialStateProperty.all(Colors.orange),
          shape:
              RoundedRectangleBorder(borderRadius: BorderRadius.circular(45)),
        ),
      ),
      home: const ShowCheckBox(),
    );
  }
}

class ShowCheckBox extends StatefulWidget {
  const ShowCheckBox({Key? key}) : super(key: key);

  @override
  State<ShowCheckBox> createState() => _ShowCheckBoxState();
}

class _ShowCheckBoxState extends State<ShowCheckBox> {
  final Widget acceptTerms = Checkbox(
    onChanged: (_) {},
    value: true,
    splashRadius: 50,
    tristate: false,
  );

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Transform.scale(
          scale: 3,
          child: acceptTerms,
        ),
      ),
    );
  }
}

This code is almost similar like your code, then to its working properly.Do one thing copy my code, paste it in your machine and then run it, that's only the solution I guess.

Output

  • Related