Can´t pass null variable between two pages in flutter - dart

I´m trying to navigate between two pages. In second page I need a constructor so i need to declare the variable null in first page and initialize it in the second page.
In main.dart (first page) i have similar to
PostDetailsPage.tag: (context) => PostDetailsPage(new List()),
In the second page (PostDetailsPage) i have this
final List<charts.Series> seriesList;
final bool animate;
PostDetailsPage(this.seriesList, {this.animate});
When i go to page two return
< List < Series< dynamic, dynamic > > is not a subtype of type < List < Series< dynamic, String>>
So how can i solve? Initializate the value in first page and pass it? Initializate value as null in first page and pass it?
UPDATED
Main.dart class
import 'package:flutter/material.dart';
import 'package:fluttercrud/screens/login_page.dart';
import 'package:fluttercrud/screens/home_page.dart';
import 'package:fluttercrud/screens/partials/list_post.dart';
import 'package:fluttercrud/screens/maps_page.dart';
import 'package:fluttercrud/screens/post_details_page.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
final routes = <String, WidgetBuilder>{
LoginPage.tag: (context) => LoginPage(),
HomePage.tag: (context) => HomePage(),
ListPost.tag: (context) => ListPost(),
MapsPage.tag: (context) => MapsPage(),
PostDetailsPage.tag: (context) => PostDetailsPage(new List()),
};
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'iGota',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch : Colors.blue,
),
home: LoginPage(),
routes: routes,
);
}
}
PostDetailsPage.dart class
import 'package:flutter/material.dart';
import 'package:charts_flutter/flutter.dart' as charts;
class PostDetailsPage extends StatelessWidget{
static String tag = 'post-details-page';
final List<charts.Series> seriesList;
final bool animate;
PostDetailsPage(this.seriesList, {this.animate});
/// Creates a [BarChart] with sample data and no transition.
factory PostDetailsPage.withSampleData() {
return new PostDetailsPage(
_createSampleData(),
// Disable animations for image tests.
animate: false,
);
}
#override
Widget build(BuildContext context) {
return new charts.BarChart(
seriesList,
animate: animate,
);
}
/// Create one series with sample hard coded data.
static List<charts.Series<OrdinalSales, String>> _createSampleData() {
final data = [
new OrdinalSales('2014', 5),
new OrdinalSales('2015', 25),
new OrdinalSales('2016', 100),
new OrdinalSales('2017', 75),
];
return [
new charts.Series<OrdinalSales, String>(
id: 'Sales',
colorFn: (_, __) => charts.MaterialPalette.blue.shadeDefault,
domainFn: (OrdinalSales sales, _) => sales.year,
measureFn: (OrdinalSales sales, _) => sales.sales,
data: data,
)
];
}
}
/// Sample ordinal data type.
class OrdinalSales {
final String year;
final int sales;
OrdinalSales(this.year, this.sales);
}
UPDATED 2: FIXED
Main.dart
import 'package:flutter/material.dart';
import 'package:fluttercrud/screens/login_page.dart';
import 'package:fluttercrud/screens/home_page.dart';
import 'package:fluttercrud/screens/partials/list_post.dart';
import 'package:fluttercrud/screens/maps_page.dart';
import 'package:fluttercrud/screens/post_details_page.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
final routes = <String, WidgetBuilder>{
LoginPage.tag: (context) => LoginPage(),
HomePage.tag: (context) => HomePage(),
ListPost.tag: (context) => ListPost(),
MapsPage.tag: (context) => MapsPage(),
PostDetailsPage.tag: (context) => PostDetailsPage(),
};
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'iGota',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch : Colors.blue,
),
home: LoginPage(),
routes: routes,
);
}
}
PostDetailsPage.dart
import 'package:flutter/material.dart';
import 'package:charts_flutter/flutter.dart' as charts;
class PostDetailsPage extends StatefulWidget {
static String tag = 'post-details-page';
#override
PostDetailsPageState createState() => new PostDetailsPageState();
}
class PostDetailsPageState extends State<PostDetailsPage> {
List<charts.Series> seriesList = [];
bool animate;
void initState() {
super.initState();
seriesList = _createSampleData();
animate = false;
}
#override
Widget build(BuildContext context) {
return new Container(
decoration: new BoxDecoration(color: Colors.white),
child: new charts.BarChart(
seriesList,
animate: animate,
),
);
}
/// Create one series with sample hard coded data.
static List<charts.Series<OrdinalSales, String>> _createSampleData() {
final data = [
new OrdinalSales('2014', 5),
new OrdinalSales('2015', 25),
new OrdinalSales('2016', 100),
new OrdinalSales('2017', 75),
];
return [
new charts.Series<OrdinalSales, String>(
id: 'Sales',
colorFn: (_, __) => charts.MaterialPalette.blue.shadeDefault,
domainFn: (OrdinalSales sales, _) => sales.year,
measureFn: (OrdinalSales sales, _) => sales.sales,
data: data,
)
];
}
}
/// Sample ordinal data type.
class OrdinalSales {
final String year;
final int sales;
OrdinalSales(this.year, this.sales);
}

