Error: The getter 'title' isn't defined for the type 'RSSParser' - flutter

I wanted to implements a simple tutorial of how parsing an Rss Feed with Flutter, here is my code:
import 'package:flutter/material.dart';
import 'package:webfeed/webfeed.dart';
import 'package:http/http.dart' as http;
import 'package:url_launcher/url_launcher.dart';
import 'package:cached_network_image/cached_network_image.dart';
class RSSParser extends StatefulWidget {
#override
_RSSParserState createState() => _RSSParserState();
}
class _RSSParserState extends State<RSSParser> {
final String url = "https://www.90min.com/posts.rss";
RssFeed _feed;
String _title;
static const String loadingFeedMsg = 'Loading Feed...';
static const String feedLoadErrorMsg = 'Error Loading Feed.';
static const String feedOpenErrorMsg = 'Error Opening Feed.';
Future<RssFeed> loadFeed() async{
try{
final client = http.Client();
final response = await client.get(url);
return RssFeed.parse(response.body);
}
catch(e){
}
return null;
}
updateTitle(title){
setState(() {
_title = title;
});
}
#override
void initState() {
// TODO: implement initState
super.initState();
updateTitle(widget.title);
}
updateFeed(feed){
setState(() {
_feed = feed;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(_title),
),
);
}
}
The problem is that i got a compilation error in that instruction
updateTitle(widget.title);
with the following error message:
The getter 'title' isn't defined for the type 'RSSParser'
In the tutorial, it works fine!!
Do you have an idea how to solve this?
Thank you

You haven't declared title for you RSS widget. It should look something like ths:
class RSSParser extends StatefulWidget {
final String title;
const RSSParser({required this.title});
This should solve your error.

This is not working because there is not title in RSS class.
I think you are not clear with use of widget.something. It means that in the class which extends StatefulWidget there is a something parameter which i need to get in stateObject.
See the code to understand.
class YellowBird extends StatefulWidget {
const YellowBird({ Key? key }) : super(key: key);
String someData = 'SomeData'; // Some data
#override
_YellowBirdState createState() => _YellowBirdState();
}
//This is the state object
class _YellowBirdState extends State<YellowBird> {
// Now that if you need some data from the above class. You use use this widget.someData to get it here
String getHere = widget.someData ;
#override
Widget build(BuildContext context) {
return Container(color: const Color(0xFFFFE306));
}
}

Related

Riverpod is not updating UI widget on state change

main.dart
void main() {
runApp(ProviderScope(child: MyApp()));
}
class MyApp extends ConsumerWidget {
MyApp({Key? key}) : super(key: key);
final _appProvider =
ChangeNotifierProvider<AppProvider>((ref) => AppProvider());
final _profileProvider = ChangeNotifierProvider<ProfileProvider>((ref) {
return ProfileProvider();
});
#override
Widget build(BuildContext context, WidgetRef ref) {
AppProvider appProvider = ref.watch(_appProvider);
ProfileProvider profileManager = ref.watch(_profileProvider);
print(appProvider.appLocale);
}
appProvider.dart
class AppProvider extends ChangeNotifier {
Locale? _appLocale = const Locale('en');
Locale get appLocale => _appLocale ?? const Locale("en");
static const supportedLanguage = [Locale('en', 'US'), Locale('km', 'KH')];
void changeLanguage(Locale type) async {
_appLocale = type;
notifyListeners();
}
}
// when i log value of _appLocale here , I can see the update value based on the state change. but it does not re render UI widgeet.
I fixed it by declaring global provider, remove any deplicated provider, same name, in other files.

Is there anyway I could pass an async funtion as a parameter to a constructor

I am trying to assign an async function to an instance variable.
I have tried:
class TextBox extends StatefulWidget {
late String message;
late bool isPass;
late Function(String?) callback;
TextBox(String message, bool isPass, Future<dynamic> Function(String?) async func) {
this.message = message;
this.isPass = isPass;
this.callback = func;
}
}
But get the following exception:
Expected to find ')'
I know why I get the error. I just dont know the proper syntax to do this in dart.
You can use this line of code:
final Future<void> callback;
You can change the void type to any data type you want.
You do not need to use the keyword async because making the function return a Future is enough.
Also, you can write a constructor without a body.
class TextBox extends StatefulWidget {
final String message;
final bool isPass;
final Future<dynamic> Function(String?) callback;
TextBox(this.message, this.isPass, this.callback);
...
import 'package:flutter/material.dart';
class MyHomePage extends StatefulWidget {
late String message;
late bool isPass;
late Future<String> data;
MyHomePage(this.message, this.isPass, this.data);
#override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
String getData = '';
#override
MyHomePage get widget => super.widget;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('$getData Test Demo'),
),
body: Container(),
);
}
getFutureData() async {
getData = await widget.data;
setState(() {});
}
}
Achieve like this have used String you can use your custom class

WebSocketChannel becomes null when passed to a StatefulWidget's State class

I have a simple client code in which I'm trying to pass the WebSocketChannel instance to an inner stateful widget, and for some reason when I try to run the code the app crushes and displays on the screen "Unexpected null value. See also: https://flutter.dev/docs/testing/errors". It would be greatly appreciated if someone could explain to me why this happens and how to fix it.
The code:
import 'package:flutter/material.dart';
import 'package:web_socket_channel/web_socket_channel.dart';
class TestWidget extends StatefulWidget {
final WebSocketChannel channel;
const TestWidget(this.channel);
#override
_TestWidgetState createState() => _TestWidgetState();
}
class _TestWidgetState extends State<TestWidget> {
String buttonText = '';
_TestWidgetState() {
widget.channel.stream.listen((data){
setState(() {buttonText = data;});
});
}
#override
Widget build(BuildContext context) {
return ElevatedButton(
onPressed: (){widget.channel.sink.add('hello');},
child: Text(buttonText)
);
}
}
class App extends StatelessWidget {
final WebSocketChannel channel = WebSocketChannel.connect(
Uri.parse('ws://localhost:8000/')
);
#override
Widget build(BuildContext context) {
return MaterialApp(home: Scaffold(body:
TestWidget(channel)
));
}
}
void main() {
runApp(App());
}
Thanks in advance for the help.
Any particular reason why you put
final WebSocketChannel channel = WebSocketChannel.connect(
Uri.parse('ws://localhost:8000/')
);
in App? Move this line code to TestStateWidget constructor. It's best practice u follow null safety method when try to access an object.

Get class reference from routes flutter

Presume I have three classes: main, EndpointList and FillDataClass.
I have defined some routes in my main class as such:
void main() {
runApp(MaterialApp(
title: 'Named Routes Demo',
initialRoute: '/',
routes: {
'/': (context) => MyApp(),
'/endpoint_list': (context) => EndpointList(),
},
));
}
My EndpointList class is a simple list view:
import 'package:flutter/material.dart';
class EndpointData {
EndpointData(this.name, this.id, this.token, this.isIncoming);
final String name;
final String id;
final String token;
bool isIncoming;
}
class EndpointList extends StatefulWidget {
EndpointList({Key key}) : super(key: key);
#override
_EndpointList createState() => new _EndpointList();
}
class _EndpointList extends State<EndpointList> {
List<EndpointData> endpointList = <EndpointData>[];
#override
Widget build(BuildContext context) {
// build and show list
}
void insertEndpoint(EndpointData endpointData){
endpointList.add(endpointData);
}
}
My question is, how can I access and instance of EndpointList, from class that is not main, in order to call the insertEndpoint method?
In my java mind, I want to do this:
Endpoint endpoint = new Endpoint(); // This is done in route in main class
And then from class FillDataClass (presuming endpoint has been properly instanced in FillDataClass via constructor):
endpoint.insertEndpoint(data);
How can I create and access endpoint in order to populate, and then display, my list?
Use a separate the Endpoint class which will contain an insertEndPoint mothed.
class EndpointData {
EndpointData(this.name, this.id, this.token, this.isIncoming);
final String name;
final String id;
final String token;
bool isIncoming;
List<EndpointData> _endpointList = <EndpointData>[];
void insertEndpoint(EndpointData endpointData){
_endpointList.add(endpointData);
}
}
Then in your UI
class EndpointListUI extends StatefulWidget {
EndpointListUI({Key key}) : super(key: key);
#override
_EndpointListUI createState() => new _EndpointListUI();
}
class _EndpointListUI extends State<EndpointListUI> {
//You can create instance from anywhere and insert data to it
List<EndpointData> endpointList = <EndpointData>[];
endpointList.add(endpointData);
#override
Widget build(BuildContext context) {
// build and show list
}
}

Passing data to StatefulWidget and accessing it in it's state in Flutter

