How to use Switch Button/Example using Material 3 in Flutter

In any app, UI play is the most important part of user interaction recency flutter introduces or modifies some widgets in material 3. In this article, I will share with you How to use a switch using Material 3.

 

How to enable Material 3 in flutter:

The first step is while we need to use Material 3 widgets then we need to enable useMaterial3: true from ThemeData. You can see below.

return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Errorgram',
      theme: ThemeData(
        useMaterial3: true,//Enable here
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );

 

How to use Material 3 Switch in Flutter :

 Switch(
   materialTapTargetSize:
   MaterialTapTargetSize.shrinkWrap,
   value:value,
   onChanged: (value) async {
                        
     },
 ),

 

Full Example:

import 'dart:io';
import 'dart:ui' as ui;

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:share_plus/share_plus.dart';

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

  @override
  State<Errorgram> createState() => _ErrorgramState();
}

class _ErrorgramState extends State<Errorgram> {
  final GlobalKey globalKey = GlobalKey();
  bool isOnOff = false;

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
        bottom: false,
        child: Scaffold(
            appBar: AppBar(automaticallyImplyLeading: false,centerTitle: true,
              title: Text("Errorgram",),
            ),
            body: Container(
              child: Center(
                child:   Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Text("Reminder",style: TextStyle(fontWeight: FontWeight.bold,fontSize: 20),),
                    SizedBox(width: 10,),
                    Switch(
                      materialTapTargetSize:
                      MaterialTapTargetSize.shrinkWrap,
                      value:isOnOff,
                      onChanged: (value) async {
                        setState(() {
                          isOnOff = value;
                        });
                      },
                    ),
                  ],
                ),
              ),
            )));
  }



}

 

Output:

Conclusion:

We learned How to use Switch Button/Example using Material 3 in a flutter. we also saw how to give support to Material-3 in a flutter. I hope this post may help you.

 

 

Tags: