Flutter assign generic Future<T> from function callback - flutter

Why does not generic Future<T> assign work? i Get this error: A value of type 'Future<T>?' can't be assigned to a variable of type 'Future<T>?'.
typedef SimpleFutureFunction<T> = Widget Function(void Function(Future<T>? newFuture) onFuture);
class SimpleFuture<T> extends StatefulWidget {
const SimpleFuture({Key? key, required this.simple, this.future}) : super(key: key);
final SimpleFutureFunction simple;
final Future<T>? future;
#override
State<SimpleFuture> createState() => _SimpleFutureState();
}
class _SimpleFutureState<T> extends State<SimpleFuture<T>> {
Future<T>? _future;
#override
void initState() {
super.initState();
_future = widget.future;
}
#override
Widget build(BuildContext context) {
return widget.simple.call(<T>(Future<T>? newFuture) {
setState(() {
_future = newFuture;
});
});
}
}

Related

Generic Widget for listening Streams in Flutter

I would like to create a StatefulWidget which I'll use all over the app for listening streams of different types. Since I try to keep all the widgets Stateless I wanted to extract this functionality.
I've created this:
class StreamListener<T> extends StatefulWidget {
const StreamListener({
Key? key,
required this.stream,
required this.onNewData,
required this.child,
}) : super(key: key);
final Stream<T?> stream;
final void Function(T data) onNewData;
final Widget child;
#override
State<StreamListener> createState() => _StreamListenerState<T>();
}
class _StreamListenerState<T> extends State<StreamListener> {
late StreamSubscription<T?> streamSubscription;
#override
void initState() {
streamSubscription = (widget.stream as Stream<T?>).listen(
(T? data) {
if (data != null) {
widget.onNewData(data);
}
},
);
super.initState();
}
#override
Widget build(BuildContext context) {
return widget.child;
}
#override
void dispose() {
streamSubscription.cancel();
super.dispose();
}
}
Then somewhere in the Widgets tree I use:
return StreamListener<int>(
stream: context.read<MyCubit>().toastStream,
onNewData: (int data) {
print("Received: $data");
},
child: SomeStatelessWidget(),
}
Stream logic is added to the Cubit like that:
mixin ToastStreamForCubit<T> {
final StreamController<T> _toastStreamController = StreamController<T>();
get toastStream => _toastStreamController.stream;
void emitToastEvent(T event) {
_toastStreamController.add(event);
}
}
And when I call let's say emitToastEvent(1).
I receive type '(int) => void' is not a subtype of type '(dynamic) => void'.
on line widget.onNewData(data);.
I'm not sure what is going on. I thought I've mapped all the functions and classes to a particular generic type (T), but it still says something about dynamic.
You are missing T while extending State<StreamListener>. It should be
class _StreamListenerState<T> extends State<StreamListener<T>>

The getter 'sundayIsSelected' was called on null. Receiver: null Tried calling: sundayIsSelected

here I created a model, and try to use the model in the page, but I get an error:
The getter 'sundayIsSelected' was called on null.
Receiver: null
Tried calling: sundayIsSelected
I set the sundayIsSelected in AlarmClock default value is false, why in the TimePickerPage there is still null? thanks!
Here is model code:
class AlarmClock {
bool sundayIsSelected;
//I also tried followings:
//bool sundayIsSelected = false;
AlarmClock({
this.sundayIsSelected = false,
});
}
here is my page code.
class TimePickerPage extends StatefulWidget {
final AlarmClock alarmClock;
const TimePickerPage({Key key, this.alarmClock}) : super(key: key);
#override
_TimePickerPageState createState() => _TimePickerPageState();
}
class _TimePickerPageState extends State<TimePickerPage> {
bool sundayIsSelected;
#override
void initState() {
sundayIsSelected = widget.alarmClock.sundayIsSelected;
}
Widget build(BuildContext context) {
Text(sundayIsSelected),
}
}
It is possible for alarmClock to be null, I will recommend adding required parameter on constructor and properly add others annotations.
class TimePickerPage extends StatefulWidget {
final AlarmClock alarmClock;
const TimePickerPage({Key? key, required this.alarmClock}) : super(key: key);
#override
_TimePickerPageState createState() => _TimePickerPageState();
}
class _TimePickerPageState extends State<TimePickerPage> {
late bool sundayIsSelected;
#override
void initState() {
sundayIsSelected = widget.alarmClock.sundayIsSelected;
super.initState();
}
#override
Widget build(BuildContext context) {
return Text(sundayIsSelected.toString());
}
}
And use it like
final alarmClock = AlarmClock(),
....
TimePickerPage(
alarmClock: alarmClock,
),
// or
TimePickerPage(
alarmClock: AlarmClock(),
)
...
Find more on docs.flutter.dev.

pass one variables value to another variable in flutter

In my flutter app I created variables var from, to; and pass those with their values to the next page. which I used it with the widget.from & widget.to.
but how can i pass this widget.from & widget.to variables to var newFrom, newTo; these variables?
class FirstPage extends StatelessWidget {
#override
Widget build(BuildContext context) {
var from = "Five", to = "Ten";
return SecondPage(from: from, to: to);
}
}
class SecondPage extends StatefulWidget {
final from, to;
const SecondPage({Key key, this.from, this.to}) : super(key: key);
#override
_SecondPageState createState() => _SecondPageState();
}
class _SecondPageState extends State<SecondPage> {
var newFrom = "", newTo = "";
#override
void initState() {
setState(() {
newFrom = widget.from;
newTo = widget.to;
});
super.initState();
}
#override
Widget build(BuildContext context) {
return Container(
child: Text("$newFrom $newTo"),
);
}
}

The value of local variable isn't used

I am new to flutter and I was following a tutorial when this error popped up. The ancestorRenderObjectOfType has deprecated and been replaced by findAncestorRenderObjectOfType so dart is throwing me errors.
What the tutor did in his video of old dart:
static T of<T extends BlocBase>(BuildContext context) {
final type = _typeOf<BlocProvider<T>>();
BlocProvider<T> provider = context
.context.ancestorRenderObjectOfType(type);
return provider.bloc;
}
static Type _typeOf() => T;
}
What I did in my code
static T of<T extends BlocBase>(BuildContext context) {
final type = _typeOf<BlocProvider<T>>();
BlocProvider<T> provider = context
.findAncestorRenderObjectOfType();
return provider.bloc;
}
static Type _typeOf<T>() => T;
}
If I put
BlocProvider<T> provider = context
.findAncestorRenderObjectOfType(type);
I get an error saying
Too many positional arguements. 0 expected, but 1 found.
The ENTIRE code
abstract class BlocBase {
void dispose();
}
//Genric Bloc provider
class BlocProvider<T extends BlocBase> extends StatefulWidget {
BlocProvider({
Key key,
#required this.child,
#required this.bloc,
}) : super(key: key);
final T bloc;
final Widget child;
#override
_BlocProviderState<T> createState() => _BlocProviderState<T>();
static T of<T extends BlocBase>(BuildContext context) {
final type = _typeOf<BlocProvider<T>>();
BlocProvider<T> provider = context
.findAncestorRenderObjectOfType(); //context.ancestorRenderObjectOfType(type); GOTCHA
return provider.bloc;
}
static Type _typeOf<T>() => T;
}
class _BlocProviderState<T> extends State<BlocProvider<BlocBase>> {
#override
void dispose() {
widget.bloc.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return widget.child;
}
}
Thank you!
findAncestorRenderObjectOfType doesnt take the type as argument instead it is a generic method where you can provide the type while calling the method. So your code will be as below:
static T of<T>(BuildContext context) {
BlocProvider<T> provider = context
.findAncestorRenderObjectOfType<BlocProvider<T>>();
return provider.bloc;
}

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".