How to implement colours dropdown in flutter? - flutter

enter image description here
how to implement this dropdown in flutter?(please refer the image above)
when the dropdown is expanded it should show a list of colours in a circular container.

try this way
import 'package:flutter/material.dart';
const Color darkBlue = Color.fromARGB(255, 18, 32, 47);
void main() {
runApp(MainApp());
}
class MainApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData.dark().copyWith(
scaffoldBackgroundColor: darkBlue,
),
debugShowCheckedModeBanner: false,
home: const Scaffold(
body: Center(
child: MyApp(),
),
),
);
}
}
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
#override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
Color pickColor = Colors.red;
List colorsList = [
Colors.red,
Colors.yellow,
Colors.black,
Colors.pink,
Colors.blue
];
#override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 10),
decoration: BoxDecoration(
color: Colors.white, borderRadius: BorderRadius.circular(8)),
child: DropdownButton(
style: const TextStyle(color: Colors.black),
//Dropdown font color
dropdownColor: Colors.white,
//dropdown menu background color
//dropdown indicator icon
underline: Container(),
//make underline empty
value: pickColor,
onChanged: (value) {
pickColor = value! as Color;
setState(() {});
},
items: colorsList.map((itemone) {
return DropdownMenuItem(
value: itemone,
child: Row(
children: [
const Text(
'Color: ',
style: TextStyle(
color: Colors.black, fontWeight: FontWeight.w700),
),
Container(
height: 20,
width: 20,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
color: itemone))
],
));
}).toList(),
),
);
}
}

Related

How to manage a custom widget state in SingleChildScrollView Widget

