Flutter - Switching between two images using GestureDetector - flutter

I found this code and modify it to switch between two pictures.
it seems to me that is ok but ..... iT doesn't work.
Can you help me to understand why?
Thanks.
See below the full code.
import 'dart:ui';
import 'package:flutter/material.dart';
void main() {
runApp(new MaterialApp(
home: new MyApp(),
));
}
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
Image img; // variable named image to be named with the path
Image imgUp = Image.asset("assets/images/pressed.jpg"); //pressed button path
Image imgDown = Image.asset("assets/images/pressed.jpg"); //unpressed button path
#override
void initState() {super.initState();
img = imgUp; //inizialize the image as imgUp version
}
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Tap The Image!"),
centerTitle: true,
), //AppBar section ended
body: Center(child: GestureDetector(
child: img,
onTapDown: (tap) {
setState(() {
img = imgDown;
});
},
onTapUp: (tap) {
setState(() {
img = imgUp;
});
},
),
));
}
}

It probably doesn't work because you are using the same image for up and down. Please see here
Image imgUp = Image.asset("assets/images/pressed.jpg"); //pressed button path
Image imgDown = Image.asset("assets/images/pressed.jpg"); //
It works if you change the images, please see code below : [Note that the image changes back to imgUp as soon as you release the tap down.]
import 'dart:ui';
import 'package:flutter/material.dart';
void main() {
runApp(new MaterialApp(
home: new MyApp(),
));
}
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
Image img; // variable named image to be named with the path
Image imgUp = Image.network("https://cdn3.iconfinder.com/data/icons/faticons/32/arrow-up-01-512.png"); //pressed button path
Image imgDown = Image.network("https://cdn3.iconfinder.com/data/icons/faticons/32/arrow-down-01-512.png"); //unpressed button path
#override
void initState() {super.initState();
img = imgUp; //inizialize the image as imgUp version
}
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Tap The Image!"),
centerTitle: true,
), //AppBar section ended
body: Center(child: GestureDetector(
child: img,
onTapDown: (tap) {
setState(() {
img = imgDown;
});
},
onTapUp: (tap) {
setState(() {
img = imgUp;
});
},
),
));
}
}

Related

How to remove package names from list that showing usage stats of all installed applications?

I simply made a flutter application that shows usage statistics of all installed application e.g if we spend two hours on WhatsApp my app show it,but the problem is : It also shows package names like
system ui, builder, launcher, com.package etc.
I am using this flutter package app_usage
Here is main.dart file
import 'package:flutter/material.dart';
import 'package:app_usage/app_usage.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
List<AppUsageInfo> _infos = [];
#override
void initState() {
super.initState();
}
void getUsageStats() async {
try {
DateTime endDate = new DateTime.now();
DateTime startDate = endDate.subtract(Duration(hours: 1));
List<AppUsageInfo> infoList =
await AppUsage.getAppUsage(startDate, endDate);
setState(() {
_infos = infoList;
});
for (var info in infoList) {
print(info.toString());
}
} on AppUsageException catch (exception) {
print(exception);
}
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('App Usage Example'),
backgroundColor: Colors.green,
),
body: ListView.builder(
itemCount: _infos.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(_infos[index].appName),
trailing: Text(_infos[index].usage.toString()));
}),
floatingActionButton: FloatingActionButton(
onPressed: getUsageStats, child: Icon(Icons.file_download)),
),
);
}
}
Here is my emulator output:

Flutter: refresh network image

