Get app icons of installed apps in Flutter from device_apps plugin - android

I was figuring out how to display list of installed apps along with their names & icons. Code works well till displaying app names. Here is the right, working code:
import 'package:flutter/material.dart';
import 'package:device_apps/device_apps.dart';
import 'dart:async';
class FirstScreen extends StatefulWidget{
State<StatefulWidget> createState(){
return _FirstScreen();
}
}
class _FirstScreen extends State<FirstScreen>{
List<Application> apps;
void initState(){
super.initState();
}
Future<void> getApp() async{
List<Application> _apps = await DeviceApps.getInstalledApplications(onlyAppsWithLaunchIntent: true, includeAppIcons: true, includeSystemApps: true);
setState(() {
apps = _apps;
});
}
Widget build(BuildContext context) {
getApp();
return Container(
child: ListView.builder(
itemCount: apps.length,
itemBuilder: (context, index){
return ListTile(
title: Text(apps[index].appName),
);
},
)
);
}
}
but when I display app icon in ListTile by:
trailing: Icon(Image.memory(apps[index].icon))
it gives icon not defined error.
I even tried ApplicationWithIcon class which extends Application class & icon defined in it, but it returned Null Error

instead of writing
List<Application> apps
write
List apps
also, instead of writing
List<Application> _apps = await DeviceApps.getInstalledApplications(onlyAppsWithLaunchIntent: true, includeAppIcons: true, includeSystemApps: true);
write:
List _apps = await DeviceApps.getInstalledApplications(onlyAppsWithLaunchIntent: true, includeAppIcons: true, includeSystemApps: true);
finally, instead of
Icon(Image.memory(apps[index].icon))
write
Image.memory(apps[index] is ApplicationWithIcon ? app.icon : null)

That's because Icon widget receive a Icons widget and you're passing a Images
ej: Icon(Icons.home)
so just pass the image
trailing: Image.memory(apps[index].icon)
Update
you must delete the type and initialize the list:
List apps = [];
In your method delete type too
Future<void> getApp() async{
List _apps = await DeviceApps.getInstalledApplications(onlyAppsWithLaunchIntent: true,
includeAppIcons: true, includeSystemApps: true);
setState(() {
apps = _apps;
});
}

Related

Hot reload doesn't work and need to Hot Restart Flutter

