I am using youtube_player_iframe to play you tube video. It is working but if click the full screen button on player, It is only show small as shown in picture. It is not always happen but It is happen once in two to three time.
import 'package:auto_size_text/auto_size_text.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:thitsarparami/blocs/bloc.dart';
import 'package:thitsarparami/helper/constants.dart';
import 'package:thitsarparami/helper/enum.dart';
import 'package:thitsarparami/ui/error/something_went_wrong.dart';
import 'package:thitsarparami/widgets/circular_progress_indicator_widget.dart';
import 'package:youtube_player_iframe/youtube_player_iframe.dart';
class VideoScreen extends StatefulWidget {
static const routeName = '/video';
const VideoScreen({Key? key}) : super(key: key);
#override
_VideoScreenState createState() => _VideoScreenState();
}
class _VideoScreenState extends State<VideoScreen> {
#override
void initState() {
super.initState();
_loadYoutube();
}
_loadYoutube() async {
List<String> codes = [
systemDataCodeToString(SystemDataCode.youtube_live),
];
BlocProvider.of<SystemDataBloc>(context).add(GetYoutubeLiveEvent(codes));
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
centerTitle: true,
backgroundColor: Theme.of(context).scaffoldBackgroundColor,
elevation: 0,
title: AutoSizeText(
kYouTubeChannel,
style: Theme.of(context).appBarTheme.titleTextStyle,
),
leading: IconButton(
onPressed: () {
Navigator.pop(context);
},
icon: Icon(
Icons.arrow_back,
color: Theme.of(context).primaryIconTheme.color!,
),
),
),
body: BlocBuilder<SystemDataBloc, SystemDataState>(
builder: (context, state) {
if (state is SystemDataError) {
return const SomethingWentWrongScreen();
} else if (state is YoutubeLiveDataLoaded) {
return Column(
mainAxisSize: MainAxisSize.max,
children: [
MyYoutubePlayer(
videoId: state.systemData.youtubeLive!.videoId!,
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
state.systemData.youtubeLive!.videoTitle!,
style: const TextStyle(
color: Colors.black,
fontSize: 16.0,
fontWeight: FontWeight.bold),
),
)
],
);
}
return const CircularProgressIndicatorWidget();
},
),
);
}
}
class MyYoutubePlayer extends StatefulWidget {
final String videoId;
const MyYoutubePlayer({Key? key, required this.videoId}) : super(key: key);
#override
State<MyYoutubePlayer> createState() => _MyYoutubePlayerState();
}
class _MyYoutubePlayerState extends State<MyYoutubePlayer> {
late YoutubePlayerController _controller;
#override
void initState() {
super.initState();
_controller = YoutubePlayerController(
initialVideoId: widget.videoId,
params: const YoutubePlayerParams(
showControls: true,
showFullscreenButton: true,
desktopMode: false,
privacyEnhanced: true,
useHybridComposition: true,
),
);
_controller.onEnterFullscreen = () {
SystemChrome.setPreferredOrientations([
DeviceOrientation.landscapeRight,
DeviceOrientation.landscapeLeft,
]);
};
_controller.onExitFullscreen = () {
SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
DeviceOrientation.portraitDown,
]);
};
}
#override
void dispose() {
_controller.close();
super.dispose();
}
#override
Widget build(BuildContext context) {
return YoutubePlayerIFrame(
controller: _controller,
aspectRatio: 16 / 9,
);
}
}
change this
Widget build(BuildContext context) {
return YoutubePlayerIFrame(
controller: _controller,
aspectRatio: 16 / 9,
);
}
to this
Widget build(BuildContext context) {
return YoutubePlayerScaffold(
autoFullScreen: true,
builder: ((context, player) {
return Container(
width: 100.w,
height: 100.h,
color: Colors.black,
child: Center(
child: player,
),
);
}),
controller: _controller
);
}
Fullscreen only works with YoutubePlayerScaffold Widget
Related
I am making a chat app using flutter. It is loading data from firestore but when I am using annimation in the drawer the chat's aren't loading I don't know the reason if i comment out the animation in the chat screen it works and it works also if comment out if block which contain connection state.waiting without commenting annimation
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:my_flutter_app/chat/messages.dart';
import 'package:my_flutter_app/chat/new_message.dart';
class ChatScreen extends StatefulWidget {
const ChatScreen({Key? key}) : super(key: key);
#override
State<ChatScreen> createState() => _ChatScreenState();
}
class _ChatScreenState extends State<ChatScreen> with SingleTickerProviderStateMixin{
late AnimationController controller;
late Animation animation;
#override
void initState() {
super.initState();
controller=AnimationController(
duration: Duration(seconds: 2),
vsync: this);
animation=CurvedAnimation(parent: controller, curve: Curves.decelerate);
controller.forward();
animation.addStatusListener((status) {
if(status==AnimationStatus.completed){
controller.reverse(from: 1.0);
}else if(status==AnimationStatus.dismissed){
controller.forward();
}
});
controller.addListener(() {
setState(() {
animation.value;
});
});
}
#override
void dispose() {
super.dispose();
controller.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
drawer: Drawer(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Container(
margin: EdgeInsets.only(top: 50),
padding: EdgeInsets.all(15),
child: CircleAvatar(backgroundImage: AssetImage('assets/profile.png'),radius: 60),),
Container(
child: Image.asset('assets/welcome.png'),
height: animation.value*100,
),
InkWell(
onTap: (){
showCupertinoDialog(context: context, builder: (context)=>CupertinoAlertDialog(
title: Text('Alert'),
content: Text('Are you sure you want to logout?'),
actions: [
CupertinoDialogAction(child: Text('Yes'),onPressed: (){
FirebaseAuth.instance.signOut();
Navigator.pop(context);
},),
CupertinoDialogAction(child: Text('No'),onPressed: (){
Navigator.pop(context);
},)
],
));
//FirebaseAuth.instance.signOut();
},
child: ListTile(leading: Icon(Icons.logout,color: Colors.white),
title: Text('LOGOUT',style: TextStyle(color: Colors.white,fontWeight: FontWeight.bold),),
tileColor: Colors.red,),
)
],
),
),
appBar: AppBar(title: Text('Chats'),centerTitle: true,backgroundColor: Colors.green),
body: Container(
child: Column(
children: [
Expanded(child: Messages()),
NewMessage(),
],
),
),
);
}
}
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:my_flutter_app/chat/mesui.dart';
class Messages extends StatefulWidget {
const Messages({Key? key}) : super(key: key);
#override
State<Messages> createState() => _MessagesState();
}
class _MessagesState extends State<Messages> {
final auth=FirebaseAuth.instance;
User ?cuser;
#override
void initState() {
// TODO: implement initState
super.initState();
getCurrentUser();
}
void getCurrentUser(){
try {
final user = auth.currentUser;
if (user != null) {
cuser = user;
}
}
catch(e){
print(e);
}
}
#override
Widget build(BuildContext context) {
return StreamBuilder(stream: FirebaseFirestore.instance.collection('chat').orderBy('messaged_on',descending: true).snapshots(),
builder: (context,snaps) {
if(snaps.connectionState == ConnectionState.waiting){
return Center(
child: CircularProgressIndicator(),
);
}
final documents=snaps.data!.docs;
final nowperson=cuser!.email;
return ListView.builder(
reverse: true,
itemBuilder: (ctx,index){
final sender=documents[index]['email'];
bool isMe= sender==nowperson;
return Mesui(documents[index]['text'],isMe);
},
itemCount: documents.length,);
},
);
}
}
This is my main
import 'package:flutter/material.dart';
import 'package:gestionchamp/screen_intro/view/onboarding_screen.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'auth/main_page.dart';
import 'pages/login_page.dart';
import 'package:firebase_core/firebase_core.dart';
bool show = true;
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
final prefs = await SharedPreferences.getInstance();
show = prefs.getBool('ON_BOARDING') ?? true;
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({
Key? key,
}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData(
textTheme: const TextTheme(
headline1: TextStyle(
fontSize: 25,
color: Colors.green,
fontWeight: FontWeight.bold,
),
headline2: TextStyle(
fontSize: 18,
color: Colors.green,
fontWeight: FontWeight.w400,
wordSpacing: 1.2,
height: 1.2),
headline3: TextStyle(
fontSize: 18,
color: Colors.green,
fontWeight: FontWeight.bold,
),
headline4: TextStyle(
fontSize: 18,
color: Colors.white,
fontWeight: FontWeight.bold,
),
)),
home: show ? OnBoardingScreen() : const MainPage(),
);
}
}
The mainPage
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import '../pages/home_page.dart';
import '../pages/login_page.dart';
import 'auth_page.dart';
class MainPage extends StatelessWidget {
const MainPage({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
body: StreamBuilder<User?>(
stream: FirebaseAuth.instance.authStateChanges(),
builder: (context, snapshot) {
if (snapshot.hasData) {
return HomePage();
} else {
return AuthPage();
}
},
),
);
}
}
and this is the Home page
import 'dart:io';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:provider/provider.dart';
import 'package:gestionchamp/mqtt/MQTTAppState.dart';
import 'package:gestionchamp/mqtt/MQTTManager.dart';
class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
#override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
final TextEditingController _hostTextController = TextEditingController();
final TextEditingController _messageTextController = TextEditingController();
final TextEditingController _topicTextController = TextEditingController();
late MQTTAppState currentAppState;
late MQTTManager manager;
#override
void initState() {
super.initState();
/*
_hostTextController.addListener(_printLatestValue);
_messageTextController.addListener(_printLatestValue);
_topicTextController.addListener(_printLatestValue);
*/
}
#override
void dispose() {
_hostTextController.dispose();
_messageTextController.dispose();
_topicTextController.dispose();
super.dispose();
}
final user = FirebaseAuth.instance.currentUser!;
// document IDs
List<String> docIDs = [];
//get docIDs
Future getDocId() async {
await FirebaseFirestore.instance.collection('users').get().then(
(snapshot) => snapshot.docs.forEach(
(document) {
print(document.reference);
docIDs.add(document.reference.id);
},
),
);
}
#override
Widget build(BuildContext context) {
final MQTTAppState appState = Provider.of<MQTTAppState>(context);
// Keep a reference to the app state.
currentAppState = appState;
final Scaffold scaffold = Scaffold(body: _buildColumn());
return scaffold;
}
Widget _buildAppBar(BuildContext context) {
return AppBar(
title: const Text('MQTT'),
backgroundColor: Colors.greenAccent,
);
}
Widget _buildColumn() {
return Column(
children: <Widget>[
_buildConnectionStateText(
_prepareStateMessageFrom(currentAppState.getAppConnectionState)),
_buildEditableColumn(),
_buildScrollableTextWith(currentAppState.getHistoryText)
],
);
}
Widget _buildEditableColumn() {
return Padding(
padding: const EdgeInsets.all(20.0),
child: Column(
children: <Widget>[
_buildTextFieldWith(
_hostTextController,
'Entrez l\'adresse du broker',
currentAppState.getAppConnectionState),
const SizedBox(height: 10),
_buildTextFieldWith(
_topicTextController,
'Entrez un topic pour souscrire ou mettre en écoute',
currentAppState.getAppConnectionState),
const SizedBox(height: 10),
_buildPublishMessageRow(),
const SizedBox(height: 10),
_buildConnecteButtonFrom(currentAppState.getAppConnectionState)
],
),
);
}
Widget _buildPublishMessageRow() {
return Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Expanded(
child: _buildTextFieldWith(_messageTextController,
'Entrez un message', currentAppState.getAppConnectionState),
),
_buildSendButtonFrom(currentAppState.getAppConnectionState)
],
);
}
Widget _buildConnectionStateText(String status) {
return Row(
children: <Widget>[
Expanded(
child: Container(
color: Colors.deepOrangeAccent,
child: Text(status, textAlign: TextAlign.center)),
),
],
);
}
Widget _buildTextFieldWith(TextEditingController controller, String hintText,
MQTTAppConnectionState state) {
bool shouldEnable = false;
if (controller == _messageTextController &&
state == MQTTAppConnectionState.connected) {
shouldEnable = true;
} else if ((controller == _hostTextController &&
state == MQTTAppConnectionState.disconnected) ||
(controller == _topicTextController &&
state == MQTTAppConnectionState.disconnected)) {
shouldEnable = true;
}
return TextField(
enabled: shouldEnable,
controller: controller,
decoration: InputDecoration(
contentPadding:
const EdgeInsets.only(left: 0, bottom: 0, top: 0, right: 0),
labelText: hintText,
));
}
Widget _buildScrollableTextWith(String text) {
return Padding(
padding: const EdgeInsets.all(20.0),
child: Container(
width: 400,
height: 200,
child: SingleChildScrollView(
child: Text(text),
),
),
);
}
Widget _buildConnecteButtonFrom(MQTTAppConnectionState state) {
return Row(
children: <Widget>[
Expanded(
// ignore: deprecated_member_use
child: ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: Colors.lightBlueAccent),
child: const Text('Connect'),
onPressed: state == MQTTAppConnectionState.disconnected
? _configureAndConnect
: null, //
),
),
const SizedBox(width: 10),
Expanded(
// ignore: deprecated_member_use
child: ElevatedButton(
style: ElevatedButton.styleFrom(backgroundColor: Colors.redAccent),
child: const Text('Disconnect'),
onPressed: state == MQTTAppConnectionState.connected
? _disconnect
: null, //
),
),
],
);
}
Widget _buildSendButtonFrom(MQTTAppConnectionState state) {
// ignore: deprecated_member_use
return ElevatedButton(
style: ElevatedButton.styleFrom(backgroundColor: Colors.green),
child: const Text('Send'),
onPressed: state == MQTTAppConnectionState.connected
? () {
_publishMessage(_messageTextController.text);
}
: null, //
);
}
// Fonctions utiles
String _prepareStateMessageFrom(MQTTAppConnectionState state) {
switch (state) {
case MQTTAppConnectionState.connected:
return 'Connected';
case MQTTAppConnectionState.connecting:
return 'Connecting';
case MQTTAppConnectionState.disconnected:
return 'Disconnected';
}
}
void _configureAndConnect() {
// ignore: flutter_style_todos
// TODO: Use UUID
String osPrefix = 'IoT';
if (Platform.isAndroid) {
osPrefix = 'Android ';
}
MQTTManager manager = MQTTManager(
host: _hostTextController.text,
topic: _topicTextController.text,
identifier: osPrefix,
state: currentAppState);
manager.initializeMQTTClient();
manager.connect();
}
void _disconnect() {
manager.disconnect();
}
void _publishMessage(String text) {
String osPrefix = 'IoT';
if (Platform.isAndroid) {
osPrefix = 'Android';
}
final String message = osPrefix + ' a dit: ' + text;
manager.publish(message);
_messageTextController.clear();
}
}
and this is the debug output
Error: Could not find the correct Provider<MQTTAppState> above this HomePage Widget
This happens because you used a `BuildContext` that does not include the provider
of your choice. There are a few common scenarios:
- You added a new provider in your `main.dart` and performed a hot-reload.
To fix, perform a hot-restart.
- The provider you are trying to read is in a different route.
Providers are "scoped". So if you insert of provider inside a route, then
other routes will not be able to access that provider.
- You used a `BuildContext` that is an ancestor of the provider you are trying to read.
Make sure that HomePage is under your MultiProvider/Provider<MQTTAppState>.
This usually happens when you are creating a provider and trying to read it immediately.
The provider you're trying to call isn't identified at the place you're referring it. For this you need to provide it in the root widget or above the widget tree where you want to call it.
You could wrap your MaterialApp by that provider like this:
Provider< MQTTAppState>(
create: (_) => MQTTAppState(),
child: MaterialApp(),
),
And please change the title of the post to the one that describes your problem.
You have to put the provider somewhere in the widget tree, higher up than where you want to use it. I'm using a MultiProvider with which you can put several providers, but just one is also fine!
Something like this:
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:my_app/screens/welcome_screen.dart';
import 'provider_updates.dart'; // The location of the MyFirstProvider class
void main() async {
WidgetsFlutterBinding.ensureInitialized();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
print('Building $runtimeType');
MyFirstProvider myFirstProvider = MyFirstProvider(); // Create your provider here!
return MultiProvider(
providers: [
ChangeNotifierProvider<MyFirstProvider>(
create: (context) => myFirstProvider), // Use it here. Now, it will exist in the entire app!
// You can put more providers here
],
builder: (context, child) {
return MaterialApp(
home: WelcomeScreen(myThemeClass),
);
});
}
}
I am having a problem where when I try to use a switch widget it will not work properly inside of an alert box as in it does not switch over to the second state it just bounces whenever I try to flick it. I am wondering if this is because there is a problem with the switch itself or how I displayed it in the box? Thanks!
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(),
home: SwitchDemo(),
);
}
}
class SwitchDemo extends StatefulWidget {
const SwitchDemo({Key key}) : super(key: key);
#override
State<StatefulWidget> createState() => new _TabsPageState();
}
class _TabsPageState extends State<SwitchDemo> {
bool isInstructionView;
#override
void initState() {
super.initState();
isInstructionView = Global.shared.isInstructionView;
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("add data"),
),
body: Container(
child: TextButton(
child: Text('Open Alert Box'),
onPressed: () => {
showDialog(
context: context,
builder: (BuildContext context) {
return Padding(
padding: EdgeInsets.symmetric(
horizontal: MediaQuery.of(context).size.width / 20,
vertical:
MediaQuery.of(context).size.height / 20,
),
child: AlertDialog(
content: Container(
child: Switch(
value: isInstructionView,
onChanged: (bool isOn) {
if (isInstructionView == false) {
} else if (isInstructionView == true) {}
setState(() {
isInstructionView = isOn;
Global.shared.isInstructionView = isOn;
isOn = !isOn;
});
},
activeColor: Colors.blue,
inactiveTrackColor: Colors.grey,
inactiveThumbColor: Colors.grey,
),
),
),
);
})
}),
));
}
}
class Global {
static final shared = Global();
bool isInstructionView = false;
}
Wrap you AlertDialog with StatefulBuilder.
here is full code:
import 'package:flutter/material.dart';
class SwitchDemo extends StatefulWidget {
const SwitchDemo({Key? key}) : super(key: key);
#override
State<StatefulWidget> createState() => new _TabsPageState();
}
class _TabsPageState extends State<SwitchDemo> {
late bool isInstructionView;
#override
void initState() {
super.initState();
isInstructionView = Global.shared.isInstructionView;
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("add data"),
),
body: Container(
child: TextButton(
child: Text('Open Alert Box'),
onPressed: () => {
showDialog(
context: context,
builder: (BuildContext context) {
return Padding(
padding: EdgeInsets.symmetric(
horizontal: MediaQuery.of(context).size.width / 20,
vertical: MediaQuery.of(context).size.height / 20,
),
child: StatefulBuilder(builder: (context, setState) {
return AlertDialog(
content: Container(
child: Switch(
value: isInstructionView,
onChanged: (bool isOn) {
print(isInstructionView);
setState(() {
isInstructionView = !isInstructionView;
});
},
activeColor: Colors.blue,
inactiveTrackColor: Colors.grey,
inactiveThumbColor: Colors.grey,
),
),
);
}),
);
},
)
}),
));
}
}
class Global {
static final shared = Global();
bool isInstructionView = false;
}
Does it answer your question?
ref: https://stackoverflow.com/a/57240941/10157127
So I was trying to make a feature where when we click an icon button it will change the video path. It will change the video path using string. I was using a print("$videoname"), to make sure the string changes, and it does. But it still doesn't work, with the videoplayercontroller.assets():
Here's the code that I was trying to make
String videoname="Video/Intro.mp4";
Container(
child:Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
ChewieListItem(
videoPlayerController: VideoPlayerController.asset(videoname),
looping: false,
),
Container(
margin: EdgeInsets.symmetric(vertical: 20.0),
height: 100.0,
child: ListView(
scrollDirection: Axis.horizontal,
children: [
IconButton(
icon:Icon(Icons.people),
onPressed: (){
videoname="Video/Intro.mp4";
print("$videoname");
},
),
IconButton(
icon:Icon(Icons.personal_video),
onPressed: (){
videoname="Video/Intro1.mp4";
print("$videoname");
},
),
],
),
),
)
You can copy paste run full code below
Step 1: Use key: UniqueKey() in ChewieListItem
Step 2: Use setState in onPressed
code snippet
ChewieListItem(
key: UniqueKey(),
videoPlayerController: VideoPlayerController.asset(videoname),
looping: false,
),
IconButton(
icon: Icon(Icons.people),
onPressed: () {
setState(() {
videoname = "Video/Intro.mp4";
print("$videoname");
});
},
),
IconButton(
icon: Icon(Icons.personal_video),
onPressed: () {
setState(() {
videoname = "Video/Intro1.mp4";
print("$videoname");
});
},
),
working demo
full code
import 'package:flutter/material.dart';
import 'package:video_player/video_player.dart';
import 'package:chewie/chewie.dart';
class ChewieListItem extends StatefulWidget {
// This will contain the URL/asset path which we want to play
final VideoPlayerController videoPlayerController;
final bool looping;
ChewieListItem({
#required this.videoPlayerController,
this.looping,
Key key,
}) : super(key: key);
#override
_ChewieListItemState createState() => _ChewieListItemState();
}
class _ChewieListItemState extends State<ChewieListItem> {
ChewieController _chewieController;
#override
void initState() {
super.initState();
print("ChewieListItem initState");
// Wrapper on top of the videoPlayerController
_chewieController = ChewieController(
videoPlayerController: widget.videoPlayerController,
aspectRatio: 16 / 9,
// Prepare the video to be played and display the first frame
autoInitialize: true,
looping: widget.looping,
// Errors can occur for example when trying to play a video
// from a non-existent URL
errorBuilder: (context, errorMessage) {
return Center(
child: Text(
errorMessage,
style: TextStyle(color: Colors.white),
),
);
},
);
}
#override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: Chewie(
controller: _chewieController,
),
);
}
#override
void dispose() {
print("ChewieListItem dispose");
super.dispose();
// IMPORTANT to dispose of all the used resources
widget.videoPlayerController.dispose();
_chewieController.dispose();
}
}
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'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
String videoname = "Video/Intro.mp4";
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Container(
child:
Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
ChewieListItem(
key: UniqueKey(),
videoPlayerController: VideoPlayerController.asset(videoname),
looping: false,
),
Container(
margin: EdgeInsets.symmetric(vertical: 20.0),
height: 100.0,
child: ListView(
scrollDirection: Axis.horizontal,
children: [
IconButton(
icon: Icon(Icons.people),
onPressed: () {
setState(() {
videoname = "Video/Intro.mp4";
print("$videoname");
});
},
),
IconButton(
icon: Icon(Icons.personal_video),
onPressed: () {
setState(() {
videoname = "Video/Intro1.mp4";
print("$videoname");
});
},
),
],
),
),
])),
);
}
}
setState should work for you
onPressed: () {
setState(() {
videoname="Video/Intro1.mp4";
print("$videoname");
});
},
When calling MediaQuery.of(context).padding.top in the parent widget (ProductsOverviewScreen) the value returned is as expected - 24. But when calling the same property from a nested widget (ProductsGrid) of the parent that we are talking about the value is always 0. Is this normal behavior?
products_overview_screen.dart
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../widgets/app_drawer.dart';
import '../screens/cart_screen.dart';
import '../widgets/products_grid.dart';
import '../widgets/badge.dart';
import '../providers/cart.dart';
import '../providers/products_provider.dart';
enum FilterOptions {
showAll,
onlyFavorites,
}
class ProductsOverviewScreen extends StatefulWidget {
#override
_ProductsOverviewScreenState createState() => _ProductsOverviewScreenState();
}
class _ProductsOverviewScreenState extends State<ProductsOverviewScreen> {
bool _showFavorites = false;
bool _isLoading = false;
bool _isInit = false;
#override
void initState() {
// Future.delayed(Duration(seconds: 1), () {
// Provider.of<Products>(context).fetchAndSetProducts();
// });
super.initState();
}
#override
void didChangeDependencies() {
if (!_isInit) {
setState(() {
_isLoading = true;
});
Provider.of<Products>(context).fetchAndSetProducts().then((_) {
setState(() {
_isLoading = false;
});
});
}
_isInit = true;
super.didChangeDependencies();
}
Future<void> refreshProducts(BuildContext context) async {
await Provider.of<Products>(context, listen: false).fetchAndSetProducts();
}
#override
Widget build(BuildContext context) {
final scaffoldKey = GlobalKey();
final appBar = AppBar(
title: Text('My Shop'),
actions: <Widget>[
Consumer<Cart>(
builder: (ctx, cart, child) => Badge(
child: child,
value: cart.length.toString(),
),
child: IconButton(
onPressed: () {
final scaffoldState = scaffoldKey.currentState as ScaffoldState;
scaffoldState.hideCurrentSnackBar();
Navigator.of(context).pushNamed(CartScreen.routeName);
},
icon: Icon(
Icons.shopping_cart,
color: Theme.of(context).accentColor,
),
),
),
PopupMenuButton(
onSelected: (FilterOptions selectedValue) {
setState(() {
if (selectedValue == FilterOptions.onlyFavorites) {
_showFavorites = true;
} else {
_showFavorites = false;
}
});
},
icon: Icon(Icons.more_vert),
itemBuilder: (_) => [
PopupMenuItem(
child: Text('Only Favorites'),
value: FilterOptions.onlyFavorites),
PopupMenuItem(
child: Text('Show All'),
value: FilterOptions.showAll,
),
],
),
],
);
return Scaffold(
key: scaffoldKey,
appBar: appBar,
drawer: AppDrawer(),
body: _isLoading
? Center(child: CircularProgressIndicator())
: RefreshIndicator(
onRefresh: () => refreshProducts(context),
child: ProductsGrid(_showFavorites, appBar.preferredSize.height),
),
);
}
}
//56
products_grid.dart
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../providers/products_provider.dart';
import '../widgets/product_item.dart';
class ProductsGrid extends StatelessWidget {
final bool _showFavorites;
final double _appBarHeight;
ProductsGrid(this._showFavorites, this._appBarHeight);
#override
Widget build(BuildContext context) {
final productsData = Provider.of<Products>(context);
final products =
_showFavorites ? productsData.favoriteItems : productsData.items;
final mediaQuery = MediaQuery.of(context);
return productsData.items.isEmpty
? SingleChildScrollView(
physics: AlwaysScrollableScrollPhysics(),
child: Container(
width: mediaQuery.size.width,
height: mediaQuery.size.height -
mediaQuery.padding.top -
_appBarHeight,
// child: Center(
// child: Text(
// 'There are no products.',
// style: TextStyle(
// color: Colors.grey,
// fontSize: 16,
// ),
// ),
// ),
),
)
: GridView.builder(
padding: const EdgeInsets.all(15),
itemCount: products.length,
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
childAspectRatio: 3 / 2,
crossAxisSpacing: 10,
mainAxisSpacing: 10,
),
itemBuilder: (ctx, index) => ChangeNotifierProvider.value(
value: products[index],
child: ProductItem(),
),
);
}
}
You can copy paste run full code below
You can use MediaQueryData.fromWindow(window).padding.top
code snippet
import 'dart:ui';
...
final statusbarHeight2 = MediaQueryData.fromWindow(window).padding.top;
working demo
full code
import 'package:flutter/material.dart';
import 'dart:ui';
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: ProductsOverviewScreen(title: 'Flutter Demo Home Page'),
);
}
}
class ProductsOverviewScreen extends StatefulWidget {
ProductsOverviewScreen({Key key, this.title}) : super(key: key);
final String title;
#override
_ProductsOverviewScreenState createState() => _ProductsOverviewScreenState();
}
class _ProductsOverviewScreenState extends State<ProductsOverviewScreen> {
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
#override
Widget build(BuildContext context) {
final statusbarHeight1 = MediaQueryData.fromWindow(window).padding.top;
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
ProductsGrid(),
Text(
'$statusbarHeight1',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}
class ProductsGrid extends StatelessWidget {
const ProductsGrid({
Key key,
}) : super(key: key);
#override
Widget build(BuildContext context) {
final statusbarHeight2 = MediaQueryData.fromWindow(window).padding.top;
return Text(
'$statusbarHeight2',
);
}
}
You can get all information about window using window object that provided by dart:ui. Here an example of finding exact size of status bar;
Firstly add this top of the dart file:
import 'dart:ui';
And use window object to find height of the status bar:
final statusBarHeight = window.padding.top / window.devicePixelRatio;