I'm a beginner in flutter and I'm looking for a simple way to refresh a network image.
In a basic code like this, what would be the simplest method of getting flutter to fetch and draw this image again? In my code the image is a snapshot from a security camera, so it changes every time it is fetched, but always has the same url. I get a new picture every time I start the app, but I would like the image refreshed when I press the image itself.
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
var title = 'Web Images';
return MaterialApp(
title: title,
home: Scaffold(
appBar: AppBar(
title: Text(title),
),
body: Image.network('https://picsum.photos/250?image=9'),
),
);
}
}
Extend Your Class With Stateful Widget then:
body: Inkwell(
onTap: ()=> setState(){};
Image.network('https://picsum.photos/250?image=9'),
),
this will refresh the page. Or If you dont want to tap then :
#override
void initState() {
super.initState();
setState(){
print('refreshing');
}
}
If you need forced picture refresh - try such code:
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
var title = 'Web Images';
return MaterialApp(
title: title,
home: Scaffold(
appBar: AppBar(
title: Text(title),
),
body: ForcePicRefresh(),
));
}
}
class ForcePicRefresh extends StatefulWidget {
#override
_ForcePicRefreshState createState() => _ForcePicRefreshState();
}
class _ForcePicRefreshState extends State<ForcePicRefresh> {
String url =
'https://www.booths.co.uk/wp-content/uploads/British-Flower-1x1-2-660x371.jpg';
Widget _pic;
#override
void initState() {
_pic = Image.network(url);
super.initState();
}
_updateImgWidget() async {
setState(() {
_pic = CircularProgressIndicator();
});
Uint8List bytes = (await NetworkAssetBundle(Uri.parse(url)).load(url))
.buffer
.asUint8List();
setState(() {
_pic = Image.memory(bytes);
});
}
#override
Widget build(BuildContext context) {
return InkWell(
child: _pic,
onTap: () {
_updateImgWidget();
},
);
}
}
Another tricky solution is to add a dummy argument which changes every time, then the image will be treat as different image source and will refresh image every time when you access it. For example add t=currentTimestamp, but you don't need handle this argument in the web server.
ex: Image.network('https://picsum.photos/250?image=9?t=${DateTime.now().millisecond}'

Count page transitions in Flutter using iframes [flutter web]

I would like to include another website in my own website.
For that I would like to register a callback to track site-tranitions (i.e. the user clicks on a link on the embedded site and is redirected to a different url / sub-url (?).) I currently use IFrameElement to embed a site, this would in theory allow to register event listeners, but I cannot find any documentation about that.
My main goal is to count the number of page transitions. This is my current code:
import 'package:flutter/material.dart';
import 'package:wikipoker/widgets/my_iframe.dart';
import 'package:wikipoker/widgets/player_tab.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Wikipedia Poker',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Game of Wikipedia Poker'),
);
}
}
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
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: LayoutBuilder(
builder: (BuildContext context, BoxConstraints constraints) {
return Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
buildIFrame(constraints.maxHeight, constraints.maxWidth),
],
);
},
),
);
}
String _youtube = 'https://www.youtube.com/embed/RQzhAQlg2JQ';
String _wiki = 'https://de.wikipedia.org/wiki/Hunde';
Widget buildIFrame(double height, double width) {
return Column(
children: [
IFrameWidget(
_wiki,
height,
width * (4 / 5),
),
],
);
}
}
import 'dart:html';
import 'dart:ui' as ui;
import 'package:flutter/cupertino.dart';
class IFrameWidget extends StatefulWidget {
final String _url;
double _height = 500;
double _width = 500;
IFrameWidget(this._url, this._height, this._width);
#override
State<StatefulWidget> createState() => _IFrameWidgetState();
}
class _IFrameWidgetState extends State<IFrameWidget> {
Widget _iframeWidget;
#override
void initState() {
super.initState();
final IFrameElement _iframeElement = IFrameElement();
// _iframeElement.height = '500';
// _iframeElement.width = '500';
// FIXME This does not load.
// _iframeElement.addEventListener('onLoad', (event) {
// setState(() {
// _iframeWidget = Text("Lol");
// });
// });
_iframeElement.src = widget._url;
_iframeElement.style.border = 'none';
// ignore: undefined_prefixed_name
ui.platformViewRegistry.registerViewFactory(
'iframeElement',
(int viewId) => _iframeElement,
);
_iframeWidget = HtmlElementView(
key: UniqueKey(),
viewType: 'iframeElement',
);
}
#override
Widget build(BuildContext context) {
return SizedBox(
height: widget._height,
width: widget._width,
child: _iframeWidget,
);
}
}
The IFrameElement has some fields and methods, which look like they could be useful.
addEventListener expects a type of event, but there is no overview about what that might be.
The documentation is very incomplete for this and I have no idea which event I would like to register.
My hope is, that I can use events from the native html iframe for that.
Documentation for IFrames: https://api.flutter.dev/flutter/dart-html/IFrameElement-class.html
Old question, but I hope the answer will help someone looking for a solution:
here is described very well
Note: need to restart the IDE (at least mine refused to work without restart)