I'm making an app, which has a theme manager, light mode, dark mode, and system mode.
I think that the way I manage the state with redux, prevent me to reload the app with the hot reload, I explain:
If I have a scaffold with a background, from the themedata, if the thememode is currently dark, and the background color is Color(0xFF1F1F1F) (a shade of black), and I change it to Color(0xFFFFFFFF) (Pure white), then I use hot reload, it doesn't work, and I need to restart the whole app with hot restart to see changes.
The same with my theme manager, I use radiobuttons to manage it, if I change the theme to light or dark, it works fine.
if I change the mode to system, it works fine, but with the system theme mode in which the app were opened, if I change the system theme mode of my phone, it doesn't work. in this case StoreProvider.dispatch doesn't work, store.dispatch neither, I have to use the hot restart.
Here the code that can cause the problem.
main.dart:
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter/services.dart';
import 'package:async_redux/async_redux.dart';
import 'package:hive/hive.dart';
import 'package:app_name/Redux/States/AppState.dart';
import 'package:app_name/UI/Screens/AppHome.dart';
import 'package:app_name/Utilities/Themes.dart';
import 'package:app_name/Utilities/functions.dart';
import 'package:app_name/Utilities/extensions.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
Box box = await initHive();
SettingsState settingsState = SettingsState(
themeMode: box.get("theme").toString().themeModeFromString,
);
Store<AppState> store = Store(
initialState: AppState(settings: settingsState),
);
runApp(App(store: store));
}
class App extends StatelessWidget {
final Store<AppState> store;
App({
required this.store,
});
Widget build(BuildContext context) {
return StoreProvider<AppState>(
store: store,
child: StoreConnector<AppState, SettingsState>(
converter: (Store<AppState> store) => store.state.settings,
builder: (BuildContext context, SettingsState settings) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Carleo',
theme: lightTheme,
darkTheme: darkTheme,
themeMode: settings.themeMode,
home: Focus(
onFocusChange: (hasFocus) =>
SystemChrome.setEnabledSystemUIOverlays([]),
autofocus: true,
descendantsAreFocusable: true,
child: AppHome(),
),
);
},
),
);
}
}
Here the file AppHome.dart:
import 'package:app_name/UI/Widgets/Radio%20buttons.dart';
import 'package:flutter/material.dart';
import 'package:carleo/UI/Screens/SelectAccess.dart';
import 'package:carleo/UI/Screens/Home.dart';
import 'package:carleo/UI/Widgets/CircularIndicator.dart';
import 'package:carleo/Utilities/Database Utilities.dart';
import 'package:app_name/Utilities/Themes.dart';
class AppHome extends StatelessWidget {
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: ThemeGetter.primary(context),
body: ThemeRadioButton(),
);
}
}
Here Radio Buttons.dart:
import 'package:flutter/material.dart';
import 'package:async_redux/async_redux.dart';
import 'package:app_name/Redux/States/AppState.dart';
import 'package:app_name/Redux/Actions/Actions.dart';
class ThemeRadioButton extends StatelessWidget {
Widget build(BuildContext context) {
return StoreConnector<AppState, SettingsState>(
converter: (Store<AppState> store) => store.state.settings,
builder: (BuildContext context, SettingsState settings) {
return Wrap(
children: [
ListTile(
leading: Radio<ThemeMode>(
value: ThemeMode.light,
fillColor: MaterialStateProperty.all(Colors.black),
groupValue: settings.themeMode,
onChanged: (ThemeMode? mode) {
StoreProvider.dispatch<AppState>(
context,
ThemeChanger(
payload: mode ?? ThemeMode.light,
),
);
},
),
title: Text("Light"),
),
ListTile(
leading: Radio<ThemeMode>(
value: ThemeMode.dark,
fillColor: MaterialStateProperty.all(Colors.black),
groupValue: settings.themeMode,
onChanged: (ThemeMode? mode) {
StoreProvider.dispatch<AppState>(
context,
ThemeChanger(
payload: mode ?? ThemeMode.dark,
),
);
},
),
title: Text("Dark"),
),
ListTile(
leading: Radio<ThemeMode>(
value: ThemeMode.system,
fillColor: MaterialStateProperty.all(Colors.black),
groupValue: settings.themeMode,
onChanged: (ThemeMode? mode) {
StoreProvider.dispatch<AppState>(
context,
ThemeChanger(
payload: mode ?? ThemeMode.system,
),
);
},
),
title: Text("System"),
),
],
);
},
);
}
}
Here any other thing that can help:
ThemeData darkTheme = ThemeData(
backgroundColor: Color(0xFF1F1F1F),
accentColor: Color(0xFF101217),
primaryColor: Color(0xFFFFFFFF),
buttonColor: Color(0xFF0D47A1),
brightness: Brightness.dark,
);
ThemeData lightTheme = ThemeData(
backgroundColor: Color(0xFFFFFFFF),
accentColor: Color(0xFFFFFFFF),
brightness: Brightness.light,
);
class ThemeGetter {
static Color primary(BuildContext context) {
return Theme.of(context).backgroundColor;
}
static Color accent(BuildContext context) {
return Theme.of(context).accentColor;
}
static Color contrast(BuildContext context) {
return Theme.of(context).primaryColor;
}
static Color secondary(BuildContext context) {
return Theme.of(context).buttonColor;
}
}
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart' show ThemeMode;
extension StringEnumExtension on String {
ThemeMode get themeModeFromString => ThemeMode.values.firstWhere(
(e) => describeEnum(e) == this,
orElse: () => ThemeMode.system,
);
}
extension ThemeModeExtensions on ThemeMode {
String get name => describeEnum(this);
}
import 'package:flutter/material.dart' show ThemeMode;
class AppState {
final SettingsState settings;
AppState({SettingsState? settings})
: this.settings = settings ?? SettingsState();
AppState.copy({
required AppState state,
}) : this.settings = state.settings;
AppState copyWith({int? counter, SettingsState? settings}) => AppState(
settings: settings ?? this.settings,
);
#override
operator ==(Object another) =>
identical(this, another) ||
(another is AppState && this.settings == another.settings);
#override
int get hashCode => super.hashCode;
}
class SettingsState {
final ThemeMode themeMode;
SettingsState({
ThemeMode? themeMode,
}) : this.themeMode = themeMode ?? ThemeMode.system;
SettingsState.copy({
required SettingsState state,
}) : this.themeMode = state.themeMode;
SettingsState copyWith({ThemeMode? themeMode, ThemeMode? radioValue}) =>
SettingsState(
themeMode: themeMode ?? this.themeMode,
);
#override
operator ==(Object another) =>
identical(this, another) &&
(another is SettingsState && another.themeMode == this.themeMode);
#override
int get hashCode => super.hashCode;
}
import 'package:async_redux/async_redux.dart';
import 'package:flutter/material.dart' show ThemeMode;
import 'package:hive/hive.dart';
import 'package:carleo/Redux/States/AppState.dart';
import 'package:carleo/Utilities/extensions.dart';
class ThemeChanger extends ReduxAction<AppState> {
final ThemeMode payload;
ThemeChanger({
required this.payload,
});
#override
Future<AppState> reduce() async {
Box box = await Hive.openBox("Settings");
box.put("theme", payload.name);
return state.copyWith(
settings: state.settings.copyWith(
themeMode: payload,
),
);
}
}
Any help will be accepted. and thanks in advance.
EDIT:
I've noticed that, even if settings.themeMode is ThemeMode.system, and, in the store connector (the one which builds the MaterialApp), the themeData values are correct, if I use later the same color with Theme.of(context) (like I do in the background of the scaffold in AppHome), the color printed is not the correct one, is the color of the last hot restart.
I put this in the StoreConnector builder to notice that:
Brightness brightness =
SchedulerBinding.instance!.window.platformBrightness;
bool darkModeOn = brightness == Brightness.dark;
print(settings.themeMode);
switch (settings.themeMode) {
case ThemeMode.light:
print(lightTheme.primaryColor);
break;
case ThemeMode.dark:
print(darkTheme.primaryColor);
break;
case ThemeMode.system:
if (darkModeOn)
print(darkTheme.primaryColor);
else
print(lightTheme.primaryColor);
}
and simply this code to notice that the colors are different in different widgets:
print(Theme.of(context).backgroundColor);
Some code changes to the app’s main() or initState() methods might not be visible in the refreshed UI on hot-reload.
As a general rule, if the modified code is downstream of the root
widget’s build() method, then hot reload behaves as expected. However,
if the modified code won’t be re-executed as a result of rebuilding
the widget tree, then you won’t see its effects after hot reload.
This may be the reason for the change to theme data not reflected after hot-reload since it is defined in the app's main().
So from Flutter documentation
Hot reload loads code changes into the VM and re-builds the widget
tree, preserving the app state; it doesn’t rerun main() or
initState().
According to the flutter docs - hot reload is not enabled for flutter web as of 16/07/21
Flutter hot reload doc
Kia Kaha,
Mike Smith

