How to Pass Value from a Statefull Widget to a Contoller while redirecting to Screen View in Flutter and Dart - flutter

I am Developing a Quiz.
Where User Choses Subject > Chapter
Then from Chapter Info Page > Start Quiz.
I am able to fetch the Subject ID and Chapter ID and When the User Clicks on Start Quiz Button Present in Chapter Info
Quiz Starts
Quiz is based on MVC Pattern
Here I am Redirecting user to Quiz Screen from Chapter Info page
How to access Value from Statefull widget ChapterInfo to a QuizContoller
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => TopicWiseQuizScreen(quizSubjectID:subjectId,CatID: catId),
),
);
},
class TopicWiseQuizScreen extends StatelessWidget {
const TopicWiseQuizScreen({super.key, required quizSubjectID, required int CatID});
#override
Widget build(BuildContext context) {
TopicWiseQuestionController _controller = Get.put(TopicWiseQuestionController());
return Scaffold()}}
class TopicWiseQuestionController extends GetxController
with SingleGetTickerProviderMixin {
late final int subID;
late final int catID;

After passing the values as parameters to your stateful widget you can access them by:
widget.quizSubjectID;
widget.catID;

You should never create a StatefulWidget widget while using GetX because in GetX you can basically do anything using StatelessWidget.
But if you really want to pass a value to controller from StatefulWidget then you can assign those values in while navigating to the view like this:
Controller
class DemoController extends GetxController {
DemoController();
Rx<int> quizSubjectID = 0.obs;
Rx<int> catID = 0.obs;
}
Now you can set the controller values before navigating to the other screen like this:
View
onPressed: () {
final logic = Get.put(DemoController());
logic.quizSubjectID.value = subjectId;
logic.catID.value = catId;
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => TopicWiseQuizScreen(quizSubjectID:subjectId,CatID: catId),
),
);
},
But try to use StatelessWidgets and pass data using arguments in GetX. There's also documentation available on pub.dev GetX package.

Related

How to acces parameter value from constructor in flutter?

I'm having trouble with accessing the value of a parameter from a constructor in my code. I access to this page from another one where I get the value of the parameter:
final route = MaterialPageRoute(
builder: (context) => AnadirJugadores(idPagina: respuesta['id'],));
Navigator.push(context, route);
This is the code of AnadirJugadores:
class AnadirJugadores extends StatefulWidget {
final String idPagina;
AnadirJugadores({required this.idPagina });
String cogerID() {
return this.idPagina;
}
#override
State<AnadirJugadores> createState() => _AnadirJugadoresState();
}
class _AnadirJugadoresState extends State<AnadirJugadores> {
#override
Widget build(BuildContext context) {
.... more code
ElevatedButton(
child: Text(idPartida), // this is the line of the error
onPressed: () {
final data = ClipboardData(text: '25342756374');
Clipboard.setData(data);
},
),
I'm trying to access the value of idPagina. How could I do that?
Thanks in advance.
When using stateful widgets you need to use widget to access the parameters.
child: Text(widget.idPartida),
In StatefulWidget your constructor exists in upper class (it's not in State class), so to access data in this constructor in your state class you should do this:
ElevatedButton(child: Text(widget.idPartida), ...),

Access Providers from Dialogs for Flutter hooks

I am new to Flutter hooks and riverpod
Basically I have a provider that stores the list of books in a book shelf.
class BookList extends StateNotifier<List<BookModel>> {
BookList() : super([]);
void setBookList(List<BookModel> bookList) =>
{state = bookList};
}
final bookListProvider = StateNotifierProvider<BookList>((_) => BookList());
Then I have a page which display the books and a create button which will shows the create a new book dialog:
class BookShelfPage extends HookWidget {
#override
Widget build(BuildContext context) {
final bookList = useProvider(bookListProvider.state);
useEffect(() {
//API to get list of books
context.read(bookListProvider).setBookList(//data from API);
},[]);
final Function() onCreateBookButtonClicked = () {
showDialog(
context: context,
builder: (context) => ProviderScope(
child: (new BookCreateDialog())));
};
//Data is available for this
print("book list length 1: " + bookList.length.toString());
}
However, I am unable to access the provider values in the dialog:
class BookCreateDialog extends HookWidget {
#override
Widget build(BuildContext context) {
final bookList = useProvider(bookListProvider.state);
//Data is not available for this
print("book list length 2: " + bookList.length.toString());
}
}
Things to note:
I have a ProviderScope wrapping my application.
I have no problems persist or access the providers across different PAGES or any child widget that resides on the PAGES but I am not able to access the provider values from dialogs.
Of course, I can pass the providers' values as parameters to the dialogs but I would like to know if there is any way that I can avoid this as I got a lot values to get from providers.
May I know how to fix this? Much thanks!
You only want to use ProviderScope in two cases. The first is wrapping your app as you mentioned. The other case is when using ScopedProvider.
What you're essentially doing here:
builder: (context) => ProviderScope(child: BookCreateDialog());
is creating a new scope where the value of your StateNotifierProvider is not available (as that value lies within the ProviderScope at the root of your app).
Remove that ProviderScope and you should get the results you are expecting.

how to navigate data between two screens in flutter?

I have homeScreen, which every another screen returns to it.
and one of the screens have parameters from TextField, which I need in the homeScreen, how I can navigate these parameters to the home?
NOTE: when I use constructor, the other screens show an error in the line that navigate to Home because there is no parameters.
You can either use an optional parameter in your constructor:
Homepage({String textfield});
and use it on your Homepage (don't forget that this value is nullable)
Or you need to use some kind of state management with ValueNotifiers
You can pass data using parameters
class XYZ extends StatelessWidget {
final TextEditingController textController = TextEditingController();
void navigationFunction() {
//send the data from XYZ to HomePage
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => HomePage(textValue: textController.text)),
);
}
}
class HomePage extends StatelessWidget {
const HomePage({this.textValue});
final String textValue; //use this textValue in HomePage
#override
Widget build(BuildContext context) {
return Scaffold();
}
}

How do i access a varible from another class in Flutter

I'm making my first flutter app.
it asks for some information then when you click a button it shows the information you entered on another page, I wanted to ask. How do I get a variable from another class?
so I can use the information entered on another page
It seems like you want to pass some data while navigating to another page. If I'm not wrong You should define a variable in the destination like this:
class NewPage extends StatefulWidget {
final int someInt;
NewPage({Key key, this.someInt}) : super(key: key);
#override
_NewPageState createState() => _NewPageState();
}
class _NewPageState extends State<NewPage> {
#override
Widget build(BuildContext context) {
return Container(
child: Container(child: Text("${widget.someInt}"),),
);
}
}
In the above code I passed someInt to NewPage class.
In the first page you should navigate like this:
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => NewPage(someInt: 293,),
));
put above code in the onPressed and pass the data with constructor.

Dart & Flutter - Passing data across screens. NoSuchMethodError being caused by widget within MaterialPageRoute()

I tried passing data from a filter page to the home page, but keep getting the following error.
Error message on console - NoSuchMethodError being caused by widget within MaterialPageRoute()
//Radio button values to select user's gender on Filter Page
enum PrayditatorGender { Female, Male }
PrayditatorGender pGender;
//Radio button values to select Prayditation category on Filter Page
enum PrayditationFilter {
All,
Family,
Fellowship,
GodlyWisdom,
GoodSuccess,
HealthAndSafety,
}
PrayditationFilter pFilter = PrayditationFilter.All;
//Code to push the data from Filter Page to Home Page
Navigator.push(context, MaterialPageRoute(
builder: (context) {
PrayditatorHomePage(
pGender: pGender,
pFilter: pFilter
)
));
//Code to handle the data on Home Page
class PrayditatorHomePage extends StatefulWidget {
final PrayditatorGender pGender;
final PrayditationFilter pFilter;
PrayditatorHomePage({this.pGender, this.pFilter});
#override
_PrayditatorHomePageState createState() => _PrayditatorHomePageState();
}
class _PrayditatorHomePageState extends State<PrayditatorHomePage> {
#override
Widget build(BuildContext context) {}
Your syntax is wrong, you're not supposed to be having this issue, this code worked with no issues:
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => PrayditatorHomePage(
pGender: pGender,
pFilter: pFilter,
),
),
);
Thank you all for taking time to view/comment. Bug has been busted and code working effectively!
Syntax was all correct, however, a static parameter was inappropriately put in the place meant for a dynamic parameter. After all, lessons learned.