Flutter VLC Player with options - flutter

import 'package:flutter/material.dart';
import 'package:flutter_vlc_player/flutter_vlc_player.dart';
class Home extends StatefulWidget {
#override
_ExampleVideoState createState() => _ExampleVideoState();
}
class _ExampleVideoState extends State<Home> {
final VlcPlayerController controller = new VlcPlayerController.network(url);
#override
Widget build(BuildContext context) {
return Scaffold(
body: SizedBox(
height: 100,
width: 40,
child: new VlcPlayer(
aspectRatio: 16 / 9,
options : VlcPlayeroptions(),
controller: controller,
placeholder: Center(child: CircularProgressIndicator()),
)
)
);
}
}
this is my example where video is playing good, but i need to add options to it like play and pause, "options" is not working
i need to add play and pause button on vlc player in flutter app

Add a widget that sends play/pause through the controller class. Check out the other available methods too for the VlcPlayerController class.
ElevatedButton.icon(
onPressed: () => controller.pause(),
icon: const Icon(Icons.pause),
label: const Text('Pause'))

import 'package:flutter/material.dart';
import 'package:flutter_vlc_player/flutter_vlc_player.dart';
class Home extends StatefulWidget {
#override
_ExampleVideoState createState() => _ExampleVideoState();
}
class _ExampleVideoState extends State<Home> {
late bool _isplaying = true;
final VlcPlayerController controller = VlcPlayerController.network(
"url",
hwAcc: HwAcc.auto,
options: VlcPlayerOptions(),
);
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(children: <Widget>[
SizedBox(
width: MediaQuery.of(context).size.width,
height: 225,
child: VlcPlayer(
aspectRatio: 16 / 9,
controller: controller,
placeholder: const Center(child: CircularProgressIndicator()),
),
),
Container(
child: Row(mainAxisAlignment: MainAxisAlignment.center, children: [
if (_isplaying)
TextButton(
onPressed: () {
controller.pause();
setState(() {
_isplaying = false;
});
},
child: const Icon(
Icons.play_arrow,
size: 50,
),
)
else
TextButton(
onPressed: () {
setState(() {
_isplaying = true;
controller.play();
});
},
child: Icon(
Icons.pause,
size: 50,
),
),
]),
),]
);
}
}
This is how i get it work done

Related

Flutter not rendering page correctly when page is called after camera is used

