Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I’m trying to develop an app using flutter , I want to have all apps usage on the mobile , I have been searching for some packages for this purpose I didn’t find something for this specific purpose.
You can copy paste run full code below
You can use package https://pub.dev/packages/usage_stats
In working demo you can see package and event timestamp history, then you can do summary
Step 1: AndroidManifest.xml, add xmlns:tools and android.permission.PACKAGE_USAGE_STATS
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="your package name" xmlns:tools="http://schemas.android.com/tools">
<uses-permission
android:name="android.permission.PACKAGE_USAGE_STATS"
tools:ignore="ProtectedPermissions" />
Step 2: Permit usage access, see working demo picture at left
working demo
full code
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:usage_stats/usage_stats.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
List<EventUsageInfo> events = [];
#override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_) {
initUsage();
});
}
Future<void> initUsage() async {
UsageStats.grantUsagePermission();
DateTime endDate = new DateTime.now();
DateTime startDate = DateTime(2020, 1, 1, 0, 0, 0);
List<EventUsageInfo> queryEvents =
await UsageStats.queryEvents(startDate, endDate);
this.setState(() {
events = queryEvents.reversed.toList();
});
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text("Usage Stats"),
),
body: Container(
child: ListView.separated(
itemBuilder: (context, index) {
return ListTile(
title: Text(events[index].packageName),
subtitle: Text(
"Last time used: ${DateTime.fromMillisecondsSinceEpoch(int.parse(events[index].timeStamp)).toIso8601String()}"),
trailing: Text(events[index].eventType),
);
},
separatorBuilder: (context, index) => Divider(),
itemCount: events.length)),
floatingActionButton: FloatingActionButton(
onPressed: () {
initUsage();
},
child: Icon(
Icons.refresh,
),
mini: true,
),
),
);
}
}
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 10 months ago.
Improve this question
there!
Can anyone achieve something like this in flutter?
screen recorded video (file size too big to attach it here!)
You can change the AppBar's color by using ScrollController#addListener.
It's a simple implementation with RiverPod.
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
class CustomScrollViewSample extends ConsumerWidget {
const CustomScrollViewSample({Key? key}) : super(key: key);
#override
Widget build(BuildContext context, WidgetRef ref) {
return CustomScrollView(
controller: ref.read(controller),
slivers: [
SliverAppBar(
backgroundColor: ref.watch(backgroundColor),
foregroundColor: ref.watch(foregroundColor),
pinned: true,
elevation: 0,
title: const Text('We did it!'),
),
SliverList(
delegate: SliverChildListDelegate(
const [
SizedBox(height: 400),
SizedBox(
height: 400,
child: Card(margin: EdgeInsets.all(16), color: Colors.blue),
),
SizedBox(height: 400),
],
),
),
],
);
}
}
final controller = Provider((ref) {
final scrollController = ScrollController();
void listener() {
ref.read(backgroundOpacity.notifier).state = min(
1,
scrollController.position.pixels / 200,
);
}
scrollController.addListener(listener);
ref.onDispose(() {
scrollController.removeListener(listener);
});
return scrollController;
});
final backgroundColor = Provider(
(ref) => Colors.black.withOpacity(
ref.watch(backgroundOpacity),
),
);
final foregroundColor = Provider(
(ref) => Color.fromRGBO(
(ref.watch(backgroundOpacity) * 255).toInt(),
(ref.watch(backgroundOpacity) * 255).toInt(),
(ref.watch(backgroundOpacity) * 255).toInt(),
1,
),
);
final backgroundOpacity = StateProvider((_) => 0.0);
I also wrote the sample that works on DartPad.
If you like please try this.
https://dartpad.dev/?id=336910211bb02227e4c0b11e939aa116
I am new in flutter development. I cannot find my mistake. I can't see my images on my app. when I use them without slider it works what is wrong in my code can someone help me?
import 'package:feedme_start/widgets/Navigation_Drawer_Widget.dart';
import 'package:flutter/material.dart';
// ignore: import_of_legacy_library_into_null_safe
import 'package:flutter_swiper/flutter_swiper.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
#override
_MyAppState createState() => _MyAppState();
}
final imageList = [
"https://cdn.yeniakit.com.tr/images/news/625/pratik-degisik-yemek-tarifleri-en-sevilen-tarifler-h1581081558-3ff37b.jpg"
"https://cdn.yemek.com/mncrop/940/625/uploads/2021/04/patlicanli-pilav-yemekcom.jpg"
];
class _MyAppState extends State<MyApp> {
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
appBar: AppBar(
elevation: 0,
backgroundColor: Colors.red,
title: Center(child: Text("FEED ME")),
actions: <Widget>[
IconButton(onPressed: () {}, icon: Icon(Icons.call))
],
),
drawer: NavigationDrawerWidget(),
backgroundColor: Colors.white,
body:
Container(
constraints: BoxConstraints.expand(height: 200),
child: imageSlider(context),
),
/*Swiper(itemCount: imageList.length,
itemBuilder: (context, index) {
return Image.network(imageList[index],/*errorBuilder:
(BuildContext context, Object exception, StackTrace? stackTrace), {return const("resim yüklenemedi")},*/
fit: BoxFit.cover,);
},)*/
),
);
}
}
Swiper imageSlider(context){
return new Swiper(
autoplay: true,
itemBuilder: (BuildContext context, int index) {
return new Image.network("https://cdn.yeniakit.com.tr/images/news/625/pratik-degisik-yemek-tarifleri-en-sevilen-tarifler-h1581081558-3ff37b.jpg",fit: BoxFit.fitHeight,);
},
itemCount: 10,
viewportFraction: 0.8,
scale: 0.9,
);
}
also here is the screenshots;
when I run the program it tries to upload the image. then it sends me the this screen and shows the 'rethrow' line error:
after I continue debugging my screen looks like in the second picture:
You're simply forgetting to add , in your list.
A newline string after a string is considered as a string. For example, the following variable:
var text = "one two three"
"four five six";
is the same as:
var text = "one two three" + "four five six";
So, instead of:
final imageList = [
"https://cdn.yeniakit.com.tr/images/news/625/pratik-degisik-yemek-tarifleri-en-sevilen-tarifler-h1581081558-3ff37b.jpg"
"https://cdn.yemek.com/mncrop/940/625/uploads/2021/04/patlicanli-pilav-yemekcom.jpg"
];
change to:
final imageList = [
"https://cdn.yeniakit.com.tr/images/news/625/pratik-degisik-yemek-tarifleri-en-sevilen-tarifler-h1581081558-3ff37b.jpg" ,
"https://cdn.yemek.com/mncrop/940/625/uploads/2021/04/patlicanli-pilav-yemekcom.jpg"
];
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:
may I ask a way how to make this work.
I have a text file named questions.txt.
This file contains the following questions:
How old are you?
Where do you live?
What is your age?
I want to load these questions from the file, and render them as a list in Flutter.
questionnaires.dart
import 'package:flutter/material.dart';
class Questionnaires extends StatefulWidget {
#override
_QuestionnairesState createState() => _QuestionnairesState();
}
class _QuestionnairesState extends State<Questionnaires> {
String q1 = "";
String q2 = "";
String q3 = "";
#override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
resizeToAvoidBottomInset: false,
body: Center(
child: Column(
children: <Widget>[
Text(q1),
Text(q2),
Text(q3)
],
),
),
),
);
}
}
You can start with the most basic way of retrieving the questions from a .txt file using rootBundle.loadString, then display it using a ListView widget.
main.dart
import 'dart:async';
import 'dart:convert';
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(
title: 'Flutter Questions',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyAppScreen(),
);
}
}
class MyAppScreen extends StatefulWidget {
#override
State<StatefulWidget> createState() {
return MyAppScreenState();
}
}
class MyAppScreenState extends State<MyAppScreen> {
List<String> _questions = [];
Future<List<String>> _loadQuestions() async {
List<String> questions = [];
await rootBundle.loadString('path/to/questions.txt').then((q) {
for (String i in LineSplitter().convert(q)) {
questions.add(i);
}
});
return questions;
}
#override
void initState() {
_setup();
super.initState();
}
_setup() async {
// Retrieve the questions (Processed in the background)
List<String> questions = await _loadQuestions();
// Notify the UI and display the questions
setState(() {
_questions = questions;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("Flutter Questions")),
body: Center(
child: Container(
child: ListView.builder(
itemCount: _questions.length,
itemBuilder: (context, index) {
return Text(_questions[index]);
},
),
),
),
);
}
}
And here are the sample list of questions.
questions.txt
"How old are you?"
"Where do you live?"
"What is your age?"
In the example code above, you are parsing the text file line by line, please see LineSplitter. This is good for small and sample projects while you're testing out Flutter. But you should be able to update this implementation by following the official docs of Flutter, on how you can read from and write on files.
Furthermore, if you want to go big with your Flutter project, you should look into ways on how you can host your questions online, eg. served via REST APIs, then retrieve it using the http plugin for Flutter.
More on:
https://flutter.dev/docs/cookbook/networking/fetch-data
https://flutter.dev/docs/cookbook/persistence/reading-writing-files
https://pub.dev/packages/path_provider
Output:
I am new to Flutter, am currently stuck with my JSON file content not populating on my emulator. It shows no error, yet not displaying. If I include the content directly in my codeblock, it works fine. I can't spot the issue.
Below are my codes:
main.dart code
import 'package:emailapp/messagelist.dart';
import 'package:flutter/material.dart';
void main() => runApp(EmailApp());
class EmailApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.green
),
home: MessageList(title: 'Muss Mailer APP'),
);
}
}
messagelist.dart
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
class MessageList extends StatefulWidget{
final String title;
const MessageList({Key key, this.title}) : super(key: key);
#override
State<StatefulWidget> createState()=>_MessageListState();
}
class _MessageListState extends State<MessageList>{
var messages=const [];
Future loadMessageList() async{
var content=await rootBundle.loadString('data/message.json');
print(content);
var collection=json.decode(content);
setState(() {
messages=collection;
});
}
void initstate() {
loadMessageList();
super.initState();
}
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: ListView.separated(
separatorBuilder: (context,index)=>Divider(),
itemCount: messages.length,
itemBuilder: (BuildContext context, int index){
var message=messages[index];
return ListTile(
isThreeLine: true,
leading: CircleAvatar( child: Text('AJ'),),
title: Text(message['subject']),
subtitle: Text(message['body'],maxLines: 2, overflow: TextOverflow.ellipsis,),
) ;
},
),
);
}
}
message.json
[ {
"subject":"My First Message",
"body":"Hello Form the other side of life fellas.. and happy to meet you guys"
},
{
"subject":"My Second Message",
"body":"Hello Form the other side of life fellas.. and happy to meet you guys"
},
{
"subject":"My Third Message",
"body":"Hello Form the other side of life fellas.. and happy to meet you guys"
},
{
"subject":"My Fourth Message",
"body":"Hello Form the other side of life fellas.. and happy to meet you guys"
},
{
"subject":"My Fifth Message",
"body":"Hello Form the other side of life fellas.. and happy to meet you guys"
},
{
"subject":"My Sixth Message",
"body":"Hello Form the other side of life fellas.. and happy to meet you guys"
}]
pubspec.yaml
assets:
# - images/a_dot_burr.jpeg
# - images/a_dot_ham.jpeg
- data/message.json
It's just a spelling mistake. It's not initstate. Its initState (S is capital).
void initState() {
loadMessageList();
super.initState();
}
I would suggest making the following changes, to resolve some basic issues:
add Override notation to initState and use S in initState name:
as suggested by #Crazy Lazy Cat
#override
void initState() {
loadMessageList();
super.initState();
}
remove the use of setState inside the initState, it is not recommended to set state of a widget which has not been built yet:
Future loadMessageList() async{
// everything else, as it is
messages = collection;
}
remove const [] from the messages, since it is replaced in the initState anyways.
since the loadMessageList is async method you should use FutureBuilder for this purpose:
FutureBuilder(
future: loadMessageList,
builder: (context, snapshot) => snapshot.hasData ? your_widget() : Container(),
),
your_widget() widget refers to the ListView.separated widget in the build method.
create var messages = snapshot.data; before defining the ListView.separated code.
for this to work you need to change the code in loadMessageList:
Future loadMessageList() async {
// everything else, as it is
//messages = collection;
return collection;
}
No need of global messages variable now.