I'm trying to design this view.
I already have the basic design of the cards, but i would like to know how to change the card's background color, the card's border color and add the little green square according to the width size of the current card when the user click one of them. It's important to know that only one card can be painted in green when the user clicked it.
Here is my code:
CategoryCardModel
class CategoryCardModel {
final String? categoryCardModelName;
CategoryCardModel(this.categoryCardModelName);
}
CategoryCard
import 'dart:ffi';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
class CategoryCard extends StatelessWidget {
final String? categoryCardName;
final Function()? wasPressed;
const CategoryCard({
super.key,
required this.categoryCardName,
this.wasPressed,
});
#override
Widget build(BuildContext context) {
return GestureDetector(
onTap: wasPressed,
child: Card(
shape: RoundedRectangleBorder(
side: const BorderSide(
color: Color.fromRGBO(212, 213, 215, 100),
width: 3,
),
borderRadius: BorderRadius.circular(20.0),
),
child: Container(
decoration: BoxDecoration(
color: const Color.fromRGBO(242, 243, 243, 100),
borderRadius: BorderRadius.circular(20.0)),
padding: const EdgeInsets.all(10),
child: Text(
categoryCardName ?? 'Todas',
style: const TextStyle(
fontSize: 25,
fontWeight: FontWeight.bold,
color: Color.fromRGBO(91, 94, 99, 100)),
),
),
),
);
}
}
MyHomePage
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'category_card.dart';
import 'category_card_model.dart';
class MyHomePage extends StatefulWidget {
MyHomePage({super.key, required this.title});
final String title;
#override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
// List of models
final categoryCardModelList = <CategoryCardModel>[
CategoryCardModel("Todas"),
CategoryCardModel("Smartphones"),
CategoryCardModel("Accesorios para celular"),
CategoryCardModel("TV")
];
List<CategoryCardModel>? _categoryCardModelListOf;
#override
void initState() {
super.initState();
setState(() {
_categoryCardModelListOf = List.of(categoryCardModelList);
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: SingleChildScrollView(
scrollDirection: Axis.horizontal,
padding: const EdgeInsets.fromLTRB(10.0, 0.0, 10.0, 0.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: _categoryCardModelListOf!
.map<Widget>((categoryCardModel) => CategoryCard(
wasPressed: () {
print("Hello World");
setState(() {});
},
categoryCardName:
categoryCardModel.categoryCardModelName))
.toList())));
}
}
main
import 'package:flutter/material.dart';
import 'my_home_page.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: "Caregory Cards"),
);
}
}
Selected is needed for Card
class CategoryCard extends StatelessWidget {
final String? categoryCardName;
final Function()? wasPressed;
final bool isActive;
const CategoryCard(
{super.key,
required this.categoryCardName,
this.wasPressed,
this.isActive = false});
#override
Widget build(BuildContext context) {
return GestureDetector(
onTap: wasPressed,
child: Card(
shape: const StadiumBorder(),
child: Container(
decoration: BoxDecoration(
color: (isActive ? Colors.green : Colors.grey).withOpacity(.1),
borderRadius: BorderRadius.circular(24.0),
border: Border.all(
width: 2, color: isActive ? Colors.green : Colors.grey)),
padding: const EdgeInsets.all(10),
child: Text(
categoryCardName ?? 'Todas',
style: const TextStyle(
fontSize: 25,
fontWeight: FontWeight.bold,
color: Color.fromRGBO(91, 94, 99, 100)),
),
),
),
);
}
}
Create a state variable for selected model
CategoryCardModel? activeTab;
And use
children: _categoryCardModelListOf!
.map<Widget>((categoryCardModel) => CategoryCard(
isActive: activeTab == categoryCardModel,
wasPressed: () {
activeTab = categoryCardModel;
setState(() {});
},
categoryCardName: categoryCardModel.categoryCardModelName))
.toList(),
),
Update your CategoryCard class like this, you may need to change the color according to your desire :
class CategoryCard extends StatelessWidget {
final String? categoryCardName;
final Function()? wasPressed;
final bool isSelected;
const CategoryCard({
super.key,
required this.categoryCardName,
this.wasPressed,
this.isSelected = false,
});
#override
Widget build(BuildContext context) {
return GestureDetector(
onTap: wasPressed,
child: Card(
shape: RoundedRectangleBorder(
side: BorderSide(
color: isSelected ? Colors.green : Color.fromRGBO(212, 213, 215, 100),
width: 3,
),
borderRadius: BorderRadius.circular(20.0),
),
child: Container(
decoration: BoxDecoration(
color: isSelected ? Colors.greenAccent : const Color.fromRGBO(242, 243, 243, 100),
borderRadius: BorderRadius.circular(20.0),
),
padding: const EdgeInsets.all(10),
child: Text(
categoryCardName ?? 'Todas',
style: const TextStyle(fontSize: 25, fontWeight: FontWeight.bold, color: Color.fromRGBO(91, 94, 99, 100)),
),
),
),
);
}
}
And then change your _MyHomePageState class to this :
class _MyHomePageState extends State<MyHomePage> {
// List of models
final categoryCardModelList = <CategoryCardModel>[
CategoryCardModel("Todas"),
CategoryCardModel("Smartphones"),
CategoryCardModel("Accesorios para celular"),
CategoryCardModel("TV")
];
List<CategoryCardModel>? _categoryCardModelListOf;
CategoryCardModel? _selectedCardModel;
#override
void initState() {
super.initState();
setState(() {
_categoryCardModelListOf = List.of(categoryCardModelList);
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: SingleChildScrollView(
scrollDirection: Axis.horizontal,
padding: const EdgeInsets.fromLTRB(10.0, 0.0, 10.0, 0.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: _categoryCardModelListOf!
.map<Widget>((categoryCardModel) => CategoryCard(
wasPressed: () {
print("Hello World");
setState(() {
_selectedCardModel = categoryCardModel;
});
},
categoryCardName: categoryCardModel.categoryCardModelName,
isSelected: _selectedCardModel == categoryCardModel,
))
.toList(),
),
),
);
}
}
Use above two answers for highlighting selected option...and here is what missing...
The underline below selected tab...
for that update your category card as below,
as u have mentioned underline width must be in size of tab width,
I have used ** IntrinsicWidth**
class CategoryCard extends StatelessWidget {
final String? categoryCardName;
final Function()? wasPressed;
final bool? isselected;
const CategoryCard({
super.key,
required this.categoryCardName,
this.wasPressed,
this.isselected=false
});
#override
Widget build(BuildContext context) {
return GestureDetector(
onTap: wasPressed,
child: IntrinsicWidth(
child: Padding(
padding: EdgeInsets.symmetric(horizontal: 10),
child: Column(children: [
Card(
shape: RoundedRectangleBorder(
side: BorderSide(
color:isselected==true?Colors.red: Color.fromRGBO(212, 213, 215, 100),
width: 3,
),
borderRadius: BorderRadius.circular(20.0),
),
child: Container(
decoration: BoxDecoration(
color: const Color.fromRGBO(242, 243, 243, 100),
borderRadius: BorderRadius.circular(20.0)),
padding: const EdgeInsets.all(10),
child: Text(
categoryCardName ?? 'Todas',
style: const TextStyle(
fontSize: 25,
fontWeight: FontWeight.bold,
color: Color.fromRGBO(91, 94, 99, 100)),
),
),
),
if(isselected==true)
Padding(
padding: EdgeInsets.symmetric(horizontal: 20),
child: Container(
color: Colors.red[200],
height: 5,
),
),
],),
),
),
);
}
}

How to make dropdown list with images and selected item also show with image in flutter?

Tell me how can I make a dropdown list but so that the elements are in the form of cards with an image? It is also necessary that the selected element be displayed without an arrow and with an image.
The following code would do the trick. The DropdownButton accepts DropdownMenuItem as items. And each menu item is customizable with a widget. Just layout an image and the texts and here you go:
Check also the live demo on DartPad
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(),
debugShowCheckedModeBanner: false,
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key});
#override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int? _value = 0;
void _setValue(int? value) {
setState(() {
_value = value;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: const Color.fromRGBO(50, 47, 61, 1),
body: Center(
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 12),
decoration: BoxDecoration(
color: const Color.fromRGBO(57, 56, 69, 1),
borderRadius: BorderRadius.circular(12),
boxShadow: const [
BoxShadow(
color: Colors.black26,
spreadRadius: 5,
blurRadius: 12,
offset: Offset(0, 0))
]),
child: DropdownButton(
itemHeight: 124,
icon: const SizedBox.shrink(),
value: _value,
underline: Container(),
dropdownColor: const Color.fromRGBO(57, 56, 69, 1),
onChanged: _setValue,
borderRadius: BorderRadius.circular(12),
items: [
for (var i = 0; i < 10; i++)
DropdownMenuItem(
value: i,
child: Row(
children: [
ClipRRect(
borderRadius: BorderRadius.circular(8.0),
child: Image(
image: NetworkImage(
'https://source.unsplash.com/random/100x100?sig=$i&cars')),
),
const SizedBox(width: 8),
Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Test title $i',
style: const TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold),
),
const SizedBox(height: 16),
Text(
'Test $i',
style: const TextStyle(color: Colors.white),
),
],
),
],
))
],
),
),
),
);
}
}
import 'package:flutter/material.dart';
class Test extends StatefulWidget {
#override
_TestState createState() => new _TestState();
}
class _TestState extends State<Test> {
var _img = new Image.network("https://upload.wikimedia.org/wikipedia/commons/thumb/8/89/TUCPamplona10.svg/500px-TUCPamplona10.svg.png");
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(title: new Text("Test Drop"),),
body: new Center(
child: new Container (
height: 50.0,
child:new DropdownButton(
items: new List.generate(10, (int index){
return new DropdownMenuItem(child: new Container(
padding: const EdgeInsets.only(bottom: 5.0),
height: 100.0,
child: new Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
_img,
new Text("Under 10")
],
),
));
})
, onChanged: null),),
),
);
}
}
this gif will give you better idea Demo of Code