I've been building an app in flutter for the past while and recently I added camera functionality. I've a button on my home page that directs me to a camera page with the camera preview, on the camera preview page I have a home icon which directs back to the home page.
I've noticed when I click the home page from the camera page it doesn't render correctly, I've multiple calls to the home page throughout the project and they all work fine its only when accessing from the camera page. I added then((value) => setState(() {})); to try and reset the state of the home page and I can see its being called but with no luck regarding the rendering[![enter image description here][1]][1]
I've added a picture of the Home Screen render issue, its worth noting im getting no errors on Xcode.
Camera screen code:
import 'package:camera/camera.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:moodful/Screens/HomeScreen/home_screen.dart';
import 'package:moodful/Screens/Login/login_screen.dart';
import 'package:moodful/main.dart';
import '../constants.dart';
class CameraPage extends StatefulWidget {
final List<CameraDescription>? cameras;
const CameraPage({this.cameras, Key? key}) : super(key: key);
#override
_CameraPageState createState() => _CameraPageState();
}
class _CameraPageState extends State<CameraPage> {
late CameraController controller;
// used to increment camera switch tap
int cameraIconTap = 0;
XFile? pictureFile;
#override
void initState() {
super.initState();
controller = CameraController(
widget.cameras![0],
ResolutionPreset.veryHigh,
);
controller.initialize().then((_) {
if (!mounted) {
return;
}
setState(() {});
});
}
#override
void dispose() {
controller.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
var size = MediaQuery.of(context).size;
if (!controller.value.isInitialized) {
return const SizedBox(
child: Center(
child: CircularProgressIndicator(),
),
);
}
return Scaffold(
appBar: AppBar(
backgroundColor: kPrimaryColor,
centerTitle: true,
title: Text('AppBar'),
leading: IconButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (BuildContext context) => HomeScreen()),
).then((value) => setState(() {}));
print("refresh done ");
},
icon: Icon(Icons.home),
),
actions: [
IconButton(
onPressed: () {
//increment on tap, calculate modulus, pass to widget.camera. 0 == rear camera, 1 == front camera
cameraIconTap++;
int modulusTap;
modulusTap = cameraIconTap % 2;
if (widget.cameras!.length > 1) {
setState(() {
controller = CameraController(
widget.cameras![modulusTap], ResolutionPreset.veryHigh);
});
controller.initialize().then((_) {
if (!mounted) {
return;
}
setState(() {});
});
} else {
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
content: Text('No secondary camera found'),
duration: Duration(seconds: 2),
));
}
},
icon: const Icon(Icons.cameraswitch),
),
],
),
body: Center(
child: Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.fromLTRB(8.0, 20.0, 8.0, 8.0),
child: Column(
children: [
Center(
child: SizedBox(
height: //400
size.height / controller.value.aspectRatio,
width: size.width * 1.3 / controller.value.aspectRatio,
child: AspectRatio(
aspectRatio: controller.value.aspectRatio,
child: CameraPreview(controller),
),
),
),
],
),
),
//),
Padding(
padding: const EdgeInsets.all(8.0),
child: ElevatedButton(
onPressed: () async {
pictureFile = await controller.takePicture();
setState(() {});
},
child: const Text('Capture Image'),
),
),
if (pictureFile != null)
Image.network(
pictureFile!.path,
height: 200,
)
//Android/iOS
// Image.file(File(pictureFile!.path)))
],
)));
}
}
Home Screen code:
import 'package:camera/camera.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:moodful/components/background.dart';
import 'package:moodful/Screens/Login/login_screen.dart';
import 'package:moodful/components/camera_screen.dart';
import 'package:moodful/main.dart';
class HomeScreen extends StatefulWidget {
HomeScreen({Key? key}) : super(key: key);
#override
State<HomeScreen> createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
Future<DocumentSnapshot<Map<String, dynamic>>>? _fetchedData;
#override
void initState() {
super.initState();
_fetchedData = getData();
}
#override
Widget build(BuildContext context) {
Size size = MediaQuery.of(context).size;
return FutureBuilder(
future: _fetchedData,
builder: (BuildContext context,
AsyncSnapshot<DocumentSnapshot<Map<String, dynamic>>> snapshot) {
if (snapshot.hasData) {
return BackgroundLogoRight(
text: "Home",
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Spacer(),
Expanded(
flex: 5,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Expanded(
flex: 10,
child: Text(
"${snapshot.data!.data()!["firstName"]} \n\n "
"Glad you're back, please enter a mood for today.\n\n "
"Be sure to check the insights page for the most up to date mood analysis\n\n"
"The more you know the more control you have",
style: TextStyle(color: Colors.black, fontSize: 15),
textAlign: TextAlign.center,
),
),
],
),
),
Expanded(
flex: 5,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
GestureDetector(
onTap: () async {
await availableCameras().then(
(value) => Navigator.push(
context,
MaterialPageRoute(
builder: (context) => CameraPage(
cameras: value,
),
),
),
);
}, // handle your image tap here
child: Image.asset(
"assets/images/recordMoodLogo.jpg",
width: size.width * 0.5,
fit: BoxFit.cover, // this is the solution for border
height: 110.0,
),
),
],
),
),
],
),
);
} else {
return CircularProgressIndicator();
}
},
);
}
Future<DocumentSnapshot<Map<String, dynamic>>> getData() async {
var currentUser = FirebaseAuth.instance.currentUser;
return await FirebaseFirestore.instance
.collection('USER_TABLE')
.doc(currentUser!.uid)
.get();
}
}
Thanks!
[1]: https://i.stack.imgur.com/pbC0w.png

How change the Icon of an IconButton when it is pressed

