How to pass data to a class in a flutter app - flutter

I am tryin to pass data to a class in flutter but it is failing with this error and i dont know how to debug it, I am new to flutter:
errors.dart:187 Uncaught (in promise) Error: Invalid argument(s): feed not found
How do I know which feed it can not find?
I tried following this but ity is not working. Here is my code for main.dart:
void main() async {
final AtomFeed feed = await RssService().getFeed();
runApp(Start(feed));
}
class Start extends StatelessWidget {
final AtomFeed feed;
Start(this.feed);
#override
Widget build(BuildContext context) {
return MaterialApp(
home: DefaultTabController(
length: 5,
child: Scaffold(
appBar: AppBar(
bottom: TabBar(
tabs: [
Tab(text: 'First', icon: Icon(Icons.music_note)),
Tab(text: 'Second', icon: Icon(Icons.music_video)),
],
),
title: Text('Start'),
backgroundColor: Colors.green,
),
body: TabBarView(
children: [
First(this.feed),
MyHomePage(title: 'Wowzers!'),
],
),
),
),
);
}
}
Then in First:
class First extends StatelessWidget {
final AtomFeed feed;
First(this.feed);
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('RSS'),
),
body: ListView.builder(
itemCount: this.feed.items.length,
itemBuilder: (BuildContext ctxt, int index) {
final item = this.feed.items[index];
return ListTile(
title: Text(item.title),
subtitle: Text('Published at ' +
DateFormat.yMd().format(DateTime.parse(item.published))),
contentPadding: EdgeInsets.all(16.0),
onTap: () async {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => WebViewContainer(
item.id.replaceFirst('http', 'https'))));
},
);
}),
);
}
}

I renamed all feed variables to feed1, feed2, ect. The problem was not from any of my variables, it was from a method to the rss service.

Related

Refresh the page data when you go to this page in the flutter

I'm trying to write a small application in which I collect data through api. I take the data, everything works. I decided to make a navigation bar to switch between pages. But when I try on the pages they are empty. In order for the data to be updated on the page, I need to click "Hot reload". I will be grateful for your help.
My main.dart:
import 'package:flutter/material.dart';
import 'package:flutter_app_seals/model/dataArea_list/JsonDataArea.dart';
import 'package:flutter_app_seals/model/object_list/JsonObject.dart';
import 'package:flutter_app_seals/model/seals_list/JsonSeals.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new MaterialApp(
home: new HomeScreen());
}
}
class HomeScreen extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: AppBar(
centerTitle: true,
title: Text('Журнал пломби'),
),
// body: Seals(),
drawer: Drawer(
child: ListView(
children: <Widget>[
ListTile(
title: Text("Seals List"),
trailing: Icon(Icons.arrow_back),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => Seals()),
);
}
)
],
),
),
);
}
}
class Seals extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home:JsonParseSeals(),
);
}
}
My modul Seals:
import 'package:flutter/material.dart';
import 'package:flutter_app_seals/model/seals_list/SealsListGet.dart';
import 'package:flutter_app_seals/model/seals_list/ServicesSeals.dart';
class JsonParseSeals extends StatefulWidget {
//
JsonParseSeals() : super();
#override
_JsonParseSealsState createState() => _JsonParseSealsState();
}
class _JsonParseSealsState extends State <StatefulWidget> {
//
List<SealList> _seals;
bool _loading;
#override
void initState(){
super.initState();
_loading = true;
Services.getSeals().then((seals) {
_seals =seals;
_loading = false;
}
);
}
#override
Widget build(BuildContext context) {
// TODO: implement build
return Scaffold(
appBar: AppBar(
centerTitle: true,
title: Text('Список пломби'),
),
body: ListView.builder(
physics: BouncingScrollPhysics(),
padding: EdgeInsets.all(40),
itemCount: null == _seals ? 0 :_seals.length,
itemBuilder: (_,index) => Card(
color: Colors.red[300],
margin: EdgeInsets.symmetric(vertical: 7),
child:ListTile(
title: Text(_seals[index].sealNumber,
style: TextStyle(fontSize: 30),
),
subtitle: Text(
"${_seals[index].used}" ),
leading: Icon(Icons.local_activity,
size: 40,
color: Colors.black87,
),
),
),
),
);
}
}
My code :
Code after change:
Try to wrap your screen with data in FutureBuilder (you can read more about this widget here):
class _JsonParseSealsState extends State <StatefulWidget> {
#override
Widget build(BuildContext context) {
return FutureBuilder<List<SealList>>(
future: Services.getSeals(),
builder: (context, snapshot) {
// Data is loading, you should show progress indicator to a user
if (!snapshot.hasData) {
return Center(
child: CircularProgressIndicator(),
);
}
// Data is loaded, handle it
return ListView.builder(
physics: BouncingScrollPhysics(),
padding: EdgeInsets.all(40),
itemCount: snapshot.data.length,
itemBuilder: (_, index) {
final item = snapshot.data[index];
return Card(
color: Colors.red[300],
margin: EdgeInsets.symmetric(vertical: 7),
child: ListTile(
title: Text(
item.sealNumber,
style: TextStyle(fontSize: 30),
),
subtitle: Text("${item.used}"),
leading: Icon(
Icons.local_activity,
size: 40,
color: Colors.black87,
),
),
);
},
),
}
);
}
}