How to store stream data and display new one along with old in a flutter list view?

I'm trying to display a comment stream from Reddit API. I"m using Streambuilder to stream contents as it arrives and displays it as list view thing is I can only view present stream content and this will disappear as new stream contents appear replacing the old ones. If I don't mention item count inside listview.builder prints contents infinitely still new stream appears.
is there a way to display contents along with previous contents in a scrollable fashion and automatically scroll down as a new stream message appears??
Assuming that the comment stream returns individual (and preferably unique) comments one at a time rather than as a list, what you need to do is store the incoming comments in a state object such as a list. When a new comment comes through the stream, you add it to the list and then trigger a widget rebuild.
What you are doing right now is replacing state with each new stream element rather than accumulating them. Using the code you provided, I have edited it to behave as an accumulator instead. Notice the List<Comment> comments = <Comment>[] object added to state. I have also removed the StreamBuilder since that isn't helpful for this use case.
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:draw/draw.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: RedditFlutter(),
debugShowCheckedModeBanner: false,
);
}
}
class RedditFlutter extends StatefulWidget {
RedditFlutter({Key key}) : super(key: key);
#override
_RedditFlutterState createState() => _RedditFlutterState();
}
class _RedditFlutterState extends State<RedditFlutter> {
var comments;
ScrollController _scrollController =
new ScrollController(initialScrollOffset: 50.0);
List<Comment> comments = <Comment>[];
StreamSubscription<Comment>? sub;
var msg = '';
Future<void> redditmain() async {
// Create the `Reddit` instance and authenticated
Reddit reddit = await Reddit.createScriptInstance(
clientId: 'clientid',
clientSecret: 'clientsecret',
userAgent: 'useragent',
username: 'username',
password: 'password', // Fake
);
// Listen to comment stream and accumulate new comments into comments list
sub = reddit.subreddit('cricket').stream.comments().listen((comment) {
if (comment != null) {
// Rebuild from state when a new comment is accumulated
setState(() {
comments.add(comment);
})
}
});
}
#override
void initState() {
// TODO: implement initState
redditmain();
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Reddit"),
centerTitle: true,
),
body: Center(
child: Container(
child: ListView.builder(
controller: _scrollController,
itemCount: comments.length,
itemBuilder: (context, index) {
final Comment comment = comments[index];
return Card(
child: ListTile(
leading: Image.asset('assets/criclogo.png'),
title: Text(comment.body),
trailing: Icon(Icons.more_vert),
),
);
},
),
);
),
);
}
#override
void dispose() {
sub?.cancel();
super.dispose();
}
}
Note that I have not tested this code so there may be (trivial) bugs. Still, conceptually, it should be fine.