I want to know how I can change the Icon of an IconButton when it is pressed. (Favorite_border to Favorite). I tried somethings but it doesn't works.
Maybe it is easy but I am a beginner and I don't understand very well how it is works.
Update
import 'package:flutter/material.dart';
import 'package:cached_network_image/cached_network_image.dart';
import '../recyclerview/data.dart';
import 'package:watch/constants.dart';
int itemCount = item.length;
List<bool> selected = new List<bool>();
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
#override
initState() {
for (var i = 0; i < itemCount; i++) {
selected.add(false);
}
super.initState();
}
Icon notFavorite = Icon(Icons.favorite_border, size: 25,);
Icon inFavorite = Icon(Icons.favorite, size: 25,);
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: AppBar(
title: Text('Accueil', style: kAppBarStyle,),
//backgroundColor: Colors.white,
elevation: 0,
),
body: ListView.builder(
itemCount: itemCount,
itemBuilder: (BuildContext context, int index) {
return Container(
child: new Row(
children: <Widget>[
//Image
new Container(
margin: new EdgeInsets.all(5.0),
child: new CachedNetworkImage(
imageUrl: item[index].imageURL,
height: MediaQuery.of(context).size.width / 4,
width: MediaQuery.of(context).size.width / 2,
fit: BoxFit.cover,
),
),
//Text
Expanded(
child: new Row(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Spacer(),
//Titre
Container(
padding: const EdgeInsets.only(bottom: 75.0, top: 10.0 ),
child: Text(
item[index].title,
style: kItemTitle,
),
),
//Decription
Container(
padding: const EdgeInsets.only(left: 10.0, top: 10.0),
child:Text(
item[index].description,
style: kItemDescription,
),
),
//Favoris
Spacer(),
GestureDetector(
child: Container(
padding: const EdgeInsets.only(right: 10.0, top: 3.0),
child: selected.elementAt(index) ? inFavorite : notFavorite,
),
onTap: () {
setState(() {
selected[index] = !selected.elementAt(index);
});
},
),
],
),
),
],
),
);
}
)
);
}
}
It is a ListView with Images, Texts and the Favorite Button and it works fine.
First you need a boolean variable.
bool toggle = false;
After that you can use IconButton like this:
IconButton(
icon: toggle
? Icon(Icons.favorite_border)
: Icon(
Icons.favorite,
),
onPressed: () {
setState(() {
// Here we changing the icon.
toggle = !toggle;
});
}),
custom radio button (some IconButton in ListView that change their icons):
main.dart file :
import 'package:flutter/material.dart';
import 'my_home_page.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
my_home_page.dart file:
import 'package:flutter/material.dart';
int itemCount = 5;
List<bool> selected = new List<bool>();
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
#override
initState() {
for (var i = 0; i < itemCount; i++) {
selected.add(false);
}
super.initState();
}
Icon firstIcon = Icon(
Icons.radio_button_on, // Icons.favorite
color: Colors.blueAccent, // Colors.red
size: 35,
);
Icon secondIcon = Icon(
Icons.radio_button_unchecked, // Icons.favorite_border
color: Colors.grey,
size: 35,
);
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: ListView.builder(
itemCount: itemCount,
itemBuilder: (BuildContext context, int index) {
return IconButton(
icon: selected.elementAt(index) ? firstIcon : secondIcon,
onPressed: () {
try {
// your code that you want this IconButton do
setState(() {
selected[index] = !selected.elementAt(index);
});
print('tap on ${index + 1}th IconButton ( change to : ');
print(selected[index] ? 'active' : 'deactive' + ' )');
} catch (e) {
print(e);
}
},
);
}),
),
);
}
}
Copy paste the code and it will work :)
import 'package:flutter/material.dart';
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData.dark(),
home: HomeApp(),
);
}
}
class HomeApp extends StatefulWidget {
#override
_HomeAppState createState() => _HomeAppState();
}
class _HomeAppState extends State<HomeApp> {
// Using a Bool
bool addFavorite = false;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Flutter App :)"),
),
body: Center(
child: IconButton(
icon: Icon(addFavorite ? Icons.favorite : Icons.favorite_border),
onPressed: () {
// Setting the state
setState(() {
addFavorite = !addFavorite;
});
}),
),
);
}
}
Updating the Code for ListView
class _HomeAppState extends State<HomeApp> {
// Using a Bool List for list view builder
List<bool> addFavorite = List<bool>();
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Flutter App :)"),
),
body: ListView.builder(
itemCount: 10,
itemBuilder: (context, index) {
// Setting a bool initially
addFavorite.add(false);
return IconButton(
icon: Icon(addFavorite.elementAt(index)
? Icons.favorite
: Icons.favorite_border),
onPressed: () {
// Setting the state
setState(() {
// Changing icon of specific index
addFavorite[index] =
addFavorite[index] == false ? true : false;
});
});
}),
);
}
}
the IconButton must be in StatefulWidget and use a flag for unselected icon and selected icon:
.
.
.
bool selected = false;
Icon first_icon = Icon(...);
Icon second_icon = Icon(...);
.
.
.
IconButton(
icon: selected
? first_icon
: second_icon,
onPressed: () {
try {
// your code that you want this IconButton do
setState(() {
selected = !selected;
});
} catch(e) {
print(e);
}
}),
for use in ListView:
.
.
.
List<bool> selected = new List<bool>();
Icon first_icon = Icon(...);
Icon second_icon = Icon(...);
.
.
.
ListView.builder(
controller: scrollController,
primary: true,
...
itemCount: _yourListViewLength,
itemBuilder: (BuildContext context, int i) {
selected.add(false);
IconButton(
icon: selected.elementAt(i)
? first_icon
: second_icon,
onPressed: () {
try {
// your code that you want this IconButton do
setState(() {
selected.elementAt(i) = !selected.elementAt(i);
});
} catch(e) {
print(e);
}
}),
},
)
i hope this help you
My code if you want : home_screen.dart
import 'package:flutter/material.dart';
import 'package:cached_network_image/cached_network_image.dart';
import '../recyclerview/data.dart';
import 'package:watch/constants.dart';
class ListViewExample extends StatefulWidget {
#override
State<StatefulWidget> createState() {
return new ListViewExampleState();
}
}
class ListViewExampleState extends State<ListViewExample>{
bool addFavorite = false;
Icon notFavorite = Icon(Icons.favorite_border, size: 25,);
Icon inFavorite = Icon(Icons.favorite, size: 25,);
List<Container> _buildListItemsFromItems(){
return item.map((item){
var container = Container(
child: new Row(
children: <Widget>[
//Image
new Container(
margin: new EdgeInsets.all(5.0),
child: new CachedNetworkImage(
imageUrl: item.imageURL,
height: MediaQuery.of(context).size.width / 4,
width: MediaQuery.of(context).size.width / 2,
fit: BoxFit.cover,
),
),
//Text
Expanded(
child: new Row(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Spacer(),
//Titre
Container(
padding: const EdgeInsets.only(bottom: 75.0, top: 5.0 ),
child: Text(
item.title,
style: kItemTitle,
),
),
//Decription
Container(
padding: const EdgeInsets.only(left: 10.0, top: 5.0),
child:Text(
item.description,
style: kItemDescription,
),
),
//Favoris
Spacer(),
GestureDetector(
child: Container(
padding: const EdgeInsets.only(right: 10.0, top: 1.0),
child: addFavorite ? inFavorite : notFavorite,
),
onTap: () {
setState(() {
addFavorite = !addFavorite;
});
},
),
],
),
),
],
),
);
return container;
}).toList();
}
//Scaffold Global
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: AppBar(
title: Text('Accueil', style: kAppBarStyle,),
//backgroundColor: Colors.white,
elevation: 0,
),
body: ListView(
children: _buildListItemsFromItems(),
),
);
}
}
It is not an IconButton but just an Icon but it is working.