How to get a bool value (true) if the user's default theme is dark on flutter?

I'm trying to change colors manually in the code when the default theme config is dark.
Does anyone know how can I get a boolean value (true) when the deafult system theme of the user is dark on flutter?
I've spent a lot of time searching in google and pub.dev but I haven't found similar problems.
Here is a example
backgroundColor: _isthemedark ? Colors.blue : Colors.red
here is my code full code
import 'package:flutter/material.dart';
import 'package:hexcolor/hexcolor.dart';
import 'package:flutter/services.dart';
void main() {
SystemChrome.setSystemUIOverlayStyle(
const SystemUiOverlayStyle(statusBarColor: Colors.transparent));///status bar transparent
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
#override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
bool _isObscure = true;
final bool _isthemedark = true;/// HERE IS WHERE I WANT TO CHANGE
#override
Widget build(BuildContext context) {
return MaterialApp(
/// color: HexColor("#fafafa"),
themeMode: ThemeMode.system,
darkTheme: ThemeData.dark(),
home: Scaffold(
backgroundColor: _isthemedark ? HexColor("#2b2e4a") : HexColor("#fafafa"),
body: SafeArea(
child: SingleChildScrollView(
child: Column(
children: [
Row(
children: [
Padding(
padding: const EdgeInsets.only(top: 150, left: 20),
child: Text('Opa!',
style:
TextStyle(fontWeight: FontWeight.bold,
fontSize: 30,
color: _isthemedark ? Colors.white : HexColor("#2b2e4a") ,),),
),
],
),///texto
const SizedBox(
height: 100,
width: 20,
),///blankspace
Padding(
padding: const EdgeInsets.symmetric(horizontal: 30),
child: TextField(
cursorColor: _isthemedark ? Colors.white : Colors.black,
decoration: InputDecoration(
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(
color: _isthemedark? Colors.white : HexColor("#666a7b").withOpacity(0.7))),
labelText: 'Username',
labelStyle: TextStyle(color: HexColor("#666a7b")),
floatingLabelBehavior: FloatingLabelBehavior.always),
),
),///Username field
const SizedBox(
height: 70,
),///blankspace
Padding(
padding: const EdgeInsets.symmetric(horizontal: 30),
child: TextField(
obscureText: _isObscure,
cursorColor: _isthemedark ? Colors.white : Colors.black,
decoration: InputDecoration(
suffixIcon: IconButton(
color: HexColor("#05c46b"),
icon: Icon(_isObscure
? Icons.visibility_off
: Icons.visibility,
color: _isObscure ? HexColor("#fafafa"):HexColor("#05c46b")),
onPressed: () {
setState(() {
_isObscure = !_isObscure;
});
},
),
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(
color: _isthemedark ? Colors.white : HexColor("#666a7b").withOpacity(0.7))),
labelText: 'Password',
labelStyle: TextStyle(color: HexColor("#666a7b")),
floatingLabelBehavior: FloatingLabelBehavior.always),
),
),///password field
const SizedBox(
height: 20,
),///blank space
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
Padding(
padding: const EdgeInsets.symmetric(horizontal: 20),
child: TextButton(
style:TextButton.styleFrom(
alignment: Alignment.topRight,
primary: HexColor("#666a7b")
),
onPressed: () {}, child: const Text('Opa senha?')),
),
],
),///tanso?
Padding(
padding: const EdgeInsets.symmetric(horizontal: 30),
child: SizedBox(
width: 450,
child: TextButton(
child: const Text ('LOGIN'),
onPressed: () {},
style: TextButton.styleFrom(
shadowColor: HexColor("#05c46b"),
elevation: 20,
primary: Colors.white,
backgroundColor: HexColor("#05c46b"),
),
),
),
),///LOGIN button
const SizedBox(
height: 30,
),///blank space
Padding(
padding: const EdgeInsets.symmetric(horizontal: 20),
child: TextButton(
style:TextButton.styleFrom(
alignment: Alignment.topRight,
primary: HexColor("#666a7b")
),
onPressed: () {}, child: const Text('Criar Conta')),
)///criar acc
],
),
),
),
),
);
}
}///Login page
Updated code:
import 'package:flutter/material.dart';
import 'package:hexcolor/hexcolor.dart';
import 'package:flutter/services.dart';
void main() {
SystemChrome.setSystemUIOverlayStyle(
const SystemUiOverlayStyle(statusBarColor: Colors.transparent));
///status bar transparent
runApp(const LoginPage());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return const MaterialApp(
home: LoginPage(),
);
}
}
class LoginPage extends StatefulWidget {
const LoginPage ({Key? key}) : super(key: key);
#override
State<LoginPage> createState() => _LoginPageState();
}
class _LoginPageState extends State<LoginPage> with WidgetsBindingObserver {
late String theme;
var brightness = WidgetsBinding.instance?.window.platformBrightness;
bool _isObscure = true;
late bool _isThemeDark;
#override
void initState() {
WidgetsBinding.instance?.addObserver(this);
if (brightness == Brightness.dark) {
theme = Brightness.dark.toString();
_isThemeDark = true;
} else {
theme = Brightness.light.toString();
_isThemeDark = false;
}
super.initState();
}
#override
void dispose() {
WidgetsBinding.instance?.removeObserver(this);
super.dispose();
}
#override
void didChangePlatformBrightness() {
if (brightness == Brightness.dark) {
theme = Brightness.dark.toString();
_isThemeDark = true;
} else {
theme = Brightness.light.toString();
_isThemeDark = false;
}
}
#override
Widget build(BuildContext context) {
///############## If I put the code above, it crashes (Red Screen)
///final dark = MediaQuery.of(context).platformBrightness == Brightness.dark;
///##############
return MaterialApp(
debugShowCheckedModeBanner: false,
/// color: HexColor("#fafafa"),
themeMode: ThemeMode.system,
darkTheme: ThemeData.dark(),
home: Scaffold(
backgroundColor: _isThemeDark ? HexColor("#2b2e4a") : HexColor("#fafafa"),
body: SafeArea(
child: SingleChildScrollView(
child: Column(
children: [
Row(
children: [
Padding(
padding: const EdgeInsets.only(top: 150, left: 20),
child: Text(
'Opa!',
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 30,
color:
_isThemeDark ? Colors.white : HexColor("#2b2e4a"),
),
),
),
],
),///texto
const SizedBox(
height: 100,
width: 20,
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 30),
child: TextField(
cursorColor: _isThemeDark ? Colors.white : Colors.black,
decoration: InputDecoration(
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(
color: _isThemeDark
? Colors.white
: Colors.black)),
labelText: 'Username',
labelStyle: TextStyle(color: HexColor("#666a7b")),
floatingLabelBehavior: FloatingLabelBehavior.always),
),
),///Username field
const SizedBox(
height: 70,
),///blankspace
Padding(
padding: const EdgeInsets.symmetric(horizontal: 30),
child: TextField(
obscureText: _isObscure,
cursorColor: _isThemeDark ? Colors.white : Colors.black,
decoration: InputDecoration(
suffixIcon: IconButton(
color: HexColor("#05c46b"),
icon: Icon(
_isObscure
? Icons.visibility_off
: Icons.visibility,
color: _isObscure
? HexColor("#fafafa")
: HexColor("#05c46b")),
onPressed: () {
setState(() {
_isObscure = !_isObscure;
});
},
),
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(
color: _isThemeDark
? Colors.white
: Colors.black)),
labelText: 'Password',
labelStyle: TextStyle(color: HexColor("#666a7b")),
floatingLabelBehavior: FloatingLabelBehavior.always),
),
),///password field
const SizedBox(
height: 20,
),///blank space
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
Padding(
padding: const EdgeInsets.symmetric(horizontal: 20),
child: TextButton(
style: TextButton.styleFrom(
alignment: Alignment.topRight,
primary: HexColor("#666a7b")),
onPressed: () {},
child: const Text('Opa senha?')),
),
],
),///tanso?
Padding(
padding: const EdgeInsets.symmetric(horizontal: 30),
child: SizedBox(
width: 450,
child: TextButton(
child: const Text('LOGIN'),
onPressed: () {},
style: TextButton.styleFrom(
shadowColor: HexColor("#05c46b"),
elevation: 20,
primary: Colors.white,
backgroundColor: HexColor("#05c46b"),
),
),
),
),///LOGIN button
const SizedBox(
height: 30,
),///blank space
Padding(
padding: const EdgeInsets.symmetric(horizontal: 20),
child: TextButton(
style: TextButton.styleFrom(
alignment: Alignment.topRight,
primary: HexColor("#666a7b")),
onPressed: () {},
child: const Text('Criar Conta')),
)///criar acc
],
),
),
),
),
);
}
}
Use MediaQuery widget to check whether the platform brightness is dark:
final dark = MediaQuery.of(context).platformBrightness == Brightness.dark;
Put the above line of code inside build method, so when the user changes the system setting, your app will be automatically rebuilt.
Full example as requested, modified from the default flutter counter project, only 2 lines of change:
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.blue,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
#override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
#override
Widget build(BuildContext context) {
/// ################### New line below:
final dark = MediaQuery.of(context).platformBrightness == Brightness.dark;
/// ################### New line above.
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
/// ################### New line below:
Text(dark ? 'Dark Mode' : 'Light Mode'),
/// ################### New line above.
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: const Icon(Icons.add),
),
);
}
}
Adding one line to your code:
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main() {
SystemChrome.setSystemUIOverlayStyle(
const SystemUiOverlayStyle(statusBarColor: Colors.transparent));
///status bar transparent
runApp(const LoginPage());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return const MaterialApp(
home: LoginPage(),
);
}
}
class LoginPage extends StatefulWidget {
const LoginPage({Key? key}) : super(key: key);
#override
State<LoginPage> createState() => _LoginPageState();
}
class _LoginPageState extends State<LoginPage> with WidgetsBindingObserver {
late String theme;
var brightness = WidgetsBinding.instance?.window.platformBrightness;
bool _isObscure = true;
late bool _isThemeDark;
#override
void initState() {
WidgetsBinding.instance?.addObserver(this);
if (brightness == Brightness.dark) {
theme = Brightness.dark.toString();
_isThemeDark = true;
} else {
theme = Brightness.light.toString();
_isThemeDark = false;
}
super.initState();
}
#override
void dispose() {
WidgetsBinding.instance?.removeObserver(this);
super.dispose();
}
#override
void didChangePlatformBrightness() {
if (brightness == Brightness.dark) {
theme = Brightness.dark.toString();
_isThemeDark = true;
} else {
theme = Brightness.light.toString();
_isThemeDark = false;
}
}
#override
Widget build(BuildContext context) {
///#####################################################################
final dark = MediaQuery.of(context).platformBrightness == Brightness.dark;
///#####################################################################
return MaterialApp(
debugShowCheckedModeBanner: false,
themeMode: ThemeMode.system,
darkTheme: ThemeData.dark(),
home: Scaffold(
appBar: AppBar(title: const Text('Login Page')),
body: Center(
child: Text('dark: $dark'),
),
),
);
}
}
Listen to changes using
void didChangePlatformBrightness()
https://docs-flutter-io.firebaseapp.com/flutter/widgets/WidgetsBindingObserver/didChangePlatformBrightness.html
import 'package:flutter/material.dart';
import 'package:hexcolor/hexcolor.dart';
import 'package:flutter/services.dart';
void main() {
SystemChrome.setSystemUIOverlayStyle(
const SystemUiOverlayStyle(statusBarColor: Colors.transparent));
///status bar transparent
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
#override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> with WidgetsBindingObserver {
late String theme;
var brightness = WidgetsBinding.instance?.window.platformBrightness;
bool _isObscure = true;
late bool _isThemeDark;
/// HERE IS WHERE I WANT TO CHANGE
#override
void initState() {
WidgetsBinding.instance?.addObserver(this);
if (brightness == Brightness.dark) {
theme = Brightness.dark.toString();
_isThemeDark = true;
} else {
theme = Brightness.light.toString();
_isThemeDark = false;
}
super.initState();
}
#override
void dispose() {
WidgetsBinding.instance?.removeObserver(this);
super.dispose();
}
#override
void didChangePlatformBrightness() {
if (brightness == Brightness.dark) {
theme = Brightness.dark.toString();
_isThemeDark = true;
} else {
theme = Brightness.light.toString();
_isThemeDark = false;
}
}
#override
Widget build(BuildContext context) {
print("CHECK CONSOLE");
print(theme);
print(_isThemeDark);
return MaterialApp(
/// color: HexColor("#fafafa"),
themeMode: ThemeMode.system,
darkTheme: ThemeData.dark(),
home: Scaffold(
backgroundColor: _isThemeDark ? HexColor("#2b2e4a") : HexColor("#fafafa"),
body: SafeArea(
child: SingleChildScrollView(
child: Column(
children: [
Row(
children: [
Padding(
padding: const EdgeInsets.only(top: 150, left: 20),
child: Text(
'Opa!',
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 30,
color:
_isThemeDark ? Colors.white : HexColor("#2b2e4a"),
),
),
),
],
),
///texto
const SizedBox(
height: 100,
width: 20,
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 30),
child: TextField(
cursorColor: _isThemeDark ? Colors.white : Colors.black,
decoration: InputDecoration(
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(
color: _isThemeDark
? Colors.white
: HexColor("#666a7b").withOpacity(0.7))),
labelText: 'Username',
labelStyle: TextStyle(color: HexColor("#666a7b")),
floatingLabelBehavior: FloatingLabelBehavior.always),
),
),
///Username field
const SizedBox(
height: 70,
),
///blankspace
Padding(
padding: const EdgeInsets.symmetric(horizontal: 30),
child: TextField(
obscureText: _isObscure,
cursorColor: _isThemeDark ? Colors.white : Colors.black,
decoration: InputDecoration(
suffixIcon: IconButton(
color: HexColor("#05c46b"),
icon: Icon(
_isObscure
? Icons.visibility_off
: Icons.visibility,
color: _isObscure
? HexColor("#fafafa")
: HexColor("#05c46b")),
onPressed: () {
setState(() {
_isObscure = !_isObscure;
});
},
),
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(
color: _isThemeDark
? Colors.white
: HexColor("#666a7b").withOpacity(0.7))),
labelText: 'Password',
labelStyle: TextStyle(color: HexColor("#666a7b")),
floatingLabelBehavior: FloatingLabelBehavior.always),
),
),
///password field
const SizedBox(
height: 20,
),
///blank space
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
Padding(
padding: const EdgeInsets.symmetric(horizontal: 20),
child: TextButton(
style: TextButton.styleFrom(
alignment: Alignment.topRight,
primary: HexColor("#666a7b")),
onPressed: () {},
child: const Text('Opa senha?')),
),
],
),
///tanso?
Padding(
padding: const EdgeInsets.symmetric(horizontal: 30),
child: SizedBox(
width: 450,
child: TextButton(
child: const Text('LOGIN'),
onPressed: () {},
style: TextButton.styleFrom(
shadowColor: HexColor("#05c46b"),
elevation: 20,
primary: Colors.white,
backgroundColor: HexColor("#05c46b"),
),
),
),
),
///LOGIN button
const SizedBox(
height: 30,
),
///blank space
Padding(
padding: const EdgeInsets.symmetric(horizontal: 20),
child: TextButton(
style: TextButton.styleFrom(
alignment: Alignment.topRight,
primary: HexColor("#666a7b")),
onPressed: () {},
child: const Text('Criar Conta')),
)
///criar acc
],
),
),
),
),
);
}
}