Flutter: Adding App Update Dialog for iOS and Android

I am currently working on Notification Feature so when a new Update is availible the User gets a Dialog where he can choose to Update or not. I'm doing it with Firebase Remote Config where i have a Parameter called "force_update_current_version" where i then add the Value for the Version for checking. But I do get following errors.
Thanks for your help and i wish you a healty start into the new Year.
Main.dart Code
import 'checkUpdate.dart';
#override
void initState() {
try {
versionCheck(**context**);
} catch (e) {
print(e);
}
**super**.initState();
}
context error: Undefined name 'context'.
Try correcting the name to one that is defined, or defining the name.
super error: Invalid context for 'super' invocation.
checkUpdate.dart Code
import 'package:flutter/material.dart';
import 'dart:io';
import 'package:firebase_remote_config/firebase_remote_config.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:package_info/package_info.dart';
import 'package:flutter/cupertino.dart';
const APP_STORE_URL = 'https://apps.apple.com/us/app/appname/idAPP-ID';
const PLAY_STORE_URL =
'https://play.google.com/store/apps/details?id=APP-ID';
versionCheck(context) async {
//Get Current installed version of app
final PackageInfo info = await PackageInfo.fromPlatform();
double currentVersion = double.parse(info.version.trim().replaceAll(".", ""));
//Get Latest version info from firebase config
final RemoteConfig remoteConfig = await RemoteConfig.instance;
try {
// Using default duration to force fetching from remote server.
await remoteConfig.fetch(expiration: const Duration(seconds: 0));
await remoteConfig.activateFetched();
remoteConfig.getString('force_update_current_version');
double newVersion = double.parse(remoteConfig
.getString('force_update_current_version')
.trim()
.replaceAll(".", ""));
if (newVersion > currentVersion) {
_showVersionDialog(context);
}
} on FetchThrottledException catch (exception) {
// Fetch throttled.
print(exception);
} catch (exception) {
print('Unable to fetch remote config. Cached or default values will be '
'used');
}
}
//Show Dialog to force user to update
_showVersionDialog(context) async {
await showDialog<String>(
context: context,
barrierDismissible: false,
builder: (BuildContext context) {
String title = "New Update Available";
String message =
"There is a newer version of app available please update it now.";
String btnLabel = "Update Now";
String btnLabelCancel = "Later";
return Platform.isIOS
? new CupertinoAlertDialog(
title: Text(title),
content: Text(message),
actions: <Widget>[
FlatButton(
child: Text(btnLabel),
onPressed: () => _launchURL(**Config**.APP_STORE_URL),
),
FlatButton(
child: Text(btnLabelCancel),
onPressed: () => Navigator.pop(context),
),
],
)
: new AlertDialog(
title: Text(title),
content: Text(message),
actions: <Widget>[
FlatButton(
child: Text(btnLabel),
onPressed: () => _launchURL(**Config**.PLAY_STORE_URL),
),
FlatButton(
child: Text(btnLabelCancel),
onPressed: () => Navigator.pop(context),
),
],
);
},
);
}
_launchURL(String url) async {
if (await canLaunch(url)) {
await launch(url);
} else {
throw 'Could not launch $url';
}
}
Config Error for App and Play Store: Undefined name 'Config'.
Try correcting the name to one that is defined, or defining the name.
In checkUpdate.dart we need to import the firebase_remote_config package that exposes the RemoteConfig class:
import 'package:firebase_remote_config/firebase_remote_config.dart';
Make sure to install it before.
The versionCheck() function shall be invoked from a StatefulWidget, hence, a good place to call it would be inside the first screen Widget, for example:
class FirstScreen extends StatefulWidget {
const FirstScreen({ Key key }) : super(key: key);
#override
_FirstScreenState createState() => _FirstScreenState();
}
class _FirstScreenState extends State<FirstScreen> {
#override
void initState() {
super.initState();
WidgetsBinding.instance
.addPostFrameCallback((_) => versionCheck(context));
}
#override
Widget build(BuildContext context) {
return Container(color: const Color(0xFFFFE306));
}
}