How to change state of programmatically created animatedPositioned widget?

AnimatedPositioned widget animates when a parameter is changed (left for example). This works well unless I create it programatically. How do I change the parameters after creating it?
If you press a button it adds an AnimatedPositioned to the screen. The 'change' button just changed the variable myLeft which should change the position but it doesn't.
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Home(),
),
);
}
}
class Home extends StatefulWidget {
#override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
double myLeft = 20;
List<Widget> listOfBoxes = [];
_createRect(){
setState(() {
final AnimatedPositioned positioned = AnimatedPositioned(
left: myLeft,
top: 25,
height: 50,
width: 100,
duration: const Duration(milliseconds: 600),
child: Container(color: Colors.black,),
);
listOfBoxes.add(positioned
,);
});
}
_change(){
setState(() {
myLeft =200;
print("listOfBoxes==$listOfBoxes");
});
}
void initState() {
super.initState();
SystemChrome.setEnabledSystemUIOverlays([]);
}
#override
Widget build(BuildContext context) {
var size = MediaQuery.of(context).size;
return Column(
children: [Row(
children: [
RaisedButton(
child: Text('create rect'),
onPressed: _createRect,
),
RaisedButton(
child: Text('change'),
onPressed: _change,
),
],
),
Container(
color: Colors.blue,
height: size.height * .7,
width: double.infinity,
child: Stack(
children: listOfBoxes,
),
),
]
);
}
}
Here's the code doing what I asked based on pskink's comments.
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'dart:async';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Home(),
),
);
}
}
class Home extends StatefulWidget {
#override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
var lefts = [10.0, 20.0];
_change() {
setState(() {
lefts[0] = 200;
});
}
#override
Widget build(BuildContext context) {
var size = MediaQuery.of(context).size;
return Column(children: [
Row(
children: [
RaisedButton(
child: Text('change'),
onPressed: _change,
),
],
),
Container(
color: Colors.blue,
height: size.height * .7,
width: double.infinity,
child: Column(
children: [
Expanded(
child: Stack(children: [
for (var i = 0; i < lefts.length; i++)
AnimatedPositioned(
duration: Duration(milliseconds: 200),
left: lefts[i],
top: i * 100.0,
width: 100,
height: 75,
child: Container(color: Colors.red),
)
]),
),
Row(
children: [
RaisedButton(
child: Text('<<'),
onPressed: () => setState(
() => lefts = lefts.map((e) => e - 50).toList())),
RaisedButton(
child: Text('>>'),
onPressed: () => setState(
() => lefts = lefts.map((e) => e + 50).toList())),
],
),
],
),
),
]);
}
}