I have 2 screens in my Flutter app: a list of records and a screen for creating and editing records.
If I pass an object to the second screen that means I am going to edit this and if I pass null it means that I am creating a new item. The editing screen is a Stateful widget and I am not sure how to use this approach https://flutter.io/cookbook/navigation/passing-data/ for my case.
class RecordPage extends StatefulWidget {
final Record recordObject;
RecordPage({Key key, #required this.recordObject}) : super(key: key);
#override
_RecordPageState createState() => new _RecordPageState();
}
class _RecordPageState extends State<RecordPage> {
#override
Widget build(BuildContext context) {
//.....
}
}
How can I access recordObject inside _RecordPageState?
To use recordObject in _RecordPageState, you have to just write widget.objectname like below
class _RecordPageState extends State<RecordPage> {
#override
Widget build(BuildContext context) {
.....
widget.recordObject
.....
}
}
Full Example
You don't need to pass parameters to State using it's constructor.
You can easily access these using widget.myField.
class MyRecord extends StatefulWidget {
final String recordName;
const MyRecord(this.recordName);
#override
MyRecordState createState() => MyRecordState();
}
class MyRecordState extends State<MyRecord> {
#override
Widget build(BuildContext context) {
return Text(widget.recordName); // Here you direct access using widget
}
}
Pass your data when you Navigate screen :
Navigator.of(context).push(MaterialPageRoute(builder: (context) => MyRecord("WonderWorld")));
class RecordPage extends StatefulWidget {
final Record recordObject;
RecordPage({Key key, #required this.recordObject}) : super(key: key);
#override
_RecordPageState createState() => new _RecordPageState(recordObject);
}
class _RecordPageState extends State<RecordPage> {
Record recordObject
_RecordPageState(this. recordObject); //constructor
#override
Widget build(BuildContext context) {. //closure has access
//.....
}
}
example as below:
class nhaphangle extends StatefulWidget {
final String username;
final List<String> dshangle;// = ["1","2"];
const nhaphangle({ Key key, #required this.username,#required this.dshangle }) : super(key: key);
#override
_nhaphangleState createState() => _nhaphangleState();
}
class _nhaphangleState extends State<nhaphangle> {
TextEditingController mspController = TextEditingController();
TextEditingController soluongController = TextEditingController();
final scrollDirection = Axis.vertical;
DateTime Ngaysx = DateTime.now();
ScrollController _scrollController = new ScrollController();
ApiService _apiService;
List<String> titles = [];
#override
void initState() {
super.initState();
_apiService = ApiService();
titles = widget.dshangle; //here var is call and set to
}
I have to Navigate back to any one of the screens in the list pages but when I did that my onTap function stops working and navigation stops.
class MyBar extends StatefulWidget {
MyBar({this.pageNumber});
final pageNumber;
static const String id = 'mybar_screen';
#override
_MyBarState createState() => _MyBarState();
}
class _MyBarState extends State<MyBar> {
final List pages = [
NotificationScreen(),
AppointmentScreen(),
RequestBloodScreen(),
ProfileScreen(),
];
#override
Widget build(BuildContext context) {
var _selectedItemIndex = widget.pageNumber;
return Scaffold(
bottomNavigationBar: BottomNavigationBar(
elevation: 0,
backgroundColor: Colors.white,
unselectedItemColor: Colors.grey.shade700,
selectedItemColor: Color(kAppColor),
selectedIconTheme: IconThemeData(color: Color(kAppColor)),
currentIndex: _selectedItemIndex,
type: BottomNavigationBarType.fixed,
onTap: (int index) {
setState(() {
_selectedItemIndex = index;
});
},
You should use a Pub/Sub mechanism.
I prefer to use Rx in many situations and languages. For Dart/Flutter this is the package: https://pub.dev/packages/rxdart
For example, you can use a BehaviorSubject to emit data from widget A, pass the stream to widget B which listens for changes and applies them inside the setState.
Widget A:
// initialize subject and put it into the Widget B
BehaviorSubject<LiveOutput> subject = BehaviorSubject();
late WidgetB widgetB = WidgetB(deviceOutput: subject);
// when you have to emit new data
subject.add(deviceOutput);
Widget B:
// add stream at class level
class WidgetB extends StatefulWidget {
final ValueStream<LiveOutput> deviceOutput;
const WidgetB({Key? key, required this.deviceOutput}) : super(key: key);
#override
State<WidgetB> createState() => _WidgetBState();
}
// listen for changes
#override
void initState() {
super.initState();
widget.deviceOutput.listen((event) {
print("new live output");
setState(() {
// do whatever you want
});
});
}
In my app, often instead of using stateful widgets, I use mainly ChangeNotifierProvider<T> in main.dart, some model class
class FooModel extends ChangeNotifier {
var _foo = false;
void changeFooState() {
_foo = true;
notifyListeners();
}
bool getFoo () => _foo;
}
and
var foo = context.read<FooModel>();
# or
var foo = context.watch<FooModel>();
in my stateless widgets. IMO this gives me more precise control over the rebuilding upon runtime state change, compared to stateful widgets.
The recipe can be found in the official docs, the concept is called "lifting state up".