Flutter theme not being applied to checkbox

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))
]
)
),
);
}
}
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
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

How to customize Dropdown Button and items in flutter?

Today I tried to design a dropdown button with customized items in it where I can select all items or deselect all items with one click. But I didn't understand the approach how to do it. So please help me guys how to approach the required design and below I placed my design and required design.
and here is my code
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
String dropdownvalue = 'Apple';
var items = ['Apple','Banana','Grapes','Orange','watermelon','Pineapple'];
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("DropDownList Example"),
),
body: Container(
padding: EdgeInsets.all(10.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text("DropDownButton"),
Container(
height: 40,
padding: EdgeInsets.all(5.0),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(30.0),
border: Border.all(
color: Colors.grey, style: BorderStyle.solid, width: 0.80),
),
child: DropdownButtonHideUnderline(
child: DropdownButton(
elevation: 0,
value: dropdownvalue,
icon: Icon(Icons.keyboard_arrow_down),
items:items.map((String items) {
return DropdownMenuItem(
value: items,
child: Text(items)
);
}
).toList(),
onChanged: (String? newValue){
setState(() {
dropdownvalue = newValue!;
});
},
),
),
),
],
),
],
),
),
);
}
}
You can use dropdown_button2 package for this:
import 'package:flutter/material.dart';
import 'package:dropdown_button2/dropdown_button2.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
String dropdownvalue = 'Apple';
var items = [
'Apple',
'Banana',
'Grapes',
'Orange',
'watermelon',
'Pineapple'
];
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("DropDownList Example"),
),
body: Container(
padding: EdgeInsets.all(10.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text("DropDownButton"),
Container(
height: 40,
padding: EdgeInsets.all(5.0),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(30.0),
border: Border.all(color: Colors.grey, style: BorderStyle.solid, width: 0.80),
),
child: DropdownButtonHideUnderline(
child: DropdownButton2(
hint: Text(
'Select Item',
style: TextStyle(
fontSize: 14,
color: Theme.of(context).hintColor,
),
),
items: items
.map((item) => DropdownMenuItem<String>(
value: item,
child: Text(
item,
style: const TextStyle(
fontSize: 14,
),
),
))
.toList(),
value: dropdownvalue,
onChanged: (String? newValue) {
setState(() {
dropdownvalue = newValue!;
});
},
buttonHeight: 40,
buttonWidth: 140,
itemHeight: 40,
),
)),
],
),
],
),
),
);
}
}
final result: