pass one variables value to another variable in flutter - 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"),
);
}
}

Related

Update TextEditingController Text with Riverpod

I'm new to Riverpod and am trying to migrate an app over from Provider. If I had a TextField and wanted to set its value based on my Provider model, I would do this:
class MyWidget extends StatefulWidget{
const MyWidget({ Key? key }) : super(key: key);
#override
State<MyWidget> createState() => _MyWidgetState();
}
class _MyWidgetState extends State<MyWidget> {
var controller = TextEditingController();
#override
void didChangeDependencies() {
super.didChangeDependencies();
//Set the value here...
var model = Provider.of<Model>(context);
controller.text = model.name;
}
Widget build(BuildContext context) {
return TextField(controller: controller)
}
}
As I understand it, didChangeDependencies() would listen to changes from Provider.of<Model>(context) and update my controller accordingly.
I'm trying to pull off the same thing with Provider, but I can't ever get the TextField's value to show up.
class MyWidget extends ConsumerStatefulWidget {
const MyWidget({Key? key}) : super(key: key);
#override
ConsumerState<ConsumerStatefulWidget> createState() => _MyWidgetState();
}
class _MyWidgetState extends ConsumerState<MyWidget> {
var controller = TextEditingController();
#override
void didChangeDependencies() {
super.didChangeDependencies();
//Trying the same thing here...
final name = ref.watch(providerName);
controller.text = name;
}
Widget build(BuildContext context) {
final name = ref.watch(providerName);
return Column(
children: [
//This doesn't work:
TextField(controller: controller),
//I know my provider has the value, because this works fine:
Text(name),
]
}
}
How can I get my TextEditingController's text property to update?
From Riverpod official website
///1.Create a [StateNotifier] sub-class, StateNotifier is something where you can define functions that can change your state like in this state is of String type, you also can use objects (Classes instead of primitive types)
class Counter extends StateNotifier<String> {
Counter() : super('');
void changeText(String text){
state=text;
}
///2.Create a provider [StateNotifierProvider] with this you can use in your widget
final counterProvider = StateNotifierProvider<Counter, String>((ref) {
return Counter();
});
///3.Consume the Provider this is how we can attach state with our widget
class Home extends ConsumerWidget {
#override
Widget build(BuildContext context, WidgetRef ref) {
final text = ref.watch(counterProvider);
return Text('$text');
}
}
so here you can add you widget like button and onTap executes the code like
onTap()=>changeText(textController.text);
So your text [Text('$text');] will automatically change.
String inputText = controller.text;

Flutter assign generic Future<T> from function callback

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;
});
});
}
}

Store the filters selected in a variable

I have a code that is responsible for filtering data: the user choose the criteria that are important to him and clicks "Apply". And sees a list based on the selected filters.
But the applied filters are not saved for subsequent filtrations. And the next time user click on the "filters" button, the user cannot continue working with them from the last moment. He has to choose all the filters again.
How to make the filters to be saved and the user to continue working with the filters based on the previous selection?
filter_dialog.dart
class FilterDialog extends StatefulWidget {
final void Function(Map<String, List<String>?>) onApplyFilters;
const FilterDialog({Key? key, required this.onApplyFilters}) : super(key: key);
#override
State<FilterDialog> createState() => _FilterDialogState();
}
class _FilterDialogState extends State<FilterDialog> {
Map<String, List<String>?> filters = {};
void _handleCheckFilter(bool checked, String key, String value) {
final currentFilters = filters[key] ?? [];
if(checked) {
currentFilters.add(value);
} else {
currentFilters.remove(value);
}
filters[key] = currentFilters;
}
#override
.......
main_page.dart
class MainPage extends StatefulWidget {
const MainPage({Key? key}) : super(key: key);
#override
State<MainPage> createState() => _MainPageState();
}
class _MainPageState extends State<MainPage> {
List<Phone> filteredPhones = phoneList;
void _filter(Map<String, List<String>?> filters) {
setState(() {
filteredPhones = phoneList;
filters.forEach((key, value) {
if((value ?? []).isNotEmpty) {
filteredPhones = filteredPhones.where((phone) {
switch(key) {
case 'brand':
return value!.contains(phone.brand);
case 'version_OS':
return value!.contains(phone.version_OS);
case 'operation_system':
return value!.contains(phone.operation_system);
default:
return false;
}
}).toList();
}
});
});
}
#override
....
}
class Filter {
String name;
bool Function(Phone) filterFn;
Filter({required this.name, required this.filterFn});
}
custom_checkbox_tile.dart
class CustomCheckboxTile extends StatefulWidget {
final String label;
final void Function(bool)? onChange;
const CustomCheckboxTile({Key? key, required this.label, this.onChange}) : super(key: key);
#override
State<CustomCheckboxTile> createState() => _CustomCheckboxTileState();
}
class _CustomCheckboxTileState extends State<CustomCheckboxTile> {
bool checked = false;
#override
Widget build(BuildContext context) {
return Row(
children: [
Checkbox(
visualDensity: VisualDensity.compact,
value: checked,
onChanged: (_) {
setState(() {
checked = !checked;
if(widget.onChange != null) {
widget.onChange!(checked);
}
});
},
),
Text(widget.label),
],
);
}
}
its not simple to answer your qustion.
More changes should made.
I'm done it all.
Please Check Github

How to access the variable from one class to other in flutter

I want to access the variable UniversityId in the class of _HomePageState
class showDetailOfUniversity extends StatelessWidget {
final String UniversityId;
showDetailOfUniversity({Key key, #required this.UniversityId}) : super(key:
key);
#override
Widget build(BuildContext context)
{
return (
HomePage()
);
}
}
class HomePage extends StatefulWidget {
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
//
var temp2 = showDetailOfUniversity();
var temp = temp2.getUniversityId;
/// here i want to access the code but failed
}
The problem here is that you created another instance of showDetailOfUniversity that will have another values for its members. You did not initialize String UniversityId so its value is null untill you set it.
So when you called showDetailOfUniversity() in temp, the value of String UniversityId in this instance is null since there was no value given in this particular instance.
You can pass the String UniversityId in the constructor of the StatefulWidget like this:
class ShowDetailOfUniversity extends StatelessWidget {
final String universityId;
ShowDetailOfUniversity({Key key, #required this.universityId})
: super(key: key);
#override
Widget build(BuildContext context) {
return HomePage(universityId: universityId);
}
}
class HomePage extends StatefulWidget {
final String universityId;
const HomePage({Key key, this.universityId}) : super(key: key);
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
var universityId;
#override
void initState() {
super.initState();
universityId = widget.universityId;
}
#override
Widget build(BuildContext context) {
// TODO: implement build
return Text(universityId);
}
}
Solution for your code:
var temp2 = showDetailOfUniversity(UniversityId: university_id);
var temp = temp2.UniversityId; //this will return university_id

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