You can fix your issue by explicitly declaring the type on the List when you pass it in.
PostDetailsPage.tag: (context) => PostDetailsPage(List<charts.Series<dynamic, String>>()),
Or, you can explicitly declare the type of the list itself on the page itself:
final List<charts.Series<dynamic, String>> seriesList;
I think the intended way for the charts library to work is that you pass in an already initialized list of chart data, which the page then renders. If you want to return just with the given sample data, you should just use the given factory method PostDetailsPage.withSampleData().

Related

how can i pass a variable to a class and call that variable in any other screen without it being reset

i want to be able to call an empty variable from a class, assign a value to it and make it persistent, anything aside provider e.t.c would be help, i don't want to overhaul the entire app again to do some bloc, provider e.t.c
NB: all screens are stateful widgets
i have tried creating a class with an empty string and passing a value to it from another screen, but this doesn't seem to work
import 'package:cloud_firestore/cloud_firestore.dart';
import 'dart:async';
import 'package:firebase_auth/firebase_auth.dart';
class MethodA {
// id(user, context){
// var name =user.email;
// }
String identity;
MethodA({this.iD});
bool isLoggedIn() {
if (FirebaseAuth.instance.currentUser() != null) {
return true;
} else {
return false;
}
}
Future<void> addUserA( userinfo) async {
//this.iD=id;
Firestore.instance
.collection('user')
.document('furtherinfo').collection(identity).document('Personal Info')
.setData(userdoc)
.catchError((e) {
print(e);
});
}
each time i pass the argument to i.e foo='bar';
and i import that class in another screen, i.e screen 9, foo is automatically set to null, but i would want foo to be bar
I would suggest that you use the Provider since it is the easiest way for me to manage state throughout the app. Flutter starts with one component on top of the widget tree so i would place my provider here.
Example
void main() {runApp(MyApp());}
class MyApp extends StatelessWidget {
MyApp();
#override
Widget build(BuildContext context) {
return MultiProvider(
providers: [
StreamProvider<FirebaseUser>.value(
stream: FirebaseAuth.instance.onAuthStateChanged, // Provider to manage user throughout the app.
),
],
child: MaterialApp(
title: 'My App',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primaryColor: Colors.green,
primarySwatch: Colors.green,
accentColor: Colors.yellow,
),
home: MainPage(),
),
);
}
}
Then in your class you can do the following
class MethodAService with ChangeNotifier {
String _identity = null;
FirebaseUser _user = null;
// constructor with the (new changes )
MethodAService(FirebaseUser user){
this._user = user;
}
get identity => _identity ;
setIdentity(String identity) {
_identity = identity ;
notifyListeners(); // required to notify the widgets of your change
}
}
Then when you want to use it anywhere in your app just do the following in the build method
#override
Widget build(BuildContext context) {
final user = Provider.of<FirebaseUser>(context); // to get the current user
final methodA = Provider.of<MethodAService>(context); // get your service with identity
// now you can set the string using
methodA.setIdentity('new identity');
// or just use it like this
if(methodA.identity.isNotEmpty()){
print(methodA.identity);
}else{
print('Identity is empty');
}
return ChangeNotifierProvider<MethodAService>(
builder: (context) => MethodAService(user), // Your provider to manage your object, sending the Firebase user in
child: loggedIn ? HomePage() : LoginPage(), );
}
References
Provider Package
Fireship 185 Provider
Great Youtube video explaining the code
Update for comment
For getting the user uid you can just do user.uid
Changed code above to fit the
I'm not sure put the whole app in a StreamProvider is the best choice. That means the app will be rebuilt on each stream value.
To make a Widget available on all screens, you need a TransitionBuilder in your MaterialApp.
To avoid the external dependency you can also use an InheritedWidget
signed_user.dart
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
class SignedUser extends InheritedWidget {
final FirebaseUser user;
SignedUser({#required this.user, #required Widget child})
: super(child: child);
#override
bool updateShouldNotify(SignedUser oldWidget) => true;
static SignedUser of(BuildContext context) =>
context.inheritFromWidgetOfExactType(SignedUser);
}
my_transition_builder.dart
class MyTransitionBuilder extends StatefulWidget {
final Widget child;
const MyTransitionBuilder({Key key, this.child}) : super(key: key);
#override
_MyTransitionBuilderState createState() => _MyTransitionBuilderState();
}
class _MyTransitionBuilderState extends State<MyTransitionBuilder> {
StreamBuilder<FirebaseUser> _builder;
#override
void initState() {
super.initState();
_builder = StreamBuilder<FirebaseUser>(
stream: FirebaseAuth.instance.onAuthStateChanged,
builder: (context, snapshot) {
return SignedUser(
child: widget.child,
user: snapshot.data,
);
});
}
#override
Widget build(BuildContext context) {
return _builder;
}
}
main.dart
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
// this will make your inherited widget available on all screens of your app
builder: (context, child) {
return MyTransitionBuilder(child: child);
},
routes: {
'/editAccount': (context) => new EditAccountPage(),
},
theme: ThemeData(
primarySwatch: Colors.green,
),
home: MyHomePage(),
);
}
}
usage in edit_account_page.dart
#override
Widget build(BuildContext context) {
var user = SignedUser.of(context).user;
return Scaffold(
body: FutureBuilder<DocumentSnapshot>(
future: Firestore.instance.document('users/${user.uid}').get(),

How to delete GridView item in flutter?

I'm trying to dynamically delete simple grid item on long press;
I've tried the most obvious way: created a list of grid data, and called setState on addition or deletion of the item.
UPD: Items works properly in the list, since it's initialisation loop moved to initState() method (just as #jnblanchard said in his comment), and don't generate new items at every build() call, but deletion is still doesn't work.
If it has more items, than can fit the screen, it deletes last row, (when enough items deleted), otherwise the following exception is thrown:
I/flutter (28074): The following assertion was thrown during performLayout():
I/flutter (28074): SliverGeometry is not valid: The "maxPaintExtent" is less than the "paintExtent".
I/flutter (28074): The maxPaintExtent is 540.0, but the paintExtent is 599.3. By definition, a sliver can't paint more
I/flutter (28074): than the maximum that it can paint!
My test code now:
main class
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:options_x_ray_informer/prototyping/TestTile.dart';
class Prototype extends StatefulWidget{
#override
_PrototypeState createState() => _PrototypeState();
}
class _PrototypeState extends State<Prototype> {
//list of grid data
List<Widget> gridItemsList = [];
#override
void initState(){
super.initState();
//----filling the list----
for(int i =0; i<10; i++){
gridItemsList.add(
TestTile(i, (){
//adding callback for long tap
delete(i);
})
);
}
}
#override
Widget build(BuildContext context) {
//----building the app----
return Scaffold(
appBar: AppBar(
title: Text("Prototype"),
actions: <Widget>[
IconButton(
icon: Icon(Icons.add),
onPressed: () {
int index = gridItemsList.length+1;
add(
new TestTile(index, (){
delete(index);
})
);
},
),
]
),
body: GridView(
gridDelegate: new SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
children: gridItemsList
)
);
}
///method for adding the items
void add(Widget toAdd){
setState(() {
TestTile tile = toAdd as TestTile;
gridItemsList.add(toAdd);
print("tile number#${tile.index} added");
});
}
///method for deleting the items
void delete(int index){
setState(() {
gridItemsList.removeAt(index);
print("tile number#$index is deleted");
});
}
}
and separate widget class for grid items
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
class TestTile extends StatelessWidget{
int _index;
var _callback;
TestTile(this._index, this._callback);
get index => _index;
#override
Widget build(BuildContext context) {
return GridTile(
child: Card(
child: InkResponse(
onLongPress: _callback,
child: Center(
child:Text("data#$_index")
)
)
),
);
}
}
How can I delete an item from grid view?
p.s. the provided code is just my attempts of solving the problem - you can offer another way, if you want!
I wrote this up from the example app, it has a few things that you may find useful. Notably I abstract the list data-structure by holding the length of the list inside a stateful widget. I wrote this with a ListView but I think you could change that to a GridView without any hiccups.
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
primarySwatch: Colors.indigo,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
#override
Widget build(BuildContext context) {
return Scaffold(appBar: AppBar(
title: Text("Owl"),
actions: <Widget>[IconButton(icon: Icon(Icons.remove), onPressed: () => this.setState(() => _counter > 1 ? _counter-- : _counter = 0)), IconButton(icon: Icon(Icons.add), onPressed: () => this.setState(() => _counter++))],
),
body: ListView.builder(itemExtent: 50, itemCount: _counter, itemBuilder: (context, index) => Text(index.toString(), textAlign: TextAlign.center, style: Theme.of(context).textTheme.title))
);
}
}
Finally I've got what I wanted.
I'll leave it here for someone who might have the same problem :)
Main class:
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:options_x_ray_informer/prototyping/TestTile.dart';
class Prototype extends StatefulWidget{
#override
_PrototypeState createState() => _PrototypeState();
}
class _PrototypeState extends State<Prototype> {
//list of some data
List<Person> partyInviteList = [];
_PrototypeState(){
//filling the list
for(int i=0; i<5; i++){
partyInviteList.add(Person.generateRandomPerson());
}
print("Person ${partyInviteList.toString()}");
}
#override
Widget build(BuildContext context) {
//----building the app----
return Scaffold(
appBar: AppBar(
title: Text("Prototype"),
actions: <Widget>[
IconButton(
icon: Icon(Icons.add),
//generating an item on tap
onPressed: () {
setState(() {
partyInviteList.add(Person.generateRandomPerson());
});
},
),
]
),
body: GridView.count(
crossAxisCount: 2,
children: List.generate(partyInviteList.length, (index) {
//generating tiles with people from list
return TestTile(
partyInviteList[index], (){
setState(() {
print("person ${partyInviteList[index]} is deleted");
partyInviteList.remove(partyInviteList[index]);
});
}
);
})
)
);
}
}
///person class
class Person{
Person(this.firstName, this.lastName);
static List<String> _aviableNames = ["Bob", "Alise", "Sasha"];
static List<String> _aviableLastNames = ["Green", "Simpson", "Stain"];
String firstName;
String lastName;
///method that returns random person
static Person generateRandomPerson(){
Random rand = new Random();
String randomFirstName = _aviableNames[rand.nextInt(3)];
String randomLastName = _aviableLastNames[rand.nextInt(3)];
return Person(randomFirstName, randomLastName);
}
#override
String toString() {
return "$firstName $lastName";
}
}
Support class:
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:options_x_ray_informer/prototyping/Prototype.dart';
class TestTile extends StatelessWidget{
final Person person;
var _callback;
TestTile(this.person, this._callback);
#override
Widget build(BuildContext context) {
return GridTile(
child: Card(
child: InkResponse(
onLongPress: _callback,
child: Center(
child:Text("${person.toString()}")
)
)
),
);
}
}

Flutter - Data from json api to be listed in drop down list

I am trying to fetch the data from json api and to be listed in the drop down list but i am hitting with The method 'map' was called on null error.
import "package:flutter/material.dart";
import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;
void main() => runApp(MaterialApp(
title: "Hospital Management",
home: MyApp(),
));
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
String _mySelection;
final String url = "http://webmyls.com/php/getdata.php";
List data;
Future<String> getSWData() async {
var res = await http
.get(Uri.encodeFull(url), headers: {"Accept": "application/json"});
var resBody = json.decode(res.body);
setState(() {
data = resBody;
});
print(resBody);
return "Sucess";
}
#override
void initState() {
super.initState();
this.getSWData();
}
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: AppBar(
title: Text("Hospital Management"),
),
body: new Center(
child: new DropdownButton(
items: data.map((item) {
return new DropdownMenuItem(
child: new Text(item['item_name']),
value: item['id'].toString(),
);
}).toList(),
onChanged: (newVal) {
setState(() {
_mySelection = newVal;
});
},
value: _mySelection,
),
),
);
}
}
The error from the debug consol
flutter: The method 'map' was called on null.
flutter: Receiver: null
flutter: Tried calling: map<DropdownMenuItem<String>>(Closure:
(dynamic) => DropdownMenuItem<String>)
flutter:
flutter: When the exception was thrown, this was the stack:
flutter: #0 Object.noSuchMethod
(dart:core/runtime/libobject_patch.dart:48:5)
I am expecting to show the list of data from the json api in the drop down menu. I am beginner to dart and flutter. Help me out to solve the error.
data is not initialized. It is set on getSWData which is async.
A possible solution could be to have data as emptyList as an initial value.
List data = List();
If you want to display DropdownButton based on data, you can use FutureBuilder and show loader or something till data comes from getSWData
Your Api http://webmyls.com/php/getdata.php returns a list not a map. Hence, it cannot have direct property advisor_report. Consider removing it.
Data should be changed inside setState.
You never called getSWData()
Below is more improved example.
import "package:flutter/material.dart";
import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;
void main() => runApp(MaterialApp(
title: "Hospital Management",
home: MyApp(),
));
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
String _mySelection;
final String url = "http://webmyls.com/php/getdata.php";
List data;
Future<String> getSWData() async {
var res = await http
.get(Uri.encodeFull(url), headers: {"Accept": "application/json"});
var resBody = json.decode(res.body);
setState(() {
data = resBody;
});
print(resBody);
return "Sucess";
}
#override
void initState() {
super.initState();
this.getSWData();
}
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: AppBar(
title: Text("Hospital Management"),
),
body: new Center(
child: new DropdownButton(
items: data.map((item) {
return new DropdownMenuItem(
child: new Text(item['item_name']),
value: item['id'].toString(),
);
}).toList(),
onChanged: (newVal) {
setState(() {
_mySelection = newVal;
});
},
value: _mySelection,
),
),
);
}
}