Flutter no backbutton on topleft, when calling a listviewScreen from a drawer

im new to Flutter. I have a mainpage, which is a listview with a drawer. I manage to call a second listview, which is mainly a copy of the mainpage without the drawer. But on the secondpage i see no backbutton on the top left.
Here i call the secondpage inside the drawer:
onTap: () {
Navigator.push(
context,
new MaterialPageRoute(builder: (context) => new ListViewTeam()),
);
},
and my secondpage begins with this code:
#override
_ListViewTeamState createState() => new _ListViewTeamState();
}
class _ListViewTeamState extends State<ListViewTeam> {
List<Team> items = new List();
DatabaseHelper db = new DatabaseHelper();
#override
void initState() {
super.initState();
db.getAllTeams().then((teams) {
setState(() {
teams.forEach((team) {
items.add(Team.fromMap(team));
});
});
});
}
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Teams',
home: Scaffold(
appBar: AppBar(
title: Text('Teams'),
centerTitle: true,
backgroundColor: Colors.teal,
),
body: Center(
child: ListView.builder(
itemCount: items.length,
padding: const EdgeInsets.all(1.0),
itemBuilder: (context, position) {
Hope someone can help a noob?
You can try with the Below code replace this code at your second page I hope this will work for you
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Teams'),
centerTitle: true,
backgroundColor: Colors.teal,
),
body: Center(
child: ListView.builder(
itemCount: items.length,
padding: const EdgeInsets.all(1.0),
itemBuilder: (context, position) {

Page Route with new file dart

How to use MaterialPageRoute with a new file dart?
My codes:
main.dart
import 'package:flutter/material.dart';
import 'package:hello_world/settings_page.dart';
void main() => runApp(Belajar());
class Belajar extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
leading: Icon(Icons.android),
title: Text('Hello World'),
actions: [
IconButton(
icon: Icon(Icons.settings),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) {
return SettingsPage();
},
),
);
},
)
],
),
),
);
}
}
settings_page.dart
import 'package:flutter/material.dart';
class SettingsPage extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
leading: IconButton(
icon: Icon(Icons.arrow_back),
onPressed: () {
Navigator.pop(context);
},
),
),
);
}
}
I tried the code above. But, give me an error:
Navigator operation requested with a context that does not include a Navigator.
What wrong with my code?
you are missing just one thing
MaterialApp(
home:Builder(
//use this context to push new route
builder:(context){
return Scaffold(
appBar://..
);
}
)
)
here builder will introduce a new context which will contain the navigator introduced by material app
First create a class for example runFunction()
and you can use these code for going to that screen
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => runFunction(),
),
);
an example of runFuction
class _recipeSearchState extends State<recipeSearch> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('hello'),
),
body: SingleChildScrollView(
scrollDirection: Axis.vertical,
child: Column(
children: [
Text("Text"),
],
),
),
);
}
}

How to rebuild only modified item in list with ChangeNotifier

I am trying to fetch the data from server. When the button is pushed, a dummy widget is added to the list and response is shown after data is fetched.
I called notifyListeners() when item is added to the list and when data is loaded, but all of items are rebuilt even unchanged items.
How can I prevent rebuilding unchanged item?
Here's my code.
class Item {
bool isLoaded;
String request;
String data;
Item(this.request) : isLoaded = false;
Future loadItemData() {
// dummy for api request
return Future.delayed(Duration(seconds: 3)).whenComplete(() {
data = "item get result";
isLoaded = true;
});
}
}
class ItemList extends ChangeNotifier {
List<Item> lists = [];
void addItem(String request) {
var item = Item(request);
lists.add(item);
item.loadItemData().whenComplete(() {
notifyListeners();
});
notifyListeners();
}
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return ChangeNotifierProvider(
create: (context) => ItemList(),
child: MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyItems(),
),
);
}
}
class MyItems extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("My Items"),
),
body: Consumer<ItemList>(
builder: (context, value, child) {
return Column(
children: <Widget>[
RaisedButton(
child: const Text("Add Item"),
onPressed: () {
value.addItem("dummy request id");
},
),
Expanded(
child: ListView.builder(
itemBuilder: (context, index) {
var item = value.lists[index];
return item.isLoaded
? ListTile(
title: Text(value.lists[index].data),
)
: ListTile(
leading: CircularProgressIndicator(),
);
},
itemCount: value.lists.length,
),
),
],
);
},
),
);
}
}
Make use of Unique keys with ListTile.
ListTile(
key: ValueKey(value.lists[index].data['id']),
...
)