Flutter : Assets Audio Player

I have problem with assest audio player package when I try to play two songs inside one page
both are playing !
The way I want when I press first button,first song play and when I press second button the first song stop and the second song start playing .
I used this code but it doesn't work
HomePage
import 'package:flutter/material.dart';
import 'package:mp3player/playpausebutton.dart';
class HomePage extends StatefulWidget {
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Mp3 Player'),
),
body: Container(
color: Colors.white,
child: Column(
children: [
PlayPauseButton(
mp3name: 'song1',
),
PlayPauseButton(
mp3name: 'song2',
)
],
),
),
);
}
}
PlayPauseButton
class PlayPauseButton extends StatefulWidget {
PlayPauseButton({this.mp3name});
final String mp3name;
#override
_PlayPauseButtonState createState() => _PlayPauseButtonState();
}
class _PlayPauseButtonState extends State<PlayPauseButton> {
final assetsAudioPlayer = AssetsAudioPlayer();
bool ispresed = false;
#override
void dispose() {
// TODO: implement dispose
super.dispose();
assetsAudioPlayer.dispose();
}
#override
Widget build(BuildContext context) {
return FlatButton(
child: Icon(ispresed ? Icons.pause : Icons.play_arrow),
onPressed: () {
assetsAudioPlayer.open(Audio("assets/audios/${widget.mp3name}.mp3"));
setState(() {
if (ispresed == false) {
assetsAudioPlayer.play();
ispresed = true;
} else if (ispresed == false) {
assetsAudioPlayer.pause();
ispresed = false;
}
});
},
);
}
}
I used this package for playing audio
https://pub.dev/packages/assets_audio_player
and also is there any way to toggle button Icon when player is finish ?
My problem is solved by changing
final assetsAudioPlayer = AssetsAudioPlayer();
to
final assetsAudioPlayer = AssetsAudioPlayer.withId("0");
you can check if the player is done playing by adding listener to it.
assetsAudioPlayer.playlistAudioFinished.listen((event){if(event) {//carry out another action you want } });
the callback response is a bool type, return false when the audio start and return true when it finished

Flutter One time Intro Screen?

I have an intro screen for my app, but it shows every time I open the app,
I need to show that for the 1st time only.
How to do that?
//THIS IS THE SCREEN COMES 1ST WHEN OPENING THE APP (SPLASHSCREEN)
class SplashScreen extends StatefulWidget {
#override
_SplashScreenState createState() => _SplashScreenState();
}
class _SplashScreenState extends State<SplashScreen> {
#override
void initState() {
super.initState();
//After 2seconds of time the Introscreen will e opened by bellow code
Timer(Duration(seconds: 2), () => MyNavigator.goToIntroscreen(context));
}
//The below code has the text to show for the spalshing screen
#override
Widget build(BuildContext context) {
return Scaffold(
body: new Center(
child: Text('SPLASH SCREEN'),
),
);
}
}
Every time this screen opens the intro screen with 2 seconds delay.
but I want for the first time only How to do that with sharedpreference??
Please add the required code.
If you wish to show the intro screen only for the first time, you will need to save locally that this user has already seen intro.
For such thing you may use Shared Preference. There is a flutter package for Shared Preference which you can use
EDITED:
Please refer to the below complete tested code to understand how to use it:
import 'dart:async';
import 'package:after_layout/after_layout.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new MaterialApp(
color: Colors.blue,
home: new Splash(),
);
}
}
class Splash extends StatefulWidget {
#override
SplashState createState() => new SplashState();
}
class SplashState extends State<Splash> with AfterLayoutMixin<Splash> {
Future checkFirstSeen() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
bool _seen = (prefs.getBool('seen') ?? false);
if (_seen) {
Navigator.of(context).pushReplacement(
new MaterialPageRoute(builder: (context) => new Home()));
} else {
await prefs.setBool('seen', true);
Navigator.of(context).pushReplacement(
new MaterialPageRoute(builder: (context) => new IntroScreen()));
}
}
#override
void afterFirstLayout(BuildContext context) => checkFirstSeen();
#override
Widget build(BuildContext context) {
return new Scaffold(
body: new Center(
child: new Text('Loading...'),
),
);
}
}
class Home extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text('Hello'),
),
body: new Center(
child: new Text('This is the second page'),
),
);
}
}
class IntroScreen extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text('IntroScreen'),
),
body: new Center(
child: new Text('This is the IntroScreen'),
),
);
}
}
Thanks to Ben B for noticing the incorrect use of delay in initState. I had used a delay because sometimes the context is not ready immediately inside initState.
So now I have replaced that with afterFirstLayout which is ready with the context. You will need to install the package after_layout.
I was able to do without using after_layout package and Mixins and instead I have used FutureBuilder.
class SplashState extends State<Splash> {
Future checkFirstSeen() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
bool _seen = (prefs.getBool('seen') ?? false);
if (_seen) {
return HomeScreen.id;
} else {
// Set the flag to true at the end of onboarding screen if everything is successfull and so I am commenting it out
// await prefs.setBool('seen', true);
return IntroScreen.id;
}
}
#override
Widget build(BuildContext context) {
return FutureBuilder(
future: checkFirstSeen(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(
child: CircularProgressIndicator(),
);
} else {
return MaterialApp(
initialRoute: snapshot.data,
routes: {
IntroScreen.id: (context) => IntroScreen(),
HomeScreen.id: (context) => HomeScreen(),
},
);
}
});
}
}
class HomeScreen extends StatelessWidget {
static String id = 'HomeScreen';
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text('Hello'),
),
body: new Center(
child: new Text('This is the second page'),
),
);
}
}
class IntroScreen extends StatelessWidget {
static String id = 'IntroScreen';
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text('IntroScreen'),
),
body: new Center(
child: new Text('This is the IntroScreen'),
),
);
}
}
I always try to use minimum count of packages, because in future it can conflict with ios or android. So my simple solution without any package:
class SplashScreen extends StatefulWidget {
#override
_SplashScreenState createState() => _SplashScreenState();
}
class _SplashScreenState extends State<SplashScreen> {
final splashDelay = 2;
#override
void initState() {
super.initState();
_loadWidget();
}
_loadWidget() async {
var _duration = Duration(seconds: splashDelay);
return Timer(_duration, checkFirstSeen);
}
Future checkFirstSeen() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
bool _introSeen = (prefs.getBool('intro_seen') ?? false);
Navigator.pop(context);
if (_introSeen) {
Navigator.pushNamed(context, Routing.HomeViewRoute);
} else {
await prefs.setBool('intro_seen', true);
Navigator.pushNamed(context, Routing.IntroViewRoute);
}
}
#override
Widget build(BuildContext context) {
//your splash screen code
}
}
Use shared_preferences:
Full code:
void main() async {
WidgetsFlutterBinding.ensureInitialized();
var prefs = await SharedPreferences.getInstance();
var boolKey = 'isFirstTime';
var isFirstTime = prefs.getBool(boolKey) ?? true;
runApp(MaterialApp(home: isFirstTime ? IntroScreen(prefs, boolKey) : RegularScreen()));
}
class IntroScreen extends StatelessWidget {
final SharedPreferences prefs;
final String boolKey;
IntroScreen(this.prefs, this.boolKey);
Widget build(BuildContext context) {
prefs.setBool(boolKey, false); // You might want to save this on a callback.
return Scaffold();
}
}
class RegularScreen extends StatelessWidget {
Widget build(BuildContext context) => Scaffold();
}
I just had to do exactly the same thing, here's how I did it:
First, in my main method, I open the normal main page and the tutorial:
MaterialApp(
title: 'myApp',
onGenerateInitialRoutes: (_) => [MaterialPageRoute(builder: mainPageRoute), MaterialPageRoute(builder: tutorialSliderRoute)],
)
...and then I use a FutureBuilder to build the tutorial only if necessary:
var tutorialSliderRoute = (context) => FutureBuilder(
future: Provider.of<UserConfiguration>(context, listen: false).loadShowTutorial() // does a lookup using Shared Preferences
.timeout(Duration(seconds: 3), onTimeout: () => false),
initialData: null,
builder: (context, snapshot){
if (snapshot.data == null){
return CircularProgressIndicator(); // This is displayed for up to 3 seconds, in case data loading doesn't return for some reason...
} else if (snapshot.data == true){
return TutorialSlider(); // The Tutorial, implemented using IntroSlider()
} else {
// In case the tutorial shouldn't be shown, just return an empty Container and immediately pop it again so that the app's main page becomes visible.
SchedulerBinding.instance.addPostFrameCallback((_){Navigator.of(context).pop();});
return Container(width: 0, height: 0);
}
},
);
Also, I think the tutorial should be shown again in case the user does not finish it, so I set only set the variable showTutorial to false once the user has completed (or skipped) the tutorial:
class TutorialSlider extends StatefulWidget {
#override
State<StatefulWidget> createState() => TutorialSliderState();
}
class TutorialSliderState extends State<TutorialSlider> {
...
#override
Widget build(BuildContext context) => IntroSlider(
...
onDonePress: (){
Provider.of<UserConfiguration>(context, listen: false).setShowTutorial(false);
Navigator.of(context).pop();
}
);
}
I took a different approach. I agree with the other answers that you should save your isFirstRun status via SharedPreferences. The tricky part then is how to show the correct widget in such a way that when you hit back you close out of the app correctly, etc. I first tried doing this by launching a my SplashWidget while building my HomePageWidget, but this turned out to lead to some weird Navigator errors.
Instead, I wound up calling runApp() multiple times with my different widget as appropriate. When I need to close the SplashWidget, rather than pop it, I just call runApp() again, this time with my HomePageWidget as the child property. It is safe to call runApp() multiple times according to this issue, indeed even for splash screens.
So it looks something like this (simplified obviously):
Future<void> main() async {
bool needsFirstRun = await retrieveNeedsFirstRunFromPrefs();
if (needsFirstRun) {
// This is will probably be an async method but no need to
// delay the first widget.
saveFirstRunSeen();
runApp(child: SplashScreenWidget(isFirstRun: true));
} else {
runApp(child: HomePageWidget());
}
}
I have an isFirstRun property on SplashScreenWidget because I can launch it in two ways--once as a true splash screen, and once from settings so that users can see it again if they want. I then inspect that in SplashScreenWidget to determine how I should return to the app.
class SplashScreenWidget extends StatefulWidget {
final bool isFirstRun;
// <snip> the constructor and getState()
}
class _SplashScreenWidgetState extends State<SplashScreenWidget> {
// This is invoked either by a 'skip' button or by completing the
// splash screen experience. If they just hit back, they'll be
// kicked out of the app (which seems like the correct behavior
// to me), but if you wanted to prevent that you could build a
// WillPopScope widget that instead launches the home screen if
// you want to make sure they always see it.
void dismissSplashScreen(BuildContext ctx) {
if (widget.isFirstRun) {
// Then we can't just Navigator.pop, because that will leave
// the user with nothing to go back to. Instead, we will
// call runApp() again, setting the base app widget to be
// our home screen.
runApp(child: HomePageWidget());
} else {
// It was launched via a MaterialRoute elsewhere in the
// app. We want the dismissal to just return them to where
// they were before.
Navigator.of(ctx).pop();
}
}
}