How fetch data from Internet in this example?

This is one official example of simple BarChart for Flutter app - https://google.github.io/charts/flutter/example/bar_charts/simple
I wood like fetch data from Internet for this chart. Here is the data - http://skazkimal.ru/hr-metrics/headcount.json
My code is not work, because method _createSampleData is async:
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:charts_flutter/flutter.dart' as charts;
import 'package:hr_metrics/FetchChartData.dart';
import 'package:http/http.dart' as http;
class SalaryView extends StatelessWidget{
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text('FFFFFFFFF'),
),
body: Padding(
padding: const EdgeInsets.all(10.0),
child: new SalaryChart.withSampleData(),
),
);
}
}
class SalaryChart extends StatelessWidget{
final List<charts.Series> seriesList;
final bool animate;
SalaryChart(this.seriesList, {this.animate});
/// Creates a [BarChart] with sample data and no transition.
factory SalaryChart.withSampleData() {
return new SalaryChart(
_createSampleData(),
// Disable animations for image tests.
animate: true,
);
}
#override
Widget build(BuildContext context) {
// This is just a simple bar chart with optional property
// [defaultInteractions] set to true to include the default
// interactions/behaviors when building the chart.
// This includes bar highlighting.
//
// Note: defaultInteractions defaults to true.
//
// [defaultInteractions] can be set to false to avoid the default
// interactions.
return new charts.BarChart(
seriesList,
animate: animate,
defaultInteractions: true,
barRendererDecorator: new charts.BarLabelDecorator<String>(),
vertical: false,
);
}
/// Create one series with sample hard coded data.
static Future<List<charts.Series<ChartData, String>>> _createSampleData() async {
final data = await fetchData(http.Client());
return [
new charts.Series<ChartData, String>(
id: 'Numbers',
domainFn: (ChartData series, _) => series.period,
measureFn: (ChartData series, _) => series.count,
data: data,
labelAccessorFn: (ChartData series, _) => '${series.count.toString()}'
)
];
}
}
/// Sample ordinal data type.
class OrdinalSalary {
final String year;
final int salary;
OrdinalSalary(this.year, this.salary);
}
You cannot use an async method in a constructor like that. Instead, you should create an async method like so:
static Future<SalaryChart> withSampleData() => _createSampleData().then((data) => SalaryChart(data, animate: true));
Which you would use elsewhere:
SalaryChart myChart = await SalaryChart.withSampleData();