How can I add splash screen I my flutter app?

I was going through various articles about adding splash screen to the app . I want to create splash screen through the splash screen package also other methods are welcome but I am not able to figure out where and how to put out the code for adding the splash screen I am a beginner in flutter and dart. I have attached the required code below:-
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
#override
void initState() {
super.initState();
getUserInfo();
}
Future getUserInfo() async {
await getUser();
setState(() {});
print(uid);
}
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Login',
home: (uid!=null && authSignedIn != false) ? FirstScreen() : LoginPage(),
);
}
}
final FirebaseAuth _auth = FirebaseAuth.instance;
final GoogleSignIn googleSignIn = GoogleSignIn();
bool authSignedIn;
String uid;
String name;
String imageUrl;
Future getUser() async {
// Initialize Firebase
await Firebase.initializeApp();
SharedPreferences prefs = await SharedPreferences.getInstance();
bool authSignedIn = prefs.getBool('auth') ?? false;
final User user = _auth.currentUser;
if (authSignedIn == true) {
if (user != null) {
uid = user.uid;
name = user.displayName;
imageUrl = user.photoURL;
}
}
}
Future<String> signInWithGoogle() async {
// Initialize Firebase
await Firebase.initializeApp();
final GoogleSignInAccount googleSignInAccount = await googleSignIn.signIn();
final GoogleSignInAuthentication googleSignInAuthentication = await googleSignInAccount.authentication;
final AuthCredential credential = GoogleAuthProvider.credential(
accessToken: googleSignInAuthentication.accessToken,
idToken: googleSignInAuthentication.idToken,
);
final UserCredential userCredential = await _auth.signInWithCredential(credential);
final User user = userCredential.user;
if (user != null) {
// Checking if email and name is null
assert(user.uid != null);
assert(user.displayName != null);
assert(user.photoURL != null);
uid = user.uid;
name = user.displayName;
imageUrl = user.photoURL;
assert(!user.isAnonymous);
assert(await user.getIdToken() != null);
final User currentUser = _auth.currentUser;
assert(user.uid == currentUser.uid);
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setBool('auth', true);
return 'Google sign in successful, User UID: ${user.uid}';
}
return null;
}
void signOutGoogle() async {
await googleSignIn.signOut();
await _auth.signOut();
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setBool('auth', false);
uid = null;
name = null;
imageUrl = null;
print("User signed out of Google account");
}
There are two methods I know about splash screen the native one and the non native :
In this answer I will give you the non native solution without using a plugin :
Splash Screen is a view where you can do all what you want with flutter widgets :
You can create your view then add it in main.dart home: SplashScreen();
->Show that SplashScreen for (3,5 secs) and then do a pushReplacement navigation to your first view :
This an example of Splash Screen :
import 'dart:async';
import 'package:flutter/material.dart';
class SplashPage extends StatefulWidget {
#override
createState() => _SplashPageState();
}
class _SplashPageState extends State<SplashPage> {
#override
void initState() {
super.initState();
Timer(Duration(seconds: 5),
() => Navigator.pushReplacementNamed(context, "TabsRoute"));
}
#override
void dispose() {
super.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Center(
child: Container(
width: 144,
height: 144,
child: Image.asset("images/logo.png"),
),
),
Center(
child: Container(
child: Text(
"Company Name",
style: TextStyle(
fontSize: 28,
),
),
),
),
],
),
);
}
}
Implementation in main.dart :
import 'package:flutter/material.dart';
import 'package:base_project/pages/TabsPage.dart';
import 'package:base_project/pages/SplashPage.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
routes: {
'TabsRoute':(context)=>TabsPage(),
},
home: SplashPage(),
);
}
}
Full Application Example here on Github : https://github.com/HoussemTN/flutter_base_project
As stated in other comments there are two methods. The native and the non native, but I would recommend the native since the non native takes few split seconds to pop up and takes more if you're using the debug apk. Of course you don't want the user to look at that black screen even for a split second. The method is a little tricky cue you have to go through your config files.
I'll go with an example in one of my projects and I'm only showing the android one because I've never tried the IOS solution.
in your project folder tree you go to
your_project_name/android/app/src/main/res/
the folders inside the rectangular area are your workspace for this operation.
all the things you're going to edit are XML files and you only have to do few touches and you're done.
choose the image you want to see in the splash screen and make sure it's around 100 px give or take so that you can see it if it's too big it will be rendered but you'll see parts. And also make sure the name doesn't contain any special characters or capital letters or spaces just make it simple like splash_screen and don't add the picture format extension like *.png / *.jpeg just the name. Then put it in the drawable folder you have in your project. Then go to drawable-v21 and go to launch_background.xml like in the picture below and uncomment that commented section
You'll make two changes in this file. First change that ic_launcher to your picture/icon name, which in our case is splash_screen and add a line specifying the background color of the screen.
<item android:drawable="#color/teal" />
note: teal here is the name I chose for my color
The final result should look like this:
Now you only have one last thing to do which is defining that color in xml format which is why I mentioned before that we'll use the values folder as well.
Go to your values folder and create a new XML file called colors.xml and put inside it this XML code.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="teal">#009688</color>
</resources>
like this
of course you'll need to change the color name and the color hex value.
And VOILA!
I know this is probably a late answer and and a long one, if it doesn't help you right now maybe it'll help somebody in need in the future.