how Can i make this Single selection Flutter?

I have an Apps which is having a listview with the reaction button in a flutter . I want to make this when a user clicked any of this love icon then it's filled with red color.
enter image description here
enter image description here
Like this image but the problem is when I clicked one of this love icon all of the icons turned into red color but I only want to change the color of love of icon which one is Selected.
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
bool like;
#override
List<String> user = ['Dipto', 'Dipankar', "Sajib", 'Shanto', 'Pranto'];
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('ListView Demu'),
),
body: Center(
child: Container(
child: ListView.builder(
itemCount: user.length,
itemBuilder: (context, index) {
return Container(
padding: EdgeInsets.all(10),
height: 50,
width: MediaQuery.of(context).size.width * 0.8,
color: Colors.yellowAccent,
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
user[index],
),
Positioned(
child: IconButton(
icon: _iconControl(like),
onPressed: () {
if (like == false) {
setState(() {
like = true;
_iconControl(like);
});
} else {
setState(() {
like = false;
_iconControl(like);
});
}
},
),
),
],
),
);
},
),
)),
);
}
_iconControl(bool like) {
if (like == false) {
return Icon(Icons.favorite_border);
} else {
return Icon(
Icons.favorite,
color: Colors.red,
);
}
}
}
I also try with using parameter but Its failed Like that :
child: IconButton(
icon: _iconControl(true),
onPressed: () {
if (false) {
setState(() {
_iconControl(true);
});
} else {
setState(() {
_iconControl(false);
});
}
},
),
Can you help me Please. Thanks in advance
You can create a modal class to manage the selection of your list
Just create a modal class and add a boolean variable to maintaining selection using. that boolean variable
SAMPLE CODE
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
bool like;
List<Modal> userList = List<Modal>();
#override
void initState() {
userList.add(Modal(name: 'Dipto', isSelected: false));
userList.add(Modal(name: 'Dipankar', isSelected: false));
userList.add(Modal(name: 'Sajib', isSelected: false));
userList.add(Modal(name: 'Shanto', isSelected: false));
userList.add(Modal(name: 'Pranto', isSelected: false));
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('ListView Demu'),
),
body: Center(
child: Container(
child: ListView.builder(
itemCount: userList.length,
itemBuilder: (context, index) {
return Container(
padding: EdgeInsets.all(10),
height: 50,
width: MediaQuery
.of(context)
.size
.width * 0.8,
color: Colors.yellowAccent,
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
userList[index].name,
),
Positioned(
child: IconButton(
icon: _iconControl( userList[index].isSelected),
onPressed: () {
setState(() {
userList.forEach((element) {
element.isSelected = false;
});
userList[index].isSelected = true;
});
},
),
),
],
),
);
},
),
)),
);
}
_iconControl(bool like) {
if (like == false) {
return Icon(Icons.favorite_border);
} else {
return Icon(
Icons.favorite,
color: Colors.red,
);
}
}
}
class Modal {
String name;
bool isSelected;
Modal({this.name, this.isSelected = false});
}