flutter: route into different pages according to different status

Trying to do a redirect depending on user status in my app (logged in or not), but it won't work as I want it to as I am not sure how to get the BuildContext inside the method.
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:t2/helpers/currentuser.dart';
import 'screens/dashboard.dart';
import 'screens/login.dart';
void main() => runApp(new MyApp());
CurrentUser user = new CurrentUser();
Future checkActiveUser() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
user.usr = prefs.get('usr');
user.pwd = prefs.get('pwd');
if (user.usr.length == 0 && user.pwd.length == 0) {
user.isLoggedIn = false;
Navigator.of(x).pushNamedAndRemoveUntil('/dashboard', (Route<dynamic> route) => false);
} else {
// Send to login screen
user.isLoggedIn = false;
Navigator.of(x).pushNamedAndRemoveUntil('/login', (Route<dynamic> route) => false);
}
return user.isLoggedIn;
/*
// How to read/write to local storage
int counter = (prefs.getInt('counter') ?? 0) + 1;
print('Pressed $counter times.');
prefs.setInt('counter', counter);
*/
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Flutter Demo',
theme: new ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or press Run > Flutter Hot Reload in IntelliJ). Notice that the
// counter didn't reset back to zero; the application is not restarted.
primarySwatch: Colors.blue,
),
home: new MyHomePage(),
routes: <String, WidgetBuilder>{
'/dashboard': (BuildContext context) => new Dashboard(),
'/login': (BuildContext context) => new Login()
});
}
}
class MyHomePage extends StatelessWidget {
var isLoggedIn = checkActiveUser();
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text('Demo Building'),
),
body: new Container(
child: new Center(
child: new Column(
children: <Widget>[new Text('DASHBOARD')],
),
)));
}
}
If you have suggestions for a different approach, I'm all ears! I basically want to run this check on app load and redirect accordingly.
Regards, Bob
UPDATED CODE: Tried the suggestion from Hadrien, and got a step closer. It now runs and I get contact access but, get the following error:
'Navigator operation requested with a context that does not include a Navigator. The context used to push or pop routes from the Navigator must be that of a widget that is a descendant of a Navigator widget.'
This is the updated code:
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:t2/helpers/currentuser.dart';
import 'screens/dashboard.dart';
import 'screens/login.dart';
void main() => runApp(new MyApp());
CurrentUser user = new CurrentUser();
checkActiveUser(BuildContext context) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
try {
user.usr = prefs.get('usr');
user.pwd = prefs.get('pwd');
if (user.usr.length == 0 && user.usr.length == 0) {
user.isLoggedIn = false;
Navigator
.of(context)
.pushNamedAndRemoveUntil('/dashboard', (Route<dynamic> route) => false);
} else {
throw new Exception('No user data found');
}
} catch (e) {
// Send to login screen
user.isLoggedIn = false;
Navigator
.of(context)
.pushNamedAndRemoveUntil('/login', (Route<dynamic> route) => false);
}
/*
// How to read/write to local storage
int counter = (prefs.getInt('counter') ?? 0) + 1;
print('Pressed $counter times.');
prefs.setInt('counter', counter);
*/
}
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => new _MyAppState();
}
class _MyAppState extends State<MyApp> {
void initState() {
super.initState();
checkActiveUser(context);
}
#override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Welcome to Flutter',
home: new Scaffold(
appBar: new AppBar(
title: new Text('CADSYS'),
),
body: new Center(
child: new Text('Loading...'),
),
),
routes: <String, WidgetBuilder> {
'/dashboard': (BuildContext context) => new Dashboard(),
'/login': (BuildContext context) => new Login()
},
);
}
}
I would probably do it a little differently... instead of pushing a route inside a function, set the login state inside your StatefulWidget and then set the body based on that.
body: user.isLoggedIn ? new Dashboard() : new Login(),
then elsewhere in your code you'll need to check the active user and do setState((){ user.isLoggedIn = true; }); (or false).
When the login state changes, your view will automatically update with the new Widget.
The Navigator come with the MaterialApp widget, so you can only access it from the routes you defined in it and from their child. (Login, Dashboard, MyHomePage).
if you transform your MyHomePage widget into a stateful widget. you will be able to call your checkActiveUser() function inside initState
initState() async {
super.initState();
checkActiveUser(context);
}

Resources