How do i run the charts in main dart? - flutter

I am trying to run charts from a library in flutter. I can't run in using main.dart.
Main.dart:
import './widgets/chart.dart';
void main() {
runApp(
new MaterialApp(
home: PointsLineChart(),
),
);
}
chart.dart:
import 'package:flutter/material.dart';
import 'package:charts_flutter/flutter.dart' as charts;
class PointsLineChart extends StatelessWidget {
final List<charts.Series> seriesList;
final bool animate;
PointsLineChart(this.seriesList, {this.animate});
/// Creates a [LineChart] with sample data and no transition.
factory PointsLineChart.withSampleData() {
return new PointsLineChart(
_createSampleData(),
// Disable animations for image tests.
animate: false,
);
}
#override
Widget build(BuildContext context) {
return new charts.LineChart(seriesList,
animate: animate,
defaultRenderer: new charts.LineRendererConfig(includePoints: true));
}
/// Create one series with sample hard coded data.
static List<charts.Series<LinearSales, int>> _createSampleData() {
final data = [
new LinearSales(0, 5),
new LinearSales(1, 25),
new LinearSales(2, 100),
new LinearSales(3, 75),
];
return [
new charts.Series<LinearSales, int>(
id: 'Sales',
colorFn: (_, __) => charts.MaterialPalette.blue.shadeDefault,
domainFn: (LinearSales sales, _) => sales.year,
measureFn: (LinearSales sales, _) => sales.sales,
data: data,
)
];
}
}
/// Sample linear data type.
class LinearSales {
final int year;
final int sales;
LinearSales(this.year, this.sales);
}
The error that i am getting is that in main.dart i need to input something in order to run chart.dart. In PointsLineChart(),
it gives me error:
1 required argument(s) expected, but 0 found.dart(not_enough_required_arguments)
(new) PointsLineChart(List> seriesList, {bool animate}) → PointsLineChart
The constructor of PointsLineChart takes two argument:
PointsLineChart(this.seriesList, {this.animate});
whereas in your main.dart, you give no arguments:
home: PointsLineChart(),// here you need to add two arguments!!!
Change the code as below:
runApp(
new MaterialApp(
home: PointsLineChart(PointsLineChart.createSampleData(), animate: false),
),
);
also change _createSampleData to createSampleData to make it public.

Categories

Resources