animate show or hide widgets with flutter

i have something like this :
import 'package:flutter/material.dart';
class MyWidget extends StatefulWidget {
#override
State<StatefulWidget> createState() {
return _MyWidgetState();
}
}
class _MyWidgetState extends State<MyWidget> {
bool loading = true;
#override
Widget build(BuildContext context) {
if(loading) {
return Container(
color: Theme.of(context).scaffoldBackgroundColor,
child: Center(
child: SizedBox(
width: 24,
height: 24,
child: GestureDetector(
onTap: _toggle,
child: CircularProgressIndicator(),
),
),
),
);
} else {
return Container(
child: Center(
child: GestureDetector(
onTap: _toggle,
child: Text("WELCOME"),
),
),
);
}
}
_toggle() {
setState(() {
loading = !loading;
});
}
}
my big problem with flutter is animating between toggling widgets
i want when _toggle called, loading widget fadeOut and after animation completed remove from screen and then show normal widget with fadeIn effect
how can i achieved to this ?
thanks
Correct way is using AnimatedSwitcher widget:
class MyWidget extends StatefulWidget {
#override
State<StatefulWidget> createState() {
return _MyWidgetState();
}
}
class _MyWidgetState extends State<MyWidget> {
bool loading = true;
#override
Widget build(BuildContext context) {
return Scaffold(
body: AnimatedSwitcher(
duration: const Duration(milliseconds: 300),
child: loading ? Container(
key: Key("loading"),
color: Theme.of(context).scaffoldBackgroundColor,
child: Center(
child: SizedBox(
width: 24,
height: 24,
child: GestureDetector(
onTap: _toggle,
child: const CircularProgressIndicator(),
),
),
),
) : Container(
key: Key("normal"),
child: Center(
child: GestureDetector(
onTap: _toggle,
child: const Text("WELCOME"),
),
),
),
),
);
}
_toggle() {
setState(() {
loading = !loading;
});
}
}
note: you must give a key for children, in my example if you remove key animation not work
import 'package:flutter/material.dart';
class MyWidget extends StatefulWidget {
#override
State<StatefulWidget> createState() {
return _MyWidgetState();
}
}
class _MyWidgetState extends State<MyWidget> {
bool loading = true;
#override
Widget build(BuildContext context) {
return Container(
child: Stack(
children: <Widget>[
Center(
child: GestureDetector(
onTap: _toggle,
child: Text("WELCOME"),
),
),
IgnorePointer(
ignoring: !loading,
child: AnimatedOpacity(
opacity: loading ? 1 : 0,
duration: Duration(milliseconds: 500),
child: Container(
color: Theme.of(context).scaffoldBackgroundColor,
child: Center(
child: SizedBox(
width: 24,
height: 24,
child: GestureDetector(
onTap: _toggle,
child: CircularProgressIndicator(),
),
),
),
),
),
)
],
),
);
}
_toggle() {
setState(() {
loading = !loading;
});
}
}