How to change state of MaterialPageRoute?

I was following the tutorial from the Flutter docs where you create a Startup naming app. The app consists in two pages: one where there's an infinite list of randomly generated startup names that you can add to your favorites, and a favorites page where you can see the names you saved.
After completing the tutorial, I tried to add some functionality of my own, I wanted to be able to Unfavorite a name by tapping it on the "Favorites" page. Below is the code that pushes the Favorites page to the navigator:
Navigator.of(context).push(
MaterialPageRoute<void>(
builder: (BuildContext context) {
final Iterable<ListTile> tiles = _saved.map(
(WordPair pair) {
return ListTile(
title: Text(
pair.asPascalCase,
style: _biggerFont,
),
// Code I added //
trailing: Icon(Icons.delete),
onTap: () {
setState(() {
_saved.remove(pair);
});
},
// End //
);
},
);
final List<Widget> divided = ListTile
.divideTiles(
context: context,
tiles: tiles,
)
.toList();
return Scaffold(
appBar: AppBar(
title: Text('Saved suggestions'),
),
body: ListView(children: divided),
);
},
),
);
}
But it didn't worked as it should: you can indeed unsave names by tapping them, but the changes will only be shown on the screen after you go back to the main page and then to the favorites page again (or in other words, when Builder is called?).
So how do I fix this? Do I need to create a Stateful widget for the favorites page? If yes, how do I pass the _saved set to my new widget?
If anybody needs the whole code:
https://pastebin.com/asLneaKe
Wrap with StatefulBuilder works fine.
You can see full code and working demo
code snippet
MaterialPageRoute<void>(
builder: (BuildContext context) {
return StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
final Iterable<ListTile> tiles = _saved.map(
working demo
full code
import 'package:english_words/english_words.dart' as prefix0;
import 'package:flutter/material.dart';
import 'package:english_words/english_words.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Startup Name Generator',
theme: ThemeData(
primaryColor: Colors.white,
),
home: RandomWords(),
);
}
}
class RandomWords extends StatefulWidget {
#override
RandomWordsState createState() => RandomWordsState();
}
class RandomWordsState extends State<RandomWords> {
final List<WordPair> _suggestions = <WordPair>[];
final Set<WordPair> _saved = Set<WordPair>();
final TextStyle _biggerFont = const TextStyle(fontSize: 18.0);
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Startup Name Generator'), actions: <Widget>[
// Icone 3 linhas
IconButton(
icon: Icon(Icons.list),
onPressed: _pushSaved,
),
]),
body: _buildSuggestions(),
);
}
Widget _buildRow(WordPair pair) {
final bool alreadySaved = _saved.contains(pair);
return ListTile(
title: Text(
pair.asPascalCase,
style: _biggerFont,
),
trailing: Icon(
alreadySaved ? Icons.favorite : Icons.favorite_border,
color: alreadySaved ? Colors.red : null,
),
onTap: () {
setState(() {
if (alreadySaved) {
_saved.remove(pair);
} else {
_saved.add(pair);
}
});
});
}
Widget _buildSuggestions() {
return ListView.builder(
padding: const EdgeInsets.all(16.0),
itemBuilder: (context, i) {
if (i.isOdd) return Divider();
final index = i ~/ 2;
if (index >= _suggestions.length) {
_suggestions.addAll(generateWordPairs().take(10));
}
return _buildRow(_suggestions[index]);
},
);
}
void _pushSaved() {
Navigator.of(context).push(
MaterialPageRoute<void>(
builder: (BuildContext context) {
return StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
final Iterable<ListTile> tiles = _saved.map(
(WordPair pair) {
return ListTile(
title: Text(
pair.asPascalCase,
style: _biggerFont,
),
// Code I added //
trailing: Icon(Icons.delete),
onTap: () {
setState(() {
_saved.remove(pair);
});
},
// End //
);
},
);
final List<Widget> divided = ListTile.divideTiles(
context: context,
tiles: tiles,
).toList();
return Scaffold(
appBar: AppBar(
title: Text('Saved suggestions'),
),
body: ListView(children: divided),
);
});
},